$all_sections = array();
$raw_sections = $tpls->list_sections();
foreach ($raw_sections as $value) {
    $all_sections[] = $value['code'];
}
if ($id == 0) {
    $section = $_POST['tpl_section'];
    $section = substr($section, 0, 3);
    $tpl = new stdClass();
    $tpl->section = $section;
    $tpl->preinstalled = 0;
    $tpl->default = 0;
    $tpl->name = 'New Template';
    $tpl->description = '';
} else {
    $tpl = wp_gdtpl_get_template($id);
    if (is_object($tpl)) {
        $section = $tpl->section;
        $elements = unserialize($tpl->elements);
        $dependencies = unserialize($tpl->dependencies);
    }
}
if (!in_array($section, $all_sections)) {
    echo '<h3>' . __("Your request is not valid.") . '</h3>';
} else {
    if ($mode == 'copy') {
        $id = 0;
        $tpl->name = 'New Template';
        $tpl->description = '';
    } else {
        if ($mode == 'edit' && $tpl->preinstalled == "1") {
 function gdTemplateRender($id, $section)
 {
     $this->dep = $this->tag = array();
     $this->tpl = wp_gdtpl_get_template($id);
     if (!is_object($this->tpl) || $this->tpl->section != $section) {
         $t = gdTemplateDB::get_templates($section, true, true);
         $id = $t->template_id;
         $this->tpl = wp_gdtpl_get_template($id);
     }
     $dependencies = unserialize($this->tpl->dependencies);
     if (is_array($dependencies)) {
         foreach ($dependencies as $key => $value) {
             $this->dep[$key] = new gdTemplateRender($value, $key);
         }
     }
     $this->elm = unserialize($this->tpl->elements);
     if (is_array($this->elm)) {
         foreach ($this->elm as $key => $value) {
             $this->tag[$key] = array();
             $this->custom[$key] = array();
             $this->custom[$key] = wp_get_custom_tags($value);
             preg_match_all('(%.+?%)', $value, $matches, PREG_PATTERN_ORDER);
             if (is_array($matches[0])) {
                 $this->tag[$key] = $matches[0];
             }
         }
     }
 }