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

/**
 * ---TB_ADDRESS---
 * #flag (0:unchecked, 1:open, 2:locked, 3:stop, 4:delete)
 */
class ComAddress {
    function setFieldRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
        global $selectid, $selectValue, $field_name, $field_value;

        if ($selectValue != '') $selectid = $selectValue;
        $sql = "UPDATE " . TB_ADDRESS . "  set $field_name ='$field_value'  WHERE id in (" . $selectid . ")";
        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showMsg($lang['modifySuccess'], 'success', 'address.php');
        } else {
            Common::showErrorMsg($lang['modifyFail']);
        } 
    } 

    function deleteRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'delete'); //have delete authority ?	
        global $selectValue;
        if ($selectValue == '00' || $selectValue == '01') {
            if (!Common::checkSysAdmin()) {
                Common::showWarningMsg($lang['checkSysData']);
            } 
        } 
        if (!Common::checkAdminAuth($url, 'manage')) {
            $uid = dbGetFieldValue(TB_ADDRESS, TFR_USER_ID, "id ='" . $selectValue . "'");
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $sql = "update " . TB_USER . " set " . TFR_ADDRESS_ID . "='' where " . TFR_ADDRESS_ID . "='" . $selectValue . "'";
        $rs = $db -> Execute($sql);
        if ($rs) {
        } else {
        } 
        $rs -> Close();

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

    function addRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        global $title, $flag, $uid, $parentid;

        if (!Common::checkAdminAuth($url, 'manage')) {
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

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

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

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

            if (strlen($id_pos) < 2) {
                $id_pos = "0" . $id_pos;
            } 
            $id = $parentid . $id_pos;
        } else {
            $id = $rs -> fields['id'] + 1;
            Common::checkOverMaxNum($id, MAX_CATEGORYID);
        } 

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

        Common::checkOverMaxNum(strlen($id), MAX_CATEGORYID_LEN);
        $addtime = time();
        $ip = getIP();
        $title = sTextEncode($title);
        $sql = "insert into " . TB_ADDRESS . " (id,title,ordernum," . TFR_USER_ID . ",ip,addtime,flag) values('$id','$title','$ordernum','$uid','$ip','$addtime','$flag')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showOkMsg($lang['addSuccess'], 'address_edit.php', 'address_edit.php?act=edit&selectid=' . $id, 'address.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

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

        if ($selectValue) $selectid = $selectValue;

        if (!Common::checkAdminAuth($url, 'manage')) {
            $uid = dbGetFieldValue(TB_ADDRESS, TFR_USER_ID, "id ='" . $selectid . "'");
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $title = sTextEncode($title);

        $sql = "update " . TB_ADDRESS . " set title='$title',  flag='$flag', " . TFR_USER_ID . "='$uid'  where id='$selectid'";
        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showOkMsg($lang['saveSuccess'], 'address_edit.php', 'address_edit.php?act=edit&selectid=' . $selectid, 'address.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
        $rs -> Close();
    } 

    function copyRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        global $selectid, $selectValue, $title, $flag, $uid;

        if ($selectValue) $selectid = $selectValue;

        if (!Common::checkAdminAuth($url, 'manage')) {
            $uid = dbGetFieldValue(TB_ADDRESS, TFR_USER_ID, "id ='" . $selectid . "'");
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $parentid = substr($selectValue, 0, strlen($selectValue)-2);

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

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

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

            if (strlen($id_pos) < 2) {
                $id_pos = "0" . $id_pos;
            } 
            $id = $parentid . $id_pos;
        } else {
            $id = $rs -> fields['id'] + 1;
            Common::checkOverMaxNum($id, MAX_CATEGORYID);
        } 

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

        Common::checkOverMaxNum(strlen($id), MAX_CATEGORYID_LEN);

        $title .= '[copy]';
        $addtime = time();
        $ip = getIP();
        $title = sTextEncode($title);
        $sql = "insert into " . TB_ADDRESS . " (id,title,ordernum," . TFR_USER_ID . ",uid,ip,addtime,flag) values('$id','$title','$ordernum','$uid','$ip','$addtime','$flag')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            Common::showOkMsg($lang['addSuccess'], 'address_edit.php', 'address_edit.php?act=edit&selectid=' . $id, 'address.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

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

        if ($id == '') return;
        $rootid = substr($id, 0, 2);

        $rs_1 = $db -> Execute("select id,ordernum from " . TB_ADDRESS . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_ADDRESS . " where ordernum<" . $rs_1 -> fields['ordernum'] . " and length(id)=" . strlen($rs_1 -> fields['id']) . " order by ordernum desc limit 1");
        } 
        if ($act == 'down') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_ADDRESS . " where  ordernum>" . $rs_1 -> fields['ordernum'] . " and length(id)=" . strlen($rs_1 -> fields['id']) . " order by ordernum asc limit 1");
        } 
        $up_1 = $db -> Execute("update " . TB_ADDRESS . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_ADDRESS . " 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 . '?rootid=' . $rootid);
    } 

    function layout_address() {
        global $db, $clTemplate, $url;

        $is_manage = Common::checkAdminAuth($url, 'manage');
        $btn_delete_forever = '';
        $btn_flag = '';
        if ($is_manage) {
            $btn_delete_forever = Common::createToolbar($url, 'delete_forever', 'address.php?act=delete_forever');
            $btn_flag .= Common::createSplitLine();
            $btn_flag .= Common::createToolbar($url, 'unchecked', 'address.php?act=setvalue&field_name=flag&field_value=0');
            $btn_flag .= Common::createToolbar($url, 'open', 'address.php?act=setvalue&field_name=flag&field_value=1');
            $btn_flag .= Common::createToolbar($url, 'locked', 'address.php?act=setvalue&field_name=flag&field_value=2');
            $btn_flag .= Common::createToolbar($url, 'stop', 'address.php?act=setvalue&field_name=flag&field_value=3');
        } 

        $toolbar = Common::createToolbar($url, 'add', 'address_edit.php');
        $toolbar .= Common::createToolbar($url, 'edit', 'address_edit.php?act=edit');
        $toolbar .= Common::createToolbar($url, 'delete', 'address.php?act=setvalue&field_name=flag&field_value=4');
        $toolbar .= $btn_delete_forever;
        $toolbar .= $btn_flag; 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                ));
        $parentid = '';
        if (!$is_manage) {
            $parentid = dbGetFieldValue(TB_ADDRESS, TF_ADDRESS_ID, "" . TFR_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
        } 

        $this -> address_show($parentid);

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

    function address_show($parentid = '') {
        global $db, $clTemplate, $url;
        global $rootid;
        static $num = 0; 
        // show list---start---
        $sqlstr = '';
        $isedit = Common::checkAdminAuth($url, 'edit');

        $sql = "select * from " . TB_ADDRESS . " where id like '" . $parentid . "__' " . $sqlstr . " order by ordernum ";
        $rs = $db -> Execute($sql); 
        // echo $sql.'<br/>';
        while (!$rs -> EOF) {
            $num++;
            $id = $rs -> fields['id'];
            $tr_id = ' id="' . $id . '"';
            $depth = strlen($id)-2;
            $spaces = '';
            $is_orderby = false;
            if ($rootid == substr($id, 0, 2)) {
                $is_orderby = true;
            } 
            if ($depth == 0) { // first floor
                    $orderby = '<b>' . $rs -> fields['ordernum'] . '</b>';
                $tr_css = 'list_parent_tr_bg';
                $td_css = 'list_parent_td_bg';
                $tr_style = ' style="display:"';
                $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_tr_bg\'" onMouseOut="this.className=\'list_parent_tr_bg\'"';
                $td_onmouse = 'onMouseOver="this.className=\'list_mouseover_td_bg\'" onMouseOut="this.className=\'list_parent_td_bg\'"';
            } else {
                $spaces = str_repeat("&nbsp;&nbsp;", $depth);
                $orderby = '' . $rs -> fields['ordernum'] . '';
                $tr_css = 'list_sub_tr_bg';
                $td_css = 'list_sub_td_bg';
                $tr_style = $is_orderby? ' style="display:"' : ' style="display:none"';
                $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_tr_bg\'" onMouseOut="this.className=\'list_sub_tr_bg\'"';
                $td_onmouse = 'onMouseOver="this.className=\'list_mouseover_td_bg\'" onMouseOut="this.className=\'list_sub_td_bg\'"';
            } 

            if (dbGetRecordCount(TB_ADDRESS, "id like '" . $id . "__' " . $sqlstr . "") > 0) { // sub menu
                if ($depth > 0)
                    $show_arrow = "<a href=\"javascript:showSubClassTr('" . $id . "','" . SYS_ADMIN_STYLE_PATH . "images/')\" ><img id='img" . $id . "' src='" . SYS_ADMIN_STYLE_PATH . "images/minus.gif' border='0'></a>";
                else
                    $show_arrow = "<a href=\"javascript:showSubClassTr('" . $id . "','" . SYS_ADMIN_STYLE_PATH . "images/')\" ><img id='img" . $id . "' src='" . SYS_ADMIN_STYLE_PATH . "images/plus.gif' border='0'></a>";
            } else {
                $show_arrow = '';
            } 

            if ($isedit) { // is to show orderby ?
                    $orderby = Common::createOrderBy('', '&id=' . $id . '');
            } 

            $clTemplate -> assign_block_vars('ListAddress', array('tr_id' => $tr_id,
                    'tr_css' => $tr_css,
                    'td_css' => $td_css,
                    'tr_onmouse' => $tr_onmouse,
                    'td_onmouse' => IS_ONMOUSE_TD? $td_onmouse : '',
                    'tr_style' => $tr_style,
                    'show_arrow' => $show_arrow,
                    'num' => $num,
                    'id' => $id,
                    'title' => $spaces . '|-' . $rs -> fields['title'],
                    'orderby' => $orderby,
                    'flag' => Common::createFlagShow($rs -> fields['flag']),
                    'ip' => $rs -> fields['ip'],
                    'addtime' => $rs -> fields['addtime']? getDateTimeMk($rs -> fields['addtime']) : ''
                    ));

            $this -> address_show($id);
            $rs -> MoveNext();
        } 
        $rs -> Close(); 
        // show list---end---
    } 

    function layout_address_edit() {
        global $db, $lang, $clTemplate, $url;
        global $selectid, $selectValue, $act;

        $id = '';
        $title = '';
        $is_edit = '';
        $isdisabled = '';

        if ($selectValue) $selectid = $selectValue;

        if ($act == 'edit') { // edit
            Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
            $is_manage = Common::checkAdminAuth($url, 'manage');
            if (!$is_manage) {
                $uid = dbGetFieldValue(TB_ADDRESS, 'uid', "id ='" . $selectid . "'");
                if ($uid != getCookie(COOKIE_UID)) {
                    Common::showWarningMsg($lang['checkAuth']);
                } 
            } 

            $toolbar = Common::createToolbar($url, 'save', 'address_edit.php?act=save_edit');
            $toolbar .= Common::createToolbar($url, 'delete', 'address.php?act=setvalue&field_name=flag&field_value=4');
            if ($is_manage) {
                $toolbar .= Common::createToolbar($url, 'delete_forever', 'address.php?act=delete_forever');
            } 

            $sql = "select * from " . TB_ADDRESS . " where id='" . $selectid . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                $list_class = Common::createClassNav(TB_ADDRESS, 'id', 'title', substr($rs -> fields['id'], 0, strlen($rs -> fields['id'])-2));
                $selectid = $rs -> fields['id'];
                $id = $rs -> fields['id'];
                $title = $rs -> fields['title'];
                $flag = Common::createFlagRadio($rs -> fields['flag']);
                $uid = $rs -> fields[TFR_USER_ID];
                $username = dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . $uid . "'");
                $is_edit = ' disabled';
                $isdisabled = Common::checkAdminAuth($url, 'manage')? '' : ' disabled';
                $addtime = getDateTimeMk($rs -> fields['addtime']);
                $ip = $rs -> fields['ip'];
            } 
            $rs -> Close();
        } else { // add
            Common::checkAdminExeAuth($url, 'add'); //have add authority ?	
            $toolbar = Common::createToolbar($url, 'save', 'address_edit.php?act=save_add');

            if (Common::checkAdminAuth($url, 'manage')) {
                $list_class = '<select name="parentid" class="input_select" ><option value="">+</option>';
                $list_class .= Common::creatClassSelect(TB_ADDRESS, 'id', $selectid, '');
                $list_class .= '</select>';
            } else {
                $parentid = dbGetFieldValue(TB_USER, TFR_ADDRESS_ID, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
                $list_class = '<select name="parentid" class="input_select" >';
                $list_class .= Common::creatClassSelect(TB_ADDRESS, 'id', $selectid, " id like '" . $parentid . "%'");
                $list_class .= '</select>';
            } 

            $flag = Common::createFlagRadio(0);
            $uid = getCookie(COOKIE_UID);
            $username = dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
            $addtime = getDateTimeMk(time());
            $ip = getIP();
        } 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                )); 
        // data
        $clTemplate -> assign_vars(array('selectid' => $selectid,
                'id' => $id,
                'list_class' => $list_class,
                'title' => $title,
                'flag' => $flag,
                'uid' => $uid,
                'username' => $username,
                'ip' => $ip,
                'addtime' => $addtime,
                'is_edit' => $is_edit,
                'isdisabled' => $isdisabled
                ));

        $clTemplate -> set_filenames(array('body' => 'address_edit.tpl.html'));
        $clTemplate -> pparse("body");
    } 
    
    function getAddresses(&$outdata, $parentid = '') {
        global $db;
        static $iscache = 0;

        if ($iscache == 0) {
            $iscache = 1;
            $cacheHelper = new CCacheHelper('db_address');
            $outdata = $cacheHelper -> getCache();
            if ($outdata !== false) {
                Log_v(__FILE__, __LINE__, 'getAddresses from cache');
                return;
            } 
        } 

        $sql = "select * from " . TB_ADDRESS . " where flag<3 and id like '" . $parentid . "__' order by ordernum ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $outdata[$rs -> fields['id']] = array(
                'id'=>$rs -> fields['id'],
                'title'=>$rs -> fields['title'],
            );
            $this -> getAddresses($outdata, $rs -> fields['id']);
            $rs -> MoveNext();
        } 
        $rs -> Close();
    } 

    function genCache() {
        $data = array();
        $cacheHelper = new CCacheHelper('db_address');
        $cacheHelper -> deleteCache();
        $this -> getAddresses($data);
        $cacheHelper -> writeCache($data);
    } 
    
} 

?>
