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

require_once(EIFR_ROOT . 'libraries/template.php');
require_once(EIFR_ROOT . 'admin/mod_adminmenu/acl_adminmenu.php');

class ComAdminmenu {
    var $acl_adminmenu;

    function __construct() {
        $this -> acl_adminmenu = new CAclAdminmenu();
    } 

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

        if (dbGetRecordCount(TB_ADMINMENU, " id like '" . $selectid . "__'") > 0) {
            Common::showWarningMsg($lang['donotadmitof_submenu']);
        } 
        
        require_once(EIFR_ROOT . 'admin/mod_user_class/class_user_class.php');
        $clComUserClass = new ComUserClass();
        $clComUserClass -> removeUserClassAcl($selectid);

        if ($this -> deleteAdminmenu($selectid)) {
            Common::showMsg($lang['delSuccess'], 'success', DIR_INSTALL . 'admin/' . $url);
        } else {
            Common::showErrorMsg($lang['delFail']);
        } 
    } 

    function deleteAdminmenu($id) {
        return dbDelete(TB_ADMINMENU, "id='$id'");
    } 

    function addRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?	
        
        $ismanage = Common::checkAdminAuth($url, 'manage');
        if (!$ismanage) {
            if (kPost('uid') != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

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

        $max_id = '';
        $sql = "select max(id) as max_id from " . TB_ADMINMENU . " where id like '" . $parentid . "__'";
        $rs = $db -> Execute($sql);
        if ($parentid) {
            Common::checkEditDataIsExist(TB_ADMINMENU, 'tourl', kPost('tourl'), "length(id)>2");

            $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;
        } 

        $parameter = '';
        $param_arr = array();
        if (kPost('channel_ids') != '') {
            $param_arr['channel_ids'] = kPost('channel_ids');
        } 
        if (kPost('template_id') != '' && trim(kPost('template_id_show')) != '') {
            $param_arr['template_id'] = kPost('template_id');
        } 
        if ($param_arr) $parameter = serialize($param_arr);

        $acl = 0;
        if (kPost('auth_list')) {
            $acl = $this -> acl_adminmenu -> getValueByValues(kPost('auth_list'));
        } 

        $record_arr = array('id' => $max_id,
            'type' => kPost('menu_type'),
            'title' => sTextEncode(kPost('title')),
            'fileurl' => kPost('fileurl'),
            'tourl' => kPost('tourl'),
            'parameter' => $parameter,
            'status' => kPost('status'),
            'is_delete' => kPost('is_delete'),
            'acl' => $acl,
            'ordernum' => $ordernum,
            'uid' => kPost('uid')
            );

        if (dbInsert(TB_ADMINMENU, $record_arr)) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'adminmenu_edit.php', 'adminmenu_edit.php?act=edit&selectid=' . $max_id, 'adminmenu.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
    } 

    function editRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        
        $ismanage = Common::checkAdminAuth($url, 'manage');

        if (!$ismanage) {
            if (kPost('uid') != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $selectid = kRequest('selectid');
        if (kPost('selectValue') != '') $selectid = kPost('selectValue');

        if (strlen($selectid) == 4) {
            Common::checkEditDataIsExist(TB_ADMINMENU, 'tourl', kPost('tourl'), kPost('tourl_old'), "length(id)>2");
        } 

        $parameter = '';
        $param_arr = array();
        if (kPost('channel_ids') != '') {
            $param_arr['channel_ids'] = kPost('channel_ids');
        } 
        if (kPost('template_id') != '' && trim(kPost('template_id_show')) != '') {
            $param_arr['template_id'] = kPost('template_id');
        } 
        if ($param_arr) $parameter = serialize($param_arr);

        $acl = 0;
        if (kPost('auth_list')) {
            $acl = $this -> acl_adminmenu -> getValueByValues(kPost('auth_list'));
        } 

        $record_arr = array('type' => kPost('menu_type'),
            'title' => sTextEncode(kPost('title')),
            'fileurl' => kPost('fileurl'),
            'parameter' => $parameter,
            'status' => kPost('status'),
            'is_delete' => kPost('is_delete'),
            'acl' => $acl,
            'uid' => kPost('uid')
            );

        if ($ismanage) {
            $record_arr['tourl'] = kPost('tourl');
        } 

        if (dbUpdate(TB_ADMINMENU, $record_arr, "id='$selectid'")) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'adminmenu_edit.php', 'adminmenu_edit.php?act=edit&selectid=' . $selectid, 'adminmenu.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    } 

    function copyRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        global $menu_type, $title, $tourl, $tourl_old, $fileurl, $uid, $status, $auth_list, $parentid, $parentid_old, $adminmenu_title;
        $auth_list_checked = '';
        if ($auth_list != '') $auth_list_checked = implode(',', $auth_list);

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

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

        $sql = "select max(id) as max_id from " . TB_ADMINMENU . " 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;
        } 
        Common::checkOverMaxNum(strlen($max_id), MAX_CATEGORYID_LEN);
        $title .= '[copy]';
        $title = sTextEncode($title);
        $parameter = '';
        $param_arr = array();
        if (kPost('channel_ids') != '') {
            $param_arr['channel_ids'] = kPost('channel_ids');
        } 
        if (kPost('template_id') != '' && trim(kPost('template_id_show')) != '') {
            $param_arr['template_id'] = kPost('template_id');
        } 
        if ($param_arr) $parameter = serialize($param_arr);

        $acl = 0;
        if (kPost('auth_list')) {
            $acl = $this -> acl_adminmenu -> getValueByValues(kPost('auth_list'));
        } 

        $sql = "insert into " . TB_ADMINMENU . " (id,type,title,fileurl,tourl,parameter,ordernum,acl,status,uid) values('$max_id','$menu_type','$title','$fileurl','$tourl','$parameter','$ordernum','$acl','$status','$uid')"; 
        // echo $sql;
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'adminmenu_edit.php', 'adminmenu_edit.php?act=edit&selectid=' . $max_id, 'adminmenu.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

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

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

        $rs_1 = $db -> Execute("select id,ordernum from " . TB_ADMINMENU . "  where  id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_ADMINMENU . " 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_ADMINMENU . " 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_ADMINMENU . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_ADMINMENU . " 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_adminmenu() {
        global $db, $url;
        global $rootid;

        $isedit = Common::checkAdminAuth($url, 'edit');

        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => Common::createToolbar($url, 'add', 'adminmenu_edit.php') . Common::createToolbar($url, 'edit', 'adminmenu_edit.php?act=edit') . Common::createToolbar($url, 'delete', 'adminmenu.php?act=delete')
                )); 
        // show list---start---
        $sqlstr = '';
        if (!Common::checkAdminAuth($url, 'manage')) {
            $sqlstr = " and uid='" . getCookie(COOKIE_UID) . "'";
        } 
        if (!Common::checkSysAdmin()) {
            $sqlstr .= ' and is_delete=0 ';
        } 

        $sql = "select * from " . TB_ADMINMENU . " where length(id)=2  " . $sqlstr . " order by ordernum ";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $id = $rs -> fields['id'];
            $orderby = '<b>' . $rs -> fields['ordernum'] . '</b>';
            if ($isedit) { // is to show orderby ?
                    $orderby = Common::createOrderBy('', '&id=' . $id . '');
            } 
            if (dbGetRecordCount(TB_ADMINMENU, "status=1 and id like '" . $id . "__' " . $sqlstr . "") > 0) {
                $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 = '';
            } 

            $clTemplate -> assign_block_vars('ListMenu', array('num' => $num,
                    'id' => $id,
                    'title' => "<b>" . $rs -> fields['title'] . "</b>",
                    'tourl' => $rs -> fields['tourl'],
                    'show_img' => $rs -> fields['fileurl']? "<img src='" . SYS_ADMIN_STYLE_PATH . "images/" . $rs -> fields['fileurl'] . "'>" : '',
                    'username' => dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . $rs -> fields['uid'] . "'"),
                    'orderby' => $orderby,
                    'tr_css' => 'list_parent_tr_bg',
                    'onmouse' => '',
                    'show_arrow' => $show_arrow,
                    'tr_id' => '',
                    'tr_style' => '',
                    )); 
            // sub menu---start---
            $where_subsql = " where  id like '" . $id . "__' ";
            if (!Common::checkSysAdmin()) {
                $where_subsql .= ' and is_delete=0 ';
            } 
            $sql1 = "select * from " . TB_ADMINMENU . " $where_subsql order by ordernum ";
            $rs1 = $db -> Execute($sql1);
            while (!$rs1 -> EOF) {
                $num++;
                $is_orderby = false;
                if ($rootid == substr($rs1 -> fields['id'], 0, 2)) {
                    $is_orderby = true;
                } 
                if ($rs1 -> fields['status'] == 1) { // hidden menu
                        $tr_id = ' id="' . $rs1 -> fields['id'] . '"';
                    $tr_css = 'list_hidden_tr_bg';
                    $td_css = 'list_hidden_td_bg';
                    $tr_onmouse = 'onMouseOver="this.className=\'list_mouseover_hidden_tr_bg\'" onMouseOut="this.className=\'list_hidden_tr_bg\'"';
                    $td_onmouse = 'onMouseOver="this.className=\'list_mouseover_hidden_td_bg\'" onMouseOut="this.className=\'list_hidden_td_bg\'"';
                    $tr_style = $is_orderby? ' style="display:"' : ' style="display:none"';
                } else {
                    $tr_id = '';
                    $tr_css = 'list_sub_tr_bg';
                    $td_css = 'list_sub_td_bg';
                    $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\'"';
                    $tr_style = ' style="display:"';
                } 

                $orderby = $rs -> fields['ordernum'];
                if (Common::checkAdminAuth($url, 'edit')) { // is to show orderby ?
                        $orderby = Common::createOrderBy('', '&id=' . $rs1 -> fields['id'] . '');
                } 
                $clTemplate -> assign_block_vars('ListMenu', array('num' => $num,
                        'id' => $rs1 -> fields['id'],
                        'title' => $rs1 -> fields['title'],
                        'tourl' => $rs1 -> fields['tourl'],
                        'fileurl' => $rs1 -> fields['fileurl']? SYS_ADMIN_STYLE_PATH . 'images/' . $rs1 -> fields['fileurl'] : SYS_ADMIN_STYLE_PATH . 'images/none_img_gray.gif',
                        'username' => dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . $rs1 -> fields['uid'] . "'"),
                        'orderby' => $orderby,
                        'tr_css' => $tr_css,
                        'td_css' => $td_css,
                        'tr_onmouse' => $tr_onmouse,
                        'td_onmouse' => IS_ONMOUSE_TD? $td_onmouse : '',
                        'show_arrow' => '',
                        'tr_id' => $tr_id,
                        'tr_style' => $tr_style
                        ));

                $rs1 -> MoveNext();
            } 
            $rs1 -> Close(); 
            // sub menu---end---
            $rs -> MoveNext();
        } 
        $rs -> Close(); 
        // show list---end---
        $clTemplate -> set_filenames(array('body' => 'adminmenu.tpl.html'));
        $clTemplate -> pparse("body");
    } 

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

        if ($selectValue) $selectid = $selectValue;

        $id = '';
        $parentid_old = '';
        $title = '';
        $auth_list = '';
        $list_class = '';
        $tourl = '';
        $tourl_old = '';
        $fileurl = '';
        $channel_ids = '';
        $template_id = '';
        $template_title = '';
        $status = '';
        $is_delete = '';
        $show_img = '';
        $is_edit = '';
        $isdisabled = '';

        $ismanage = Common::checkAdminAuth($url, 'manage');

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

        if ($act == 'edit') { // edit
            Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
            $toolbar = Common::createToolbar($url, 'save', 'adminmenu_edit.php?act=save_edit') . Common::createToolbar($url, 'copy', 'adminmenu_edit.php?act=copy') . Common::createToolbar($url, 'delete', 'adminmenu.php?act=delete');

            if (!$ismanage) {
                $uid = dbGetFieldValue(TB_ADMINMENU, "uid", "id ='" . $selectid . "'");
                if ($uid != getCookie(COOKIE_UID)) {
                    Common::showWarningMsg($lang['checkAuth']);
                } 
            } 

            $sql = "select * from " . TB_ADMINMENU . " where id='" . $selectid . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                $list_class = $this -> creatAdminmenuSelect(substr($rs -> fields['id'], 0, strlen($rs -> fields['id'])-2), $ismanage);

                $param_arr = unserialize($rs -> fields['parameter']);
                if (is_array($param_arr) && isset($param_arr['channel_ids'])) {
                    $channel_ids = $param_arr['channel_ids'];
                } 
                if (is_array($param_arr) && isset($param_arr['template_id'])) {
                    $template_id = $param_arr['template_id'];
                    $template_title = dbGetFieldValue(TB_TEMPLATE, 'title', "id='" . $template_id . "'");
                } 

                $parentid_old = substr($rs -> fields['id'], 0, strlen($rs -> fields['id'])-2);
                $selectid = $rs -> fields['id'];
                $id = $rs -> fields['id'];
                $title = $rs -> fields['title'];
                $auth_list = $this -> getAuthlist($rs -> fields['acl']);
                $tourl = $rs -> fields['tourl'];
                $tourl_old = $rs -> fields['tourl'];
                $fileurl = $rs -> fields['fileurl']? $rs -> fields['fileurl'] : '';

                $show_img = $rs -> fields['fileurl']? "<img src='" . SYS_ADMIN_STYLE_PATH . 'images/' . $rs -> fields['fileurl'] . "'>" : '';
                $status = Common::creatFlagCheck('status', '0', 'display', $rs -> fields['status'] == 0 ? true:false) . Common::creatFlagCheck('status', '1', 'hidden', $rs -> fields['status'] == 1 ? true:false);
                $is_delete = Common::creatFlagCheck('is_delete', '0', 'open', $rs -> fields['is_delete'] == 0 ? true:false) . Common::creatFlagCheck('is_delete', '1', 'stop', $rs -> fields['is_delete'] == 1 ? true:false);
                $uid = $rs -> fields['uid'];
                $username = dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . $rs -> fields['uid'] . "'");
                $is_edit = ' disabled';
                $type_show = $this -> createAdminmenuTypeSelect($rs -> fields['type']);
                $isdisabled = Common::checkAdminAuth($url, 'manage')? '' : ' disabled';
            } 
            $rs -> Close();
        } else { // add
            Common::checkAdminExeAuth($url, 'add'); //have edit authority ?	
            $toolbar = Common::createToolbar($url, 'save', 'adminmenu_edit.php?act=save_add');

            if ($selectid != '') {
                $selectid = substr($selectid, 0, 2);
            } 
            $list_class = $this -> creatAdminmenuSelect($selectid, $ismanage);

            $auth_list = $this -> getAuthlist();
            $status = Common::creatFlagCheck('status', '0', 'display', true) . Common::creatFlagCheck('status', '1', 'hidden');
            $is_delete = Common::creatFlagCheck('is_delete', '0', 'open', true) . Common::creatFlagCheck('is_delete', '1', 'stop');
            $uid = getCookie(COOKIE_UID);
            $username = dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
            $type_show = $this -> createAdminmenuTypeSelect(0);
        } 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                )); 
        // data
        $clTemplate -> assign_vars(array('list_class' => $list_class,
                'parentid_old' => $parentid_old,
                'selectid' => $selectid,
                'id' => $id,
                'title' => $title,
                'auth_list' => $auth_list,
                'tourl' => $tourl,
                'tourl_old' => $tourl_old,
                'fileurl' => $fileurl,
                'channel_ids' => $channel_ids,
                'template_id' => $template_id,
                'template_title' => $template_title,
                'show_img' => $show_img,
                'status' => $status,
                'is_delete' => $is_delete,
                'uid' => $uid,
                'username' => $username,
                'is_edit' => $is_edit,
                'type_show' => $type_show,
                'isdisabled' => $isdisabled
                ));

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

    function layout_adminmenu_auth_edit() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authorization ?
        
        $selectid = kRequest('selectid');
        if (kPost('selectValue') != '') $selectid = kPost('selectValue');

        if ($selectid == '') {
            Common::showWarningMsg($lang['records_inexistence']);
        } 

        if (!Common::checkAdminAuth($url, 'manage')) {
            $user_class_id = dbGetFieldValue(TB_USER, TFR_USER_CLASS_ID, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
            if ($selectid != $user_class_id) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => Common::createToolbar($url, 'save', 'adminmenu_auth_edit.php?act=save'),
                'user_class_title' => dbGetFieldValue(TB_USER_CLASS, TF_USER_CLASS_TITLE, "" . TF_USER_CLASS_ID . " ='" . $selectid . "'"),
                'user_class_id' => $selectid
                )); 

        // show list---start---
        $wheresql = '  where length(id)=2  ';
        if (!Common::checkSysAdmin()) {
            $wheresql .= ' and is_delete=0 ';
        } 

        $userClassAclStr = dbGetFieldValue(TB_USER_CLASS, 'acl', "id='" . $selectid . "'");

        $sql = "select * from " . TB_ADMINMENU . " $wheresql order by ordernum ";
        $rs = $db -> Execute($sql);
        $num = 0;
        while (!$rs -> EOF) {
            $num++;
            $id = $rs -> fields['id'];
            $show_img = ''; 
            $show_title = '&nbsp;<b>' . $num . '&nbsp;' . $rs -> fields['title'] . '</b>&nbsp;' . $show_img;

            $clTemplate -> assign_block_vars('ListMenu', array('tr_css' => 'list_parent_tr_bg',
                    'td_css' => 'list_parent_td_bg',
                    'tr_onmouse' => '',
                    'td_onmouse' => '',
                    'tr_id' => '',
                    'num' => $num,
                    'id' => $rs -> fields['id'],
                    'title' => $show_title,
                    'adminmenu_id' => '',
                    'show_edit' => ''
                    )); 
            // sub menu---start---
            $where_subsql = " where  id like '" . $id . "__' ";
            if (!Common::checkSysAdmin()) {
                $where_subsql .= ' and is_delete=0 ';
            } 

            $sql1 = "select * from " . TB_ADMINMENU . " $where_subsql order by ordernum ";
            $rs1 = $db -> Execute($sql1);
            while (!$rs1 -> EOF) {
                $sub_id = $rs1 -> fields['id'];

                $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\'"';

                $clTemplate -> assign_block_vars('ListMenu', array('tr_css' => 'list_sub_tr_bg',
                        'td_css' => 'list_sub_td_bg',
                        'tr_onmouse' => $tr_onmouse,
                        'td_onmouse' => IS_ONMOUSE_TD? $td_onmouse : '',
                        'tr_id' => $sub_id,
                        'id' => $sub_id,
                        'title' => $rs1 -> fields['title'],
                        'adminmenu_id' => $sub_id,
                        'show_edit' => $this -> getAuthlistByAclStr($rs1 -> fields['acl'], $sub_id, $userClassAclStr)
                        ));

                $rs1 -> MoveNext();
            } 
            $rs1 -> Close(); 
            // sub menu---end---
            $rs -> MoveNext();
        } 
        $rs -> Close(); 
        // show list---end---
        $clTemplate -> set_filenames(array('body' => 'adminmenu_auth_edit.tpl.html'));
        $clTemplate -> pparse("body");
    } 

    function getVisibleAdminmenusLevel() {
        return $this -> getAdminmenusLevel(0);
    } 

    /**
     * get Adminmenus Level
     * 
     * @status , default is all, 0 is visible, 1 is hidden
     */
    function getAdminmenusLevel($status = '') {
        $rtn = array();

        if (Common::checkSysAdmin()) {
            $rtn = $this -> getAllAdminmenusLevel($status);
        } else {
            $adminmenus = $this -> getAvailableAdminmenusExceptPrivate();
            $acls = $this -> acl_adminmenu -> getUserAcls();
            foreach($adminmenus as $key => $val) {
                if ($status !== '' && $val['status'] != $status) {
                    continue;
                } 
                if (array_key_exists($key, $acls)) {
                    $pkey = substr($key, 0, 2);
                    if (!array_key_exists($pkey, $rtn)) {
                        $rtn[$pkey] = $adminmenus[$pkey];
                        $rtn[$pkey]['eifr_child'] = array();
                    } 
                    $rtn[$pkey]['eifr_child'][$key] = $val;
                } 
            } 
        } 
        // remove parent, if specified status and no child
        if ($status !== '') {
            foreach($rtn as $key => $val) {
                if (isset($val['eifr_child']) && !$val['eifr_child']) {
                    unset($rtn);
                } 
            } 
        } 
        return $rtn;
    } 

    function getVisibleAdminmenusLevel1() {
        return $this -> getAdminmenusLevel1(0);
    } 

    /**
     * get get Adminmenus Level 1
     * 
     * @status , default is all, 0 is visible, 1 is hidden
     */
    function getAdminmenusLevel1($status = '') {
        $rtn = array();
        if (Common::checkSysAdmin()) {
            $wheresql = "where length(id)=2";
            if ($status !== '') {
                $wheresql .= " and status=$status";
            } 
            $sql = "select * from " . TB_ADMINMENU . " $wheresql order by ordernum";
            $rtn = dbGetRecordn($sql);
        } else {
            $adminmenus = $this -> getAvailableAdminmenusExceptPrivate();
            $acls = $this -> acl_adminmenu -> getUserAcls();
            foreach($adminmenus as $key => $val) {
                if (array_key_exists($key, $acls)) {
                    if ($status !== '' && $val['status'] != $status) {
                        continue;
                    } 
                    $key = substr($key, 0, 2);
                    if (!array_key_exists($key, $rtn)) {
                        $rtn[$key] = $adminmenus[$key];
                    } 
                } 
            } 
        } 
        return $rtn;
    } 

    function getVisibleAdminmenuChildByPid($parentid) {
        return $this -> getAdminmenuChildByPid($parentid, 0);
    } 

    function getAdminmenuChildByPid($parentid, $status = '') {
        $rtn = array();
        if (Common::checkSysAdmin()) {
            $wheresql = "where id like '" . $parentid . "__'";
            if ($status !== '') {
                $wheresql .= " and status=$status";
            } 
            $sql = "select id from " . TB_ADMINMENU . " $wheresql order by ordernum";
            $rtn = dbGetRecordn($sql);
        } else {
            $adminmenus = $this -> getAvailableAdminmenusExceptPrivate();
            $acls = $this -> acl_adminmenu -> getUserAcls();
            foreach($adminmenus as $key => $val) {
                $pkey = substr($key, 0, 2);
                if (array_key_exists($key, $acls) && $pkey == $parentid) {
                    if ($status !== '' && $val['status'] != $status) {
                        continue;
                    } 
                    $rtn[$key] = $val;
                } 
            } 
        } 

        return $rtn;
    } 

    function getAllAdminmenusLevel($status = '') {
        global $db;
        $rtn = array();

        $wheresql = " where length(id)=2 ";
        if ($status !== '') {
            $wheresql .= " and status=$status ";
        } 
        $sql = "select * from " . TB_ADMINMENU . " $wheresql order by ordernum ";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        while (!$rs -> EOF) {
            $id = $rs -> fields['id'];
            $rtn[$id] = array('id' => $id,
                'title' => $rs -> fields['title'],
                'tourl' => $rs -> fields['tourl'],
                'fileurl' => $rs -> fields['fileurl'],
                'parameter' => $rs -> fields['parameter'],
                'acl' => $rs -> fields['acl'],
                'ordernum' => $rs -> fields['ordernum'],
                'status' => $rs -> fields['status'],
                'type' => $rs -> fields['type'],
                );

            $wheresql = " where id like '" . $id . "__' ";
            if ($status !== '') {
                $wheresql .= " and status=$status ";
            } 
            // sub menu---start---
            $sql1 = "select * from " . TB_ADMINMENU . " $wheresql order by ordernum ";
            $rs1 = $db -> Execute($sql1);
            while (!$rs1 -> EOF) {
                $rtn[$id]['eifr_child'][] = array('id' => $rs1 -> fields['id'],
                    'title' => $rs1 -> fields['title'],
                    'tourl' => $rs1 -> fields['tourl'],
                    'fileurl' => $rs1 -> fields['fileurl'],
                    'parameter' => $rs1 -> fields['parameter'],
                    'acl' => $rs1 -> fields['acl'],
                    'ordernum' => $rs1 -> fields['ordernum'],
                    'status' => $rs1 -> fields['status'],
                    'type' => $rs1 -> fields['type'],
                    );
                $rs1 -> MoveNext();
            } 
            $rs1 -> Close(); 
            // sub menu---end---
            $rs -> MoveNext();
        } 
        $rs -> Close();

        return $rtn;
    } 

    /**
     * get Available Admin menus Except Private
     */
    function getAvailableAdminmenusExceptPrivate() {
        global $db;
        $rtn = array();

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

        $sql = "select * from " . TB_ADMINMENU . " where length(id)=2 and is_delete=0 and type<>2 order by ordernum ";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        while (!$rs -> EOF) {
            $id = $rs -> fields['id'];
            $rtn[$id] = array('id' => $id,
                'title' => $rs -> fields['title'],
                'tourl' => $rs -> fields['tourl'],
                'fileurl' => $rs -> fields['fileurl'],
                'parameter' => $rs -> fields['parameter'],
                'acl' => $rs -> fields['acl'],
                'ordernum' => $rs -> fields['ordernum'],
                'status' => $rs -> fields['status'],
                'type' => $rs -> fields['type'],
                ); 
            // sub menu---start---
            $sql1 = "select * from " . TB_ADMINMENU . " where id like '" . $id . "__' and is_delete=0 and type<>2 order by ordernum ";
            $rs1 = $db -> Execute($sql1);
            while (!$rs1 -> EOF) {
                $rtn[$rs1 -> fields['id']] = array('id' => $rs1 -> fields['id'],
                    'title' => $rs1 -> fields['title'],
                    'tourl' => $rs1 -> fields['tourl'],
                    'fileurl' => $rs1 -> fields['fileurl'],
                    'parameter' => $rs1 -> fields['parameter'],
                    'acl' => $rs1 -> fields['acl'],
                    'ordernum' => $rs1 -> fields['ordernum'],
                    'status' => $rs1 -> fields['status'],
                    'type' => $rs1 -> fields['type'],
                    );
                $rs1 -> MoveNext();
            } 
            $rs1 -> Close(); 
            // sub menu---end---
            $rs -> MoveNext();
        } 
        $rs -> Close(); 
        // show list---end---
        return $rtn;
    } 

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

    function getAuthlist($select_aclvalue = 0) {
        global $lang;
        $rtn = '';
        $access = $this -> acl_adminmenu -> getAccess();

        foreach($access as $key => $val) {
            $ischecked = '';
            if ($this -> acl_adminmenu -> isAllowedInValue($key, $select_aclvalue)) {
                $ischecked = ' checked';
            } 
            $rtn .= '<input type="checkbox" name="auth_list[]"  class="input_checkbox" value="' . $val . '" ' . $ischecked . '>' . $lang[$key] . '&nbsp;';
        } 

        return $rtn;
    } 

    function getAuthlistByAclStr($menu_aclvalue = 0, $adminmenu_id, $aclstr = '') {
        global $lang;
        $rtn = '';
        if ($menu_aclvalue === 0) return '';
        $clCAclAdminmenu = new CAclAdminmenu();
        $clCAclAdminmenu -> setValue($menu_aclvalue);
        $access_menu = $clCAclAdminmenu -> getAccess();

        $acl_arr = unserialize($aclstr);
        $select_aclvalue = 0;
        if (is_array($acl_arr) && array_key_exists($adminmenu_id, $acl_arr)) {
            $select_aclvalue = $acl_arr[$adminmenu_id];
        } 

        foreach($access_menu as $key => $val) {
            $ischecked = '';
            if ($clCAclAdminmenu -> isAllowedInValue($key, $select_aclvalue)) {
                $ischecked = ' checked';
            } 

            $rtn .= '<input type="checkbox" name="auth_list_' . $adminmenu_id . '[]"  class="input_checkbox" value="' . $val . '" ' . $ischecked . '>' . $lang[$key] . '&nbsp;';
        } 

        return $rtn;
    } 

    function getAdminmenuByid($id) {
        $rtn = array();
        if (Common::checkSysAdmin()) {
            $sql = "select * from " . TB_ADMINMENU . " where id='$id'";
            $rtn = dbGetRecord1($sql);
        } else {
            $cacheHelper = new CCacheHelper('db_adminmenu');
            $adminmenu = $cacheHelper -> getCache();
            if ($adminmenu) {
                foreach($adminmenu as $val) {
                    if ($val['id'] === $id) {
                        $rtn = $val;
                        break;
                    } 
                } 
            } else {
                $sql = "select * from " . TB_ADMINMENU . " where id='" . $id . "'";
                $rtn = dbGetRecord1($sql);
            } 
        } 

        return $rtn;
    } 

    function getAdminmenuByUrl($url = '') {
        $rtn = array();
        if (Common::checkSysAdmin()) {
            $sql = "select * from " . TB_ADMINMENU . " where tourl='" . $url . "'";
            $rtn = dbGetRecord1($sql);
        } else {
            $cacheHelper = new CCacheHelper('db_adminmenu');
            $adminmenu = $cacheHelper -> getCache();
            if ($adminmenu) {
                foreach($adminmenu as $val) {
                    if ($val['tourl'] == $url) {
                        $rtn = $val;
                        break;
                    } 
                } 
            } else {
                $sql = "select * from " . TB_ADMINMENU . "  where tourl='" . $url . "'";
                $rtn = dbGetRecord1($sql);
            } 
        } 
        return $rtn;
    } 

    /**
     * ---createAdminmenuTypeSelect---
     * 
     * @param string $type 
     * @return string 
     */
    function createAdminmenuTypeSelect($type = '') {
        global $lang;
        $rtn = '';
        $type_arr = array(0, 1, 2);
        if (!is_numeric($type)) $type = -1;
        for($i = 0; $i < 3;$i++) {
            $e_s = '';
            if ($type_arr[$i] == $type) {
                $e_s = ' checked';
                $type = '';
            } 
            $showvalue = $lang['adminmenu_type'][$i];
            $rtn .= "<input name='menu_type' type='radio' onclick='selectShowAuth(" . $type_arr[$i] . ")' value='" . $type_arr[$i] . "' " . $e_s . ">" . $showvalue . "\n";
        } 

        return $rtn;
    } 

    /**
     * ---creatAdminmenuSelect---
     * list adminmenu list/menu
     * 
     * @param string $tb table name
     * @param string $fieldname table field name
     * @param string $select selected id
     * @param string $wherevalue 
     * @return string 
     */
    function creatAdminmenuSelect($select = '', $ismanage = true) {
        global $db;
        $rtn = '';
        $strsql = '';
        if (!$ismanage) $strsql = " and uid='" . getCookie(COOKIE_UID) . "'";
        $sql = "select id, title from " . TB_ADMINMENU . " where length(id)=2 " . $strsql . " order by id asc";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $adminmenu_id = $rs -> fields['id'];
            $depth = strlen($adminmenu_id)-2;
            $spaces = '';
            if ($depth > 0) $spaces = str_repeat("&nbsp;", $depth);
            $e_s = '';
            if ($adminmenu_id == $select) {
                $e_s = "selected";
                $select = '';
            } 
            $rtn .= "<option value=" . $adminmenu_id . " " . $e_s . "> " . $spaces . "├ " . $rs -> fields['title'] . "";
            $rtn .= "</option>\n";

            $rs -> MoveNext();
        } 
        $rs -> Close();

        return $rtn;
    } 

    /**
     * createAdminMenuNav
     * admin menu navigation
     * 
     * @param string $url ,$subtitle=''
     * @return string 
     */
    function createAdminMenuNav($url, $subtitle = '') {
        $rtn = "";
        if ($url) {
            $row = $this -> getAdminmenuByUrl($url);
            if ($row && strlen($row['id']) == 4) {
                $prow = $this -> getAdminmenuByid(substr($row['id'], 0, 2));
                if ($prow && $prow['fileurl'] != '') {
                    $rtn .= "<img src='" . SYS_ADMIN_STYLE_PATH . 'images/' .$prow['fileurl'] . "' align='absmiddle'>&nbsp;";
                } 
                $rtn .= "<b>" . $prow['title'] . "</b>";
                $rtn .= "&gt;&gt;" . $row['title'];
            } 
        } 

        if ($subtitle) {
            $rtn .= "&gt;&gt;" . $subtitle . "";
        } 

        return $rtn;
    } 
} 

?>
