<?php
/**
 * 
 * @file class_template.php
 * @copyright (c) 2005 - 2007 eifr.com
 * @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
 * eifr is free software
 */

require_once(EIFR_ROOT . 'libraries/template.php');

class ComTemplate {
    function deleteRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'delete'); //have delete authority ?
        global $selectid, $selectValue;
        if ($selectValue) $selectid = $selectValue;
        $program_filename = dbGetFieldValue(TB_TEMPLATE, 'program_filename', "id =" . $selectid . "");
        if ($program_filename == 'channel.php') {
            $sql = "update " . TB_CHANNEL . " set template_id='0' where template_id=" . $selectid . "";
            $rs = $db -> Execute($sql);
        } 

        if ($program_filename == 'article.php') {
            $sql = "update " . TB_ARTICLE . " set template_id='0' where template_id=" . $selectid . "";
            $rs = $db -> Execute($sql);
        } 

        //! also need to update layout_id for article, ad, link and user

        $sql = "DELETE FROM " . TB_TEMPLATE . " WHERE id=" . $selectid . "";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showMsg($lang['delSuccess'], 'success', DIR_INSTALL . 'admin/' . $url);
        } else {
            Common::showErrorMsg($lang['delFail']);
        } 
    } 

    function deleteRecords_layout() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'delete'); //have delete authority ?
        global $selectid, $selectValue, $template_layout_id;

        //! also need to update layou_id for article, ad, link and user

        $sql = "DELETE FROM " . TB_TEMPLATE_LAYOUT . " WHERE id='" . $template_layout_id . "'";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showMsg($lang['delSuccess'], 'success', DIR_INSTALL . 'admin/' . $url . '?act=edit_layout&selectid=' . $selectid);
        } else {
            Common::showErrorMsg($lang['delFail']);
        } 
    } 

    function addRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?	
        global $title, $template_filename, $program_filename, $intro, $flag; 
        // Common::checkEditDataIsExist(TB_TEMPLATE,'template_filename',$template_filename);
        $id = dbGetMaxValue1(TB_TEMPLATE, 'id');
        $ordernum = dbGetMaxValue1(TB_TEMPLATE, 'ordernum');
        $title = sTextEncode($title);
        $sql = "insert into " . TB_TEMPLATE . " (id,title,template_filename,program_filename,intro,ordernum,flag) values('$id','$title','$template_filename','$program_filename','$intro','$ordernum','$flag')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['addSuccess'], 'template_edit.php', 'template_edit.php?act=edit&selectid=' . $id, 'template.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

    function addRecords_layout() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?	
        global $template_id, $title, $layout_code, $intro, $sql_select, $status, $type;
        Common::checkEditDataIsExist(TB_TEMPLATE_LAYOUT, 'layout_code', $layout_code, '', "template_id='$template_id'");
        $id = dbGetMaxValue1(TB_TEMPLATE_LAYOUT, 'id');
        $ordernum = dbGetMaxValue1(TB_TEMPLATE_LAYOUT, 'ordernum', "template_id='$template_id'");
        $title = sTextEncode($title);
        $sql = "insert into " . TB_TEMPLATE_LAYOUT . " (id,title,layout_code,intro,sql_select,status,type,ordernum,template_id) values('$id','$title','$layout_code','$intro','$sql_select','$status','$type','$ordernum','$template_id')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showMsg($lang['addSuccess'], 'success', '?act=add_layout&selectid=' . $template_id);
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

    function editRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        global $selectid, $selectValue, $title, $template_filename, $template_filename_old, $program_filename, $intro, $flag;

        if ($selectValue) $selectid = $selectValue; 
        // Common::checkEditDataIsExist(TB_TEMPLATE,'template_filename',$template_filename,$template_filename_old);
        $title = sTextEncode($title);
        $sql = "update " . TB_TEMPLATE . " set title='$title', template_filename='$template_filename', program_filename='$program_filename', intro='$intro', flag='$flag' where id=" . $selectid . "";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'template_edit.php', 'template_edit.php?act=edit&selectid=' . $selectid, 'template.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
        $rs -> Close();
    } 

    function editRecords_layout() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        global $selectid, $template_id, $template_layout_id, $title, $layout_code, $layout_code_old, $intro, $sql_select, $status, $type;
        Common::checkEditDataIsExist(TB_TEMPLATE_LAYOUT, 'layout_code', $layout_code, $layout_code_old, "template_id='$template_id'");
        $id = dbGetMaxValue1(TB_TEMPLATE_LAYOUT, 'id');
        $ordernum = dbGetMaxValue1(TB_TEMPLATE_LAYOUT, 'ordernum', "template_id='$template_id'");
        $title = sTextEncode($title);
        if ($intro != '') $intro = HTMLEncode2($intro);
        $sql = "update " . TB_TEMPLATE_LAYOUT . " set title='$title', layout_code='$layout_code', intro='$intro', sql_select='$sql_select', status='$status', type='$type' where id=" . $template_layout_id . "";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showMsg($lang['saveSuccess'], 'success', DIR_INSTALL . 'admin/' . $url . '?act=edit_layout&selectid=' . $template_id . '&template_layout_id=' . $template_layout_id);
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
        $rs -> Close();
    } 

    function orderbyRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        global $id, $act;

        if ($id == '') return;

        $rs_1 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE . " where ordernum<" . $rs_1 -> fields['ordernum'] . "  order by ordernum desc limit 1");
        } 
        if ($act == 'down') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE . " where  ordernum>" . $rs_1 -> fields['ordernum'] . "  order by ordernum asc limit 1");
        } 
        $up_1 = $db -> Execute("update " . TB_TEMPLATE . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_TEMPLATE . " set ordernum='" . $rs_1 -> fields['ordernum'] . "' where id='" . $rs_2 -> fields['id'] . "'");

        $rs_1 -> Close();
        $rs_2 -> Close();
        $up_1 -> Close();
        $up_2 -> Close();
        Common::showMsg('', '', DIR_INSTALL . 'admin/' . $url);
    } 

    function orderbyRecords_layout() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        global $id, $template_id, $act;

        if ($id == '') return;

        $rs_1 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE_LAYOUT . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE_LAYOUT . " where ordernum<" . $rs_1 -> fields['ordernum'] . " and template_id='$template_id'  order by ordernum desc limit 1");
        } 
        if ($act == 'down') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_TEMPLATE_LAYOUT . " where  ordernum>" . $rs_1 -> fields['ordernum'] . " and template_id='$template_id'  order by ordernum asc limit 1");
        } 
        $up_1 = $db -> Execute("update " . TB_TEMPLATE_LAYOUT . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_TEMPLATE_LAYOUT . " set ordernum='" . $rs_1 -> fields['ordernum'] . "' where id='" . $rs_2 -> fields['id'] . "'");

        $rs_1 -> Close();
        $rs_2 -> Close();
        $up_1 -> Close();
        $up_2 -> Close();
        Common::showMsg('', '', DIR_INSTALL . 'admin/' . $url . '?act=add_layout&selectid=' . $template_id);
    } 

    function layout_template() {
        global $db, $url;
        $isedit = Common::checkAdminAuth($url, 'edit');
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // show list---start---
        $where_sql = ' where 1 ';
        if (!Common::checkSysAdmin()) {
            $where_sql .= ' and is_delete=0 ';
        } 
        $sql = "select * from " . TB_TEMPLATE . " $where_sql order by ordernum asc "; 
        // echo $sql;
        $clPages = new Pages();
        $clPages -> query_sql = $sql;
        $aryResult = $clPages -> Execute();
        $rs = $aryResult[0];
        $intList = $aryResult[2];

        if ($intList > 0) {
            $num = 0;
            while (!$rs -> EOF) {
                $num++;
                if (!$isedit) {
                    $orderby = $rs -> fields['ordernum'];
                } else {
                    $orderby = Common::createOrderBy('', '&id=' . $rs -> fields['id'] . '');
                } 

                $clTemplate -> assign_block_vars('ListTemplate', array('num' => $num,
                        'id' => $rs -> fields['id'],
                        'title' => $rs -> fields['title'],
                        'template_filename' => $rs -> fields['template_filename'],
                        'program_filename' => $rs -> fields['program_filename'],
                        'orderby' => $orderby,
                        'flag' => $rs -> fields['flag']? Common::createFlagTxt('default') : Common::createFlagTxt('open')
                        ));

                $rs -> MoveNext();
            } 
        } 
        $rs -> Close(); 
        // show list---end---
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'template_suffix' => SYS_TEMPLATE_SUFFIX,
                'toolbar' => Common::createToolbar($url, 'add', 'template_edit.php') . Common::createToolbar($url, 'edit', 'template_edit.php?act=edit') . Common::createToolbar($url, 'delete', 'template.php?act=delete') . Common::createToolbar($url, 'preview', 'template_view.php'),
                'pagenext' => $aryResult[3]
                ));

        $clTemplate -> set_filenames(array('body' => 'template.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_select() {
        global $db, $url;
        global $pfile;

        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // show list---start---
        $strsql = '';
        if ($pfile != '') {
            // echo $pfile;
            $pfile_list = "''";
            $pfile_arr = explode(',', $pfile);
            $pfile_arr_count = count($pfile_arr); 
            // echo $pfile_arr[1];
            for($i = 0; $i < $pfile_arr_count; $i++) {
                $pfile_list .= ",'" . $pfile_arr[$i] . "'";
            } 
            // echo $pfile_list;
            $strsql = " and program_filename in ($pfile_list) ";
        } 

        if (!Common::checkSysAdmin()) {
            $strsql .= ' and is_delete=0 ';
        } 

        $sql = "select * from " . TB_TEMPLATE . " where flag<3 " . $strsql . " order by ordernum asc "; 
        // echo $sql;
        $rs = $db -> Execute($sql);
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $tr_css = 'list_sub_tr_bg';
            $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_tr_bg\'" onMouseOut="this.className=\'list_sub_tr_bg\'"';

            $clTemplate -> assign_block_vars('ListTemplate', array('num' => $num,
                    'id' => $rs -> fields['id'],
                    'title' => $rs -> fields['title'],
                    'template_filename' => $rs -> fields['template_filename'],
                    'program_filename' => $rs -> fields['program_filename'],
                    'tr_css' => $tr_css,
                    'tr_onmouse' => $tr_onmouse
                    ));

            $rs -> MoveNext();
        } 

        $rs -> Close(); 
        // show list---end---
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url)
                ));

        $clTemplate -> set_filenames(array('body' => 'template_select.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_layout_select() {
        global $db, $lang, $url, $act, $type;
        $is_ajax = false;
        $is_ajax_str = 'false';
        $btn_value = $lang['select'];
        if ($act == 'insert') $btn_value = $lang['insert'];

        if (strtoupper(SYS_CHARSET) != "UTF-8") {
            if (!function_exists("iconv")) {
                $is_ajax = false;
                $is_ajax_str = 'false';
            } 
        } 

        $clTemplate = new Template(getAdminTemplateDir($url));

        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'is_ajax' => $is_ajax_str,
                'type' => $type,
                'btn_value' => $btn_value
                )); 
                
        $tplArr = $this -> getTemplateLayoutByType($type);
        
        foreach ($tplArr as $row)
        {
            if(isset($row['eifrtf_layout'])) {
                $clTemplate -> assign_block_vars('ListTemplate', array(
                    'id' => $row['id'],
                    'title' => $row['title'],
                    'template_filename' => $row['template_filename'],
                    'program_filename' => $row['program_filename'],
                    'td_css' => 'list_parent_td_bg',
                    'td_onmouse' => 'onMouseOver="this.className=\'list_mouseover_td_bg\'" onMouseOut="this.className=\'list_parent_td_bg\'"'
                    ));
                if (!$is_ajax) {
                    $num = 0;
                    foreach ($row['eifrtf_layout'] as $row2)
                    {
                        $num++;
                        $clTemplate -> assign_block_vars('ListTemplate.ListLayoutInfo', array(
                            'num' => $num,
                            'id' => $row2['id'],
                            'title' => $row2['title'],
                            'intro' => $row2['intro']
                            ));
                    }
                }
            }
        }
        
        // show list---end---
        $clTemplate -> set_filenames(array('body' => 'template_layout_select.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_add() {
        global $db, $url;
        Common::checkAdminExeAuth($url, 'add');

        global $selectid, $selectValue;

        $toolbar = Common::createToolbar($url, 'save', 'template_edit.php?act=save');
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'display_edit' => 'none',
                'toolbar' => $toolbar
                ));

        $clTemplate -> assign_vars(array('selectid' => '',
                'title' => '',
                'template_filename' => '',
                'template_filename_old' => '',
                'template_suffix' => SYS_TEMPLATE_SUFFIX,
                'program_filename' => '',
                'intro' => '',
                'flag' => Common::creatFlagCheck('flag', '0', 'open', true) . Common::creatFlagCheck('flag', '1', 'default', false)
                ));

        $clTemplate -> set_filenames(array('body' => 'template_edit.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_edit() {
        global $db, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
        global $selectid, $selectValue;

        $toolbar = Common::createToolbar($url, 'save', 'template_edit.php?act=save') . Common::createToolbar($url, 'delete', 'template.php?act=delete');
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'display_edit' => '',
                'toolbar' => $toolbar
                ));

        if ($selectValue) $selectid = $selectValue;

        $sql = "select * from " . TB_TEMPLATE . " where id=" . $selectid . "";
        $rs = $db -> Execute($sql);
        if (!$rs -> EOF) {
            // data
            $clTemplate -> assign_vars(array('selectid' => $selectid,
                    'title' => $rs -> fields['title'],
                    'template_filename' => $rs -> fields['template_filename'],
                    'template_filename_old' => $rs -> fields['template_filename'],
                    'template_suffix' => SYS_TEMPLATE_SUFFIX,
                    'program_filename' => $rs -> fields['program_filename'],
                    'intro' => $rs -> fields['intro'],
                    'flag' => Common::creatFlagCheck('flag', '0', 'open', $rs -> fields['flag'] == 0 ? true:false) . Common::creatFlagCheck('flag', '1', 'default', $rs -> fields['flag'] == 1 ? true:false)
                    ));
        } 
        $rs -> Close();

        $clTemplate -> set_filenames(array('body' => 'template_edit.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_layout_edit() {
        global $db, $url, $act;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
        $isdelete = Common::checkAdminAuth($url, 'delete');

        global $selectid, $selectValue, $template_layout_id;

        if ($selectValue) $selectid = $selectValue;

        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url)
                ));

        /**
         * ---ListLayout---start---
         */

        $sql = "select * from " . TB_TEMPLATE_LAYOUT . " where template_id='$selectid' order by ordernum asc ";
        $rs = $db -> Execute($sql);
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $id = $rs -> fields['id'];

            $operate_btn = Common::createButton('modify', 'template_edit.php?act=edit_layout&selectid=' . $selectid . '&template_layout_id=' . $id . '');
            if ($isdelete) {
                $operate_btn .= Common::createButton('delete', 'template_edit.php?act=delete_layout&selectid=' . $selectid . '&template_layout_id=' . $id . '', true);
            } 
            $operate_btn .= Common::createButton('preview', '', false, '', "winOpen('template_view.php?selectid=" . $selectid . "&layout_id=" . $id . "')");

            $title_style = '';
            if ($template_layout_id == $rs -> fields['id']) $title_style = 'title_selected';

            $clTemplate -> assign_block_vars('ListLayout', array('id' => $id,
                    'num' => $num,
                    'title' => $rs -> fields['title'],
                    'intro' => $rs -> fields['intro'],
                    'status' => Common::createStatusTxt($rs -> fields['status']),
                    'layout_code' => $rs -> fields['layout_code'],
                    'type' => $this -> createTypeTxt($rs -> fields['type']),
                    'orderby' => Common::createOrderBy('', '&id=' . $id . '&template_id=' . $selectid),
                    'title_style' => $title_style,
                    'operate_btn' => $operate_btn
                    ));
            $rs -> MoveNext();
        } 
        $rs -> Close();
        /**
         * ---ListLayout---end---
         */

        if ($act == 'edit_layout' && $template_layout_id != '') { // edit
            $toolbar = Common::createToolbar($url, 'save', 'template_edit.php?act=save_edit_layout');
            $toolbar .= Common::createButton('add', 'template_edit.php?act=add_layout&selectid=' . $selectid . '', false, 'add');
            $is_display = '';
            $sql = "select * from " . TB_TEMPLATE_LAYOUT . " where id=" . $template_layout_id . "";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                // data
                $title = $rs -> fields['title'];
                $layout_code = $rs -> fields['layout_code'];
                $layout_code_old = $layout_code;
                $intro = $rs -> fields['intro'];
                $status = Common::creatStatusRadio($rs -> fields['status']);
                $sql_select = $rs -> fields['sql_select'];
                $template_id = $rs -> fields['template_id'];
                $layout_type = $this -> createTypeRadio($rs -> fields['type']);
            } 
            $rs -> Close();
        } else { // add
            $toolbar = Common::createToolbar($url, 'save', 'template_edit.php?act=save_add_layout');
            $is_display = 'none';
            $title = '';
            $layout_code = '';
            $layout_code_old = '';
            $intro = '';
            $status = Common::creatStatusRadio(0);
            $sql_select = '';
            $template_id = $selectid;
            $template_layout_id = dbGetMaxValue1(TB_TEMPLATE_LAYOUT, 'id');
            $layout_type = $this -> createTypeRadio(0);
        } 

        $clTemplate -> assign_vars(array('selectid' => $selectid,
                'title' => $title,
                'layout_code' => $layout_code,
                'layout_code_old' => $layout_code_old,
                'intro' => $intro,
                'status' => $status,
                'sql_select' => dQuotEncode($sql_select),
                'template_id' => $template_id,
                'template_layout_id' => $template_layout_id,
                'layout_type' => $layout_type,
                'toolbar' => $toolbar,
                'is_display' => $is_display
                ));

        $clTemplate -> set_filenames(array('body' => 'template_layout_edit.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function layout_template_view() {
        global $db, $url;

        global $selectid, $selectValue, $layout_id;
        if ($selectValue) $selectid = $selectValue;
        $layout_code = '';
        if ($layout_id != '') {
            $selectid = dbGetFieldValue(TB_TEMPLATE_LAYOUT, 'template_id', "id='" . $layout_id . "'");
            $layout_code = dbGetFieldValue(TB_TEMPLATE_LAYOUT, 'layout_code', "id='" . $layout_id . "'");
        } 

        $tplfile = dbGetFieldValue(TB_TEMPLATE, 'template_filename', "id='" . $selectid . "'");

        $layout_id_list = "''";
        $sql = "select * from " . TB_TEMPLATE_LAYOUT . " where template_id='$selectid' order by ordernum asc ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $layout_id_list .= ",'" . $rs -> fields['layout_code'] . "'";
            $rs -> MoveNext();
        } 
        $rs -> Close();

        $head_js = "<script language='javascript' src='" . DIR_INSTALL . 'js/' . SYS_DEFAULT_STYLE . ".js'></script>\n";
        $layout_foot_js = "<script language='javascript' src='" . SYS_ADMIN_STYLE_PATH . "js/foot.js'></script>\n";
        $layout_foot_js .= "<script language='javascript'>\n";
        $layout_foot_js .= "var layoutArr=[$layout_id_list];\n";
        $layout_foot_js .= "showSelectLayoutId(layoutArr,'$layout_code');\n";
        $layout_foot_js .= "</script>\n";

        $clTemplate = new Template('../../' . DIR_TEMPLATE_NAME . '/' . SYS_DEFAULT_STYLE); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'sys_weburl' => SYS_WEBURL,
                'soft_name' => SOFT_NAME,
                'soft_version' => SOFT_VERSION,
                'soft_copyright' => SOFT_COPYRIGHT,
                'soft_weburl' => SOFT_WEBURL,
                'head_js' => $head_js,
                'foot_js' => $layout_foot_js
                ));

        $clTemplate -> set_filenames(array('body' => $tplfile));
        $clTemplate -> pparse("body");
    } 

    public static function getTemplateById($id) {
        $rtn = array();
        $cacheHelper = new CCacheHelper('db_template');
        $tpl = $cacheHelper -> getCache();
        if ($tpl) {
            foreach($tpl as $val) {
                if ($val['id'] == $id) {
                    $rtn = $val;
                    break;
                } 
            } 
        } else {
            $sql = "select * from " . TB_TEMPLATE . " where id=" . $id ;
            $rtn = dbGetRecord1($sql);
        } 

        return $rtn;
    } 
 
    public static function getTemplateByLayoutId($id) {
        $rtn = array();
        $cacheHelper = new CCacheHelper('db_template');
        $tpl = $cacheHelper -> getCache();
        if ($tpl) {
            foreach($tpl as $row) {
                if (isset($row['eifrtf_layout'])) {
                    if(array_key_exists($id, $row['eifrtf_layout'])) {
                        $rtn = $row;
                        break;
                    }
                } 
            }
        } else {
            $template_id = dbGetFieldValue(TB_TEMPLATE_LAYOUT, 'template_id', "id='" . $id . "'");
            $sql = "select * from " . TB_TEMPLATE . " where id=" . $template_id ;
            $rtn = dbGetRecord1($sql);
        } 

        return $rtn;
    } 
    
    public static function getTemplateLayoutById($id) {
        $rtn = array();
        $cacheHelper = new CCacheHelper('db_template');
        $tpl = $cacheHelper -> getCache();
        if ($tpl) {
            foreach($tpl as $row) {
                if (isset($row['eifrtf_layout'])) {
                    if(array_key_exists($id, $row['eifrtf_layout'])) {
                        $rtn = $row['eifrtf_layout'][$id];
                        break;
                    }
                } 
            } 
        } else {
            $sql = "select * from " . TB_TEMPLATE_LAYOUT . " where id=" . $id ;
            $rtn = dbGetRecord1($sql);
        } 

        return $rtn;
    }
    
    function getTemplateLayoutByType($type) {
        $rtn = array();
        $sql = "select * from " . TB_TEMPLATE . " where is_delete=0 order by ordernum asc ";
        $tpldata = dbGetRecordn($sql);
        foreach($tpldata as $row) {
            $id = $row['id'];

            // TB_TEMPLATE_LAYOUT
            $strsql = '';
            if ($type != '') $strsql = " and type='$type' ";
            $sql_sub = "select * from " . TB_TEMPLATE_LAYOUT . " where status=0 and template_id='$id' " . $strsql . " order by ordernum asc ";
            
            $layoutdata = dbGetRecordn($sql_sub);
            if ($layoutdata) {
                $row['eifrtf_layout'] = array();
                foreach($layoutdata as $row2) {
                    $row['eifrtf_layout'][] = array(
                        'id' => $row2['id'],
                        'layout_code' => $row2['layout_code'],
                        'title' => $row2['title'],
                        'intro' => $row2['intro'],
                        'sql_select' => $row2['sql_select'],
                        'type' => $row2['type'],
                    );
                } 
            } 
            
            $rtn[] = $row;
        } 

        return $rtn;
    } 
    
    function getTemplateLayout() {
        $rtn = array();

        $cacheHelper = new CCacheHelper('db_template');
        $rtn = $cacheHelper -> getCache();
        if ($rtn !== false) {
            Log_v(__FILE__, __LINE__, 'getTemplateLayout from cache');
            return $rtn;
        } 

        $sql = "select id, title, template_filename, program_filename from " . TB_TEMPLATE . " where is_delete=0 order by ordernum asc ";
        $tpldata = dbGetRecordn($sql);
        foreach($tpldata as $row) {
            $id = $row['id'];
            $rtn[$id] = array('id' => $id,
                'title' => $row['title'],
                'template_filename' => $row['template_filename'],
                'program_filename' => $row['program_filename'],
                ); 
            // TB_TEMPLATE_LAYOUT
            $sql_sub = "select id, type, layout_code, title, intro, sql_select from " . TB_TEMPLATE_LAYOUT . " where template_id='$id' order by ordernum asc ";
            $layoutdata = dbGetRecordn($sql_sub);
            if ($layoutdata) {
                $rtn[$id]['eifrtf_layout'] = array();
                foreach($layoutdata as $row) {
                    $rtn[$id]['eifrtf_layout'][$row['id']] = array(
                        'id' => $row['id'],
                        'layout_code' => $row['layout_code'],
                        'title' => $row['title'],
                        'intro' => $row['intro'],
                        'sql_select' => $row['sql_select'],
                        'type' => $row['type'],
                    );
                } 
            } 
        } 

        return $rtn;
    } 

    function genCache() {
        $cacheHelper = new CCacheHelper('db_template');
        $cacheHelper -> deleteCache();
        $cachedata = $this -> getTemplateLayout();
        $cacheHelper -> writeCache($cachedata);
    } 

    /**
     * ---createTypeRadio---
     * 
     * @param string $type 
     * @return string 
     */
    function createTypeRadio($type = '') {
        global $lang;
        $rtn = '';
        $type_len = count($lang['layout_type_arr']);
        if (!is_numeric($type)) $type = -1;
        for($i = 0; $i < $type_len;$i++) {
            $e_s = '';
            if ($i == $type) {
                $e_s = ' checked';
                $type = '';
            } 
            $rtn .= "<input type='radio' name='type' value='" . $i . "' " . $e_s . " onclick='setShowType()'>" . $lang['layout_type_arr'][$i] . "&nbsp;\n";
        } 

        return $rtn;
    } 

    /**
     * ---createTypeTxt---
     * 
     * @param string $flag 
     * @return string 
     */
    function createTypeTxt($type = '') {
        global $lang;
        $rtn = '';
        $type_len = count($lang['layout_type_arr']);
        if (!is_numeric($type)) $type = -1;
        for($i = 0; $i < $type_len;$i++) {
            if ($i == $type) {
                $rtn = $lang['layout_type_arr'][$i];
                break;
            } 
        } 

        return $rtn;
    } 
} 

?>
