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

class ComConfig {
    function deleteRecords() {
        global $db, $lang, $url;
        global $selectid, $selectValue;
        if ($selectValue) $selectid = $selectValue;

        $sql = "DELETE FROM " . TB_CONFIG . " WHERE id='" . $selectid . "'";

        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showMsg($lang['delSuccess'], 'success', 'config.php');
        } else {
            Common::showErrorMsg($lang['delFail']);
        } 
    } 

    function addRecords() {
        global $db, $lang, $url;
        global $selectid, $selectValue, $parentid, $title, $varname, $varvalue, $vartype, $intro, $type;

        if ($selectValue) $selectid = $selectValue;

        $varname = $this -> checkValidStr($varname);
        $varvalue = $this -> checkValidStr($varvalue);
        if (strlen($parentid) > 0) Common::checkEditDataIsExist(TB_CONFIG, 'varname', $varname);

        $ordernum = dbGetMaxValue1(TB_CONFIG, 'ordernum', " id like '" . $parentid . "__'");

        $sql = "select max(id) as max_id from " . TB_CONFIG . " where id like '" . $parentid . "__'";
        $rs = $db -> Execute($sql);

        if ($parentid) {
            $id_pos = substr($rs -> fields['max_id'], strlen($parentid), 2);
            $id_pos += 1;
            Common::checkOverMaxNum($id_pos, MAX_CATEGORYID);

            if (strlen($id_pos) < 2) {
                $id_pos = "0" . $id_pos;
            } 
            $max_id = $parentid . $id_pos;
        } else {
            $max_id = $rs -> fields['max_id'] + 1;
        } 

        if (strlen($max_id) < 2) {
            $max_id = "0" . $max_id;
        } 

        $title = sTextEncode($title);

        $sql = "insert into " . TB_CONFIG . " (id,title,varname,varvalue,vartype,intro,ordernum,type) values('$max_id','$title','$varname','$varvalue','$vartype','$intro','$ordernum','$type')";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        if ($rs) {
            Common::showOkMsg($lang['addSuccess'], 'config_edit.php?selectid=' . $max_id, 'config_edit.php?act=edit&selectid=' . $max_id, 'config.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

    function editRecords() {
        global $db, $lang, $url;
        global $selectid, $selectValue, $title, $varname, $varname_old, $varvalue, $vartype, $intro, $type;

        if ($selectValue) $selectid = $selectValue;
        $varname = $this -> checkValidStr($varname);
        $varvalue = $this -> checkValidStr($varvalue);

        if (strlen($selectid) > 2) Common::checkEditDataIsExist(TB_CONFIG, 'varname', $varname, $varname_old);

        $sql = "update " . TB_CONFIG . " set title='$title' , varname='$varname', varvalue='$varvalue', vartype='$vartype', intro='$intro', type='$type' where id='" . $selectid . "'"; 
        // echo $sql;
        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showOkMsg($lang['addSuccess'], 'config_edit.php?selectid=' . $selectid, 'config_edit.php?act=edit&selectid=' . $selectid, 'config.php');
        } 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_CONFIG . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_CONFIG . " where ordernum<" . $rs_1 -> fields['ordernum'] . "  order by ordernum desc limit 1");
        } 
        if ($act == 'down') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_CONFIG . " where  ordernum>" . $rs_1 -> fields['ordernum'] . "  order by ordernum asc limit 1");
        } 
        $up_1 = $db -> Execute("update " . TB_CONFIG . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_CONFIG . " 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 layoutConfig_show($type = 0, $isedit = false, $ismanage = false) {
        global $db, $clTemplate;

        /**
         * ---ListConfig---start---
         */

        $sql = "select * from " . TB_CONFIG . " where type=$type and length(id)=2 and id<>'00' order by ordernum asc ";
        $rs = $db -> Execute($sql);
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $id = $rs -> fields['id'];
            $depth = strlen($id)-2;
            $orderby = '';
            if ($isedit) { // is to show orderby ?
                    $orderby = Common::createOrderBy('', '&id=' . $id . '');
            } 
            if (dbGetRecordCount(TB_CONFIG, "id like '" . $id . "__' ") > 0) { // sub
                    $show_arrow = "<a href=\"javascript:showsubmenu('" . $id . "')\" ><img id='img" . $id . "' src='" . SYS_ADMIN_STYLE_PATH . "images/arrow_display.gif' border='0'></a>";
            } else {
                $show_arrow = '';
            } 

            $tr_id = ' id="' . $id . '"';
            $tr_css = 'list_parent_tr_bg';
            $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_tr_bg\'" onMouseOut="this.className=\'list_parent_tr_bg\'"';
            $td_css = 'list_parent_td_bg';
            $td_onmouse = 'onMouseOver="this.className=\'list_mouseover_td_bg\'" onMouseOut="this.className=\'list_parent_td_bg\'"';

            $clTemplate -> assign_block_vars('ListConfig' . $type, array('id' => $id,
                    'num' => $num,
                    'title' => $rs -> fields['title'],
                    'intro' => $rs -> fields['intro'],
                    'varname' => $rs -> fields['varname'],
                    'varvalue' => $rs -> fields['varvalue'],
                    'orderby' => $orderby,
                    'tr_css' => $tr_css,
                    'td_css' => $td_css,
                    'td_onmouse' => IS_ONMOUSE_TD? $td_onmouse : '',
                    'show_txt' => '',
                    'value_css' => '',
                    'show_arrow' => $show_arrow
                    )); 
            // sub ---start---
            $sql1 = "select * from " . TB_CONFIG . " where type=$type and  id like '" . $id . "__' order by ordernum ";
            $rs1 = $db -> Execute($sql1);
            while (!$rs1 -> EOF) {
                $num++;
                $original_var = '';
                if ($type == 0) $original_var = $this -> getOriginalVar($rs1 -> fields['varname'], $rs1 -> fields['varvalue'], $rs1 -> fields['vartype']);
                $id1 = $rs1 -> fields['id'];

                $tr_id = ' id="' . $id1 . '"';
                $tr_css = 'list_sub_tr_bg';
                $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_tr_bg\'" onMouseOut="this.className=\'list_sub_tr_bg\'"';

                $td_css = 'list_sub_td_bg';
                $td_onmouse = 'onMouseOver="this.className=\'list_mouseover_td_bg\'" onMouseOut="this.className=\'list_sub_td_bg\'"';

                $orderby = '';
                if ($isedit) { // is to show orderby ?
                        $orderby = Common::createOrderBy('', '&id=' . $id1 . '');
                } 
                $clTemplate -> assign_block_vars('ListConfig' . $type, array('id' => $id1,
                        'num' => $num,
                        'title' => $rs1 -> fields['title'],
                        'intro' => $rs1 -> fields['intro'],
                        'varname' => $rs1 -> fields['varname'],
                        'varvalue' => $rs1 -> fields['varvalue'],
                        'original_var' => $original_var,
                        'orderby' => $orderby,
                        'tr_css' => $tr_css,
                        'tr_id' => $tr_id,
                        'td_css' => $td_css,
                        'value_css' => $rs1 -> fields['vartype'] == 'string'? 'txt_varvalue_string' : 'txt_varvalue',
                        'td_onmouse' => IS_ONMOUSE_TD? $td_onmouse : '',
                        'show_txt' => ' = '
                        ));

                $rs1 -> MoveNext();
            } 
            $rs1 -> Close(); 
            // sub ---end---
            // ////////
            $rs -> MoveNext();
        } 
        $rs -> Close();
        /**
         * ---ListConfig---end---
         */

    } 

    function layoutConfig() {
        global $db, $clTemplate, $url, $act;
        global $selectid, $selectValue;
        if ($selectValue) $selectid = $selectValue;

        $isedit = Common::checkAdminAuth($url, 'edit');
        $ismanage = Common::checkAdminAuth($url, 'manage');
        $toolbar = ''; 
        if ($ismanage) {
            $toolbar .= Common::createToolbar($url,'add','config_edit.php');
            $toolbar .= Common::createToolbar($url, 'edit', 'config_edit.php?act=edit'); 
            $toolbar .= Common::createToolbar($url,'delete','config_edit.php?act=delete');
            $toolbar .= Common::createButton('apply', 'config.php?act=setfile', true, 'apply'); 
        }
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                ));

        $this -> layoutConfig_show(0, $isedit, $ismanage);
        $this -> layoutConfig_show(1, $isedit, $ismanage);

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

    function layoutConfig_edit() {
        global $db, $clTemplate, $url, $act;
        global $selectid, $selectValue;
        if ($selectValue) $selectid = $selectValue;

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

                ));

        $is_display = '';

        if ($act == 'edit') { // edit
            if (strlen($selectid) > 2) $is_display = '';
            $toolbar = Common::createToolbar($url, 'save', 'config_edit.php?act=save_edit');
            $sql = "select * from " . TB_CONFIG . " where id='$selectid'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                // data
                $title = $rs -> fields['title'];
                $varname = $rs -> fields['varname'];
                $varname_old = $varname;
                $varvalue = $rs -> fields['varvalue'];
                $intro = $rs -> fields['intro'];
                $flag = $rs -> fields['flag'];
                $parentid = '';
                $checked_0 = $rs -> fields['type'] == 0 ? ' checked' : '';
                $checked_1 = $rs -> fields['type'] == 1 ? ' checked' : '';
                $is_checked = $rs -> fields['vartype'] == 'string'? ' checked ': '';
            } 
            $rs -> Close();
        } else { // add
            $checked_0 = '';
            $checked_1 = ' checked';

            if (strlen($selectid) > 0) {
                $is_display = '';
                $type = dbGetFieldValue(TB_CONFIG, 'type', "id ='$selectid'");
                $checked_0 = $type == 0 ? ' checked' : '';
                $checked_1 = $type == 1 ? ' checked' : '';
            } 
            $toolbar = Common::createToolbar($url, 'save', 'config_edit.php?act=save_add'); 
            // $toolbar .= Common::createToolbar($url,'delete','config_edit.php?act=delete');
            $title = '';
            $varname = '';
            $varname_old = '';
            $varvalue = '';
            $intro = '';
            $flag = '';
            $parentid = '';
            $is_checked = ' checked';

            if ($selectid != '') $parentid = substr($selectid, 0, 2);
        } 

        $clTemplate -> assign_vars(array('selectid' => $selectid,
                'parentid' => $parentid,
                'title' => $title,
                'varname' => $varname,
                'varname_old' => $varname_old,
                'varvalue' => $varvalue,
                'intro' => $intro,
                'flag' => $flag,
                'checked_0' => $checked_0,
                'checked_1' => $checked_1,
                'is_checked' => $is_checked,
                'is_display' => $is_display,
                'toolbar' => $toolbar
                ));

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

    function setFileConfig() {
        global $db, $lang, $url;

        if (file_exists(dirname(__FILE__) . '/../../includes/config.php') == false) die ($lang['failed']);
        $result = copy(dirname(__FILE__) . '/../../includes/config.php', dirname(__FILE__) . '/../../includes/config.bak.php');
        if ($result == false) die ($lang['failed']);

        $configstr = "<?php\n
/**
* @file config.php
* @copyright (c) 2005 - 2011 eifr.com
* @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
* eifr is free software
*/\n\n";
        $sql = "select * from " . TB_CONFIG . " where length(id)=4 and type=0 order by id asc, ordernum asc ";
        $rs = $db -> Execute($sql);
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $varvalue = $rs -> fields['varvalue'];
            if ($rs -> fields['vartype'] == 'string') $varvalue = "'$varvalue'";
            $configstr .= "define('" . $rs -> fields['varname'] . "'," . $varvalue . ");\n";
            $rs -> MoveNext();
        } 
        $rs -> Close();

        $configstr .= "\n?>";

        $fp = fopen(dirname(__FILE__) . '/../../includes/config.php', 'w') or die("<script>alert('failed!');history.go(-1);</script>");
        fwrite($fp, $configstr);
        fclose($fp);

        Common::showMsg($lang['successful'], 'success', DIR_INSTALL . 'admin/' . $url);
    } 

    function getOriginalVar($varname = '', $varvalue = '', $vartype = 'string') {
        $rtn = '';
        if (!defined($varname)) {
            return $rtn;
        }
        $varvalue_old = constant($varname);
        if ($varvalue_old === false) $varvalue_old = 'false';
        else if ($varvalue_old === true) $varvalue_old = 'true';

        if ($varvalue_old != $varvalue) $rtn = $varname . ' = ' . $varvalue_old;
        return $rtn;
    } 

    function checkValidStr($str) {
        $str = stripslashes($str);
        $str = str_replace("'", '', $str);
        $str = str_replace('"', '', $str);
        $str = str_replace('$', '', $str);
        $str = trim($str);
        return $str;
    } 
} 

?>
