<?php
/**
 * 
 * @file class_user_class.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 . 'admin/mod_adminmenu/acl_adminmenu.php');

/**
 * ---TB_USER_CLASS---
 * #status(0:display,1:hidden)
 * #flag (0:unchecked, 1:open, 2:locked, 3:stop, 4:delete)
 */
class ComUserClass {
    function deleteRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'delete'); //have delete authority ?	
        global $selectValue, $selectid;
        if ($selectValue) {
            $selectid = $selectValue;
        } 
        if ($selectid == '') {
            Common::showErrorMsg($lang['records_inexistence']);
        } 
        if ($selectid == '00' || $selectid == '01') {
            if (!Common::checkSysAdmin()) {
                Common::showWarningMsg($lang['checkSysData']);
            } 
        } 
        if (!Common::checkAdminAuth($url, 'manage')) {
            $uid = dbGetFieldValue(TB_USER_CLASS, TFR_USER_ID, "id ='" . $selectid . "'");
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

        $sql = "update " . TB_USER . " set " . TFR_USER_CLASS_ID . "='' where " . TFR_USER_CLASS_ID . "='" . $selectid . "'";
        $rs = $db -> Execute($sql);
        $rs -> Close();

        $sql = "DELETE FROM " . TB_USER_CLASS . " WHERE id like '" . $selectid . "%'";
        $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, $intro, $loginurl, $fileurl, $status, $flag, $channel_type, $channel_id, $channel_type, $uid, $parentid;

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

        $channel_id = addCommaHeadTail($channel_id);
        if ($channel_type == '1') $channel_id = '-1';

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

        $sql = "select max(id) as id from " . TB_USER_CLASS . " 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_USER_CLASS . " (id,title,fileurl,loginurl,ordernum,intro,status,flag," . TFR_CHANNEL_ID . ",uid,ip,addtime) values('$id','$title','$fileurl','$loginurl','$ordernum','$intro','$status','$flag','$channel_id','$uid','$ip','$addtime')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['addSuccess'], 'user_class_edit.php', 'user_class_edit.php?act=edit&selectid=' . $id, 'user_class.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        $rs -> Close();
    } 

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

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

        $channel_id = addCommaHeadTail(kPost('channel_id'));
        if (kPost('channel_type') == '1') $channel_id = '-1';

        $record_arr = array('title' => sTextEncode(kPost('title')),
            'fileurl' => kPost('fileurl'),
            'intro' => kPost('intro'),
            'loginurl' => kPost('loginurl'),
            'status' => kPost('status'),
            'flag' => kPost('flag'),
            'channel_id' => kPost('channel_id'),
            'uid' => kPost('uid')
            );

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

    function copyRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        global $selectValue, $title, $intro, $loginurl, $fileurl, $status, $flag, $channel_type, $channel_id, $uid;

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

        $channel_id = addCommaHeadTail($channel_id);
        if ($channel_type == '1') $channel_id = '-1';

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

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

        $sql = "select max(id) as id from " . TB_USER_CLASS . " 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_USER_CLASS . " (id,title,fileurl,loginurl,ordernum,intro,status,flag," . TFR_CHANNEL_ID . ",uid,ip,addtime) values('$id','$title','$fileurl','$loginurl','$ordernum','$intro','$status','$flag','$channel_id','$uid','$ip','$addtime')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['addSuccess'], 'user_class_edit.php', 'user_class_edit.php?act=edit&selectid=' . $id, 'user_class.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_USER_CLASS . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_USER_CLASS . " 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_USER_CLASS . " 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_USER_CLASS . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_USER_CLASS . " 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 updateAcl() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        $user_class_id = kPost('user_class_id');

        $acl_arr = array();
        $adminmenu_id_arr = kPost('adminmenu_id');
        $acl_adminmenu = new CAclAdminmenu();
        foreach($adminmenu_id_arr as $key) {
            if (strlen($key) == 4) {
                if (kPost('auth_list_' . $key)) {
                    $acl_arr[$key] = $acl_adminmenu -> getValueByValues(kPost('auth_list_' . $key));
                } 
            } 
        } 

        $acl_str = '';
        if ($acl_arr) {
            $acl_str = serialize($acl_arr);
        } 

        if (dbUpdate(TB_USER_CLASS, array('acl' => $acl_str), "id='$user_class_id'")) {
            $this -> genCache();
            Common::showMsg($lang['saveSuccess'], 'success', DIR_INSTALL . 'admin/' . $url . '?act=edit&selectid=' . $user_class_id);
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    } 

    function layout_user_class() {
        global $db, $clTemplate, $url; 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => Common::createToolbar($url, 'authority', '../mod_adminmenu/adminmenu_auth_edit.php') . Common::createToolbar($url, 'add', 'user_class_edit.php') . Common::createToolbar($url, 'edit', 'user_class_edit.php?act=edit') . Common::createToolbar($url, 'delete', 'user_class.php?act=delete')
                ));
        $parentid = '';
        if (!Common::checkAdminAuth($url, 'manage')) {
            $parentid = dbGetFieldValue(TB_USER_CLASS, TF_USER_CLASS_ID, "" . TFR_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
        } 

        $this -> user_class_show($parentid);

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

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

        $sql = "select * from " . TB_USER_CLASS . " where id like '" . $parentid . "__' " . $sqlstr . " order by ordernum ";
        $rs = $db -> Execute($sql); 
        // echo $sql;
        // echo '<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_USER_CLASS, "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='" . DSYS_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('ListUserClass', 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,
                    'intro' => Common::showTxtAb($rs -> fields['intro'], 20, '...'),
                    'status' => $rs -> fields['status']? Common::createFlagTxt('hidden') : Common::createFlagTxt('display'),
                    'flag' => Common::createFlagShow($rs -> fields['flag']),
                    'ip' => $rs -> fields['ip'],
                    'addtime' => $rs -> fields['addtime']? getDateTimeMk($rs -> fields['addtime']) : ''
                    ));

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

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

        $id = '';
        $title = '';
        $intro = '';
        $loginurl = '';
        $fileurl = '';
        $show_img = '';
        $is_edit = '';
        $isdisabled = '';
        $channel_id = '';
        $channel_checked_1 = '';
        $channel_checked_2 = '';
        $channel_display = 'none';

        if ($selectValue) $selectid = $selectValue;

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

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

            $sql = "select * from " . TB_USER_CLASS . " where id='" . $selectid . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                $channel_id = removeCommaHeadTail($rs -> fields[TFR_CHANNEL_ID]);
                if ($channel_id != '' && $channel_id != '-1') {
                    $channel_checked_2 = ' checked';
                    $channel_display = '';
                } 
                if ($channel_id == '-1') $channel_checked_1 = ' checked';

                $list_class = Common::createClassNav(TB_USER_CLASS, 'id', 'title', substr($rs -> fields['id'], 0, strlen($rs -> fields['id'])-2));
                $selectid = $rs -> fields['id'];
                $id = $rs -> fields['id'];
                $title = $rs -> fields['title'];
                $intro = $rs -> fields['intro'];
                $loginurl = $rs -> fields['loginurl'];
                $fileurl = $rs -> fields['fileurl']? $rs -> fields['fileurl'] : '';
                $show_img = $rs -> fields['fileurl']? "<img src='" . CSafeData::getImgSrc($rs -> fields['fileurl']) . "' align='absmiddle'>" : '';
                $status = Common::creatStatusRadio($rs -> fields['status']);
                $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', 'user_class_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_USER_CLASS, 'id', $selectid, '');
                $list_class .= '</select>';
            } else {
                $parentid = dbGetFieldValue(TB_USER, TFR_USER_CLASS_ID, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
                $list_class = '<select name="parentid" class="input_select" >';
                $list_class .= Common::creatClassSelect(TB_USER_CLASS, 'id', $selectid, " id like '" . $parentid . "%'");
                $list_class .= '</select>';
            } 

            $status = Common::creatStatusRadio(0);
            $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,
				'sys_dir' => DIR_INSTALL,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                )); 
        // data
        $clTemplate -> assign_vars(array('selectid' => $selectid,
                'id' => $id,
                'list_class' => $list_class,
                'channel_id' => $channel_id,
                'channel_checked_1' => $channel_checked_1,
                'channel_checked_2' => $channel_checked_2,
                'channel_display' => $channel_display,
                'title' => $title,
                'intro' => $intro,
                'loginurl' => $loginurl,
                'fileurl' => $fileurl,
                'show_img' => $show_img,
                'status' => $status,
                'flag' => $flag,
                'uid' => $uid,
                'username' => $username,
                'ip' => $ip,
                'addtime' => $addtime,
                'is_edit' => $is_edit,
                'isdisabled' => $isdisabled
                ));

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

    function removeUserClassAcl($adminmenu_id) {
        $cacheHelper = new CCacheHelper('db_user_class');
        $userClasses = $cacheHelper -> getCache();
        if (!$userClasses) {
            $sql = "select id, acl from " . TB_USER_CLASS . " order by id, ordernum ";
            $userClasses = dbGetRecordn($sql);
        } 

        $isfound = false;
        foreach($userClasses as $row) {
            $acl_arr = unserialize($row['acl']);
            if (is_array($acl_arr) && array_key_exists($adminmenu_id, $acl_arr)) {
                $isfound = true;
                unset($acl_arr[$adminmenu_id]);
                dbUpdate(TB_USER_CLASS, array('acl' => serialize($acl_arr)), "id='" . $row['id'] . "'");
            } 
        } 

        if ($isfound) {
            $this -> genCache();
        } 
    } 
    
    public static function getUserClassById($id) {
        $cacheHelper = new CCacheHelper('db_user_class');
        $outdata = $cacheHelper -> getCache();
        if ($outdata !== false) {
            Log_v(__FILE__, __LINE__, 'getUserClassById from cache');
            foreach ($outdata as $row) {
                if ($row['id'] === $id ) {
                    return $row;
                }
            }
        } else {
            $sql = "select * from " . TB_USER_CLASS . " where id ='" . $id . "'";
            return dbGetRecord1($sql);
        }
    }

    function getUserClasses(&$outdata, $parentid = '') {
        global $db;
        static $iscache = 0;

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

        $sql = "select * from " . TB_USER_CLASS . " where 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'],
                'acl' => $rs -> fields['acl'],
                'channel_id' => $rs -> fields['channel_id'],
                'loginurl' => $rs -> fields['loginurl'],
                'flag' => $rs -> fields['flag']
                );
            $this -> getUserClasses($outdata, $rs -> fields['id']);
            $rs -> MoveNext();
        } 
        $rs -> Close();
    } 

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

?>
