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

/**
 * ---ComChannel---
 * #status(0:display,1:hidden)
 * #flags (0:unchecked, 1:open, 2:navigation, 3:stop, 4:delete)
 */
class ComChannel {
    var $flags = array('unchecked', 'open', 'navigation', 'stop', 'delete');

    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') {
            if (!Common::checkSysAdmin()) {
                Common::showWarningMsg($lang['checkSysData']);
            } 
        } 

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

        $this -> updateReChannel($selectid, '');

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

    function updateReChannel($from_id, $to_id) {
        dbUpdateRelatedField(TB_ARTICLE, TFR_CHANNEL_ID, $from_id, $to_id, true, 'id');
        dbUpdateRelatedField(TB_ARTICLE, 'channel_ids', $from_id, $to_id, true, 'id');
        dbUpdateRelatedField(TB_USER, TFR_CHANNEL_ID, $from_id, $to_id, false, 'uid');
        dbUpdateRelatedField(TB_USER_CLASS, TFR_CHANNEL_ID, $from_id, $to_id, false, 'id');
        dbUpdateRelatedField(TB_AD, TFR_CHANNEL_ID, $from_id, $to_id, false, 'id');
        dbUpdateRelatedField(TB_LINK, TFR_CHANNEL_ID, $from_id, $to_id, true, 'id');
    } 

    function addRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        global $title, $intro, $template_id, $article_template_id, $redirecturl, $fileurl, $status, $flag, $uid, $parentid, $channel_id;
        $parentid = $channel_id;
        if (!Common::checkAdminAuth($url, 'manage')) {
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 

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

        $sql = "select max(id) as id from " . TB_CHANNEL . " 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);
        if ($template_id == '') $template_id = 0;
        $addtime = time();
        $ip = getIP();
        $title = sTextEncode($title);
        $sql = "insert into " . TB_CHANNEL . " (id,title,fileurl,redirecturl,ordernum,intro,template_id,article_template_id,status,flag,uid,ip,addtime) values('$id','$title','$fileurl','$redirecturl','$ordernum','$intro','$template_id','$article_template_id','$status','$flag','$uid','$ip','$addtime')"; 
        // echo $sql;
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['addSuccess'], 'channel_edit.php?act=add&selectid=' . $parentid, 'channel_edit.php?act=edit&selectid=' . $id, 'channel.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, $intro, $template_id, $article_template_id, $redirecturl, $fileurl, $status, $flag, $uid;

        if (!Common::checkAdminAuth($url, 'manage')) {
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 
        if ($selectValue) $selectid = $selectValue;
        $title = sTextEncode($title);
        if ($template_id == '') $template_id = 0;
        $sql = "update " . TB_CHANNEL . " set title='$title', fileurl='$fileurl', intro='$intro', template_id='$template_id', article_template_id='$article_template_id', redirecturl='$redirecturl', status='$status', flag='$flag', uid='$uid' where id='$selectid'";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'channel_edit.php', 'channel_edit.php?act=edit&selectid=' . $selectid, 'channel.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
        $rs -> Close();
    } 

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

        if (!Common::checkAdminAuth($url, 'manage')) {
            if ($uid != getCookie(COOKIE_UID)) {
                Common::showWarningMsg($lang['checkAuth']);
            } 
        } 
        $parentid = substr($selectValue, 0, strlen($selectValue)-2);

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

        $sql = "select max(id) as id from " . TB_CHANNEL . " 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);
        if ($template_id == '') $template_id = 0;

        $sql = "insert into " . TB_CHANNEL . " (id,title,fileurl,redirecturl,ordernum,intro,template_id,article_template_id,status,flag,uid,ip,addtime) values('$id','$title','$fileurl','$redirecturl','$ordernum','$intro','$template_id','$article_template_id','$status','$flag','$uid','$ip','$addtime')";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $this -> genCache();
            Common::showOkMsg($lang['addSuccess'], 'channel_edit.php', 'channel_edit.php?act=edit&selectid=' . $id, 'channel.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_CHANNEL . "  where id='" . $id . "'");
        if ($act == 'up') {
            $rs_2 = $db -> Execute("select id,ordernum from " . TB_CHANNEL . " 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_CHANNEL . " 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_CHANNEL . " set ordernum='" . $rs_2 -> fields['ordernum'] . "' where id='" . $rs_1 -> fields['id'] . "'");
        $up_2 = $db -> Execute("update " . TB_CHANNEL . " set ordernum='" . $rs_1 -> fields['ordernum'] . "' where id='" . $rs_2 -> fields['id'] . "'");

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

    function moveRecords() {
        global $db, $lang, $url;
        global $from_id, $to_id;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        $is_manage = Common::checkAdminAuth($url, 'manage');
        $this -> checkMove($from_id, $to_id, $is_manage);

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

        $sql = "select max(id) as id from " . TB_CHANNEL . " 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;
        } 
        // echo "$id|$from_id";
        // exit;
        $rtn_channel = true;
        $rtn_article = true;
        $sql = "update " . TB_CHANNEL . " set id='$id'  where id='$from_id'";
        $rs = $db -> Execute($sql);
        if ($rs) {
            $rtn_channel = true;
        } else {
            $rtn_channel = false;
        } 
        $rs -> Close();

        $this -> updateReChannel($from_id, $id);

        if ($rtn_channel && $rtn_article) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'channel_edit.php', 'channel_edit.php?act=edit&selectid=' . $id, 'channel.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    } 

    function checkMove($from_id, $to_id, $is_manage) {
        global $db, $lang;
        $from_id_parent = substr($from_id, 0, strlen($from_id)-2);
        if ($from_id_parent == $to_id) Common::showWarningMsg($lang['no_changed']);
        $count_sub_id = dbGetRecordCount(TB_CHANNEL, "id like '" . $from_id . "__' ");
        if ($count_sub_id > 0) Common::showWarningMsg($lang['no_subcategory']);
        if (!$is_manage) {
            $rtn = $this -> getIsChannelAuth($to_id);
            if (!$rtn) Common::showWarningMsg($lang['checkAuth']);
        } 
    } 

    function mergeRecords() {
        global $db, $lang, $url;
        global $from_id, $to_id;
        Common::checkAdminExeAuth($url, 'delete');
        $is_manage = Common::checkAdminAuth($url, 'manage');
        $this -> checkMerge($from_id, $to_id, $is_manage);

        $rtn_channel = true;
        $rtn_article = true;

        for($i = 0; $i < count($from_id); $i++) {
            $this -> updateReChannel($from_id[$i], $to_id);

            $sql = "DELETE FROM " . TB_CHANNEL . " WHERE id='" . $from_id[$i] . "'";
            $rs = $db -> Execute($sql);
            if ($rs) {
                $rtn_channel = true;
            } else {
                $rtn_channel = false;
            } 
            $rs -> Close();
        } 

        if ($rtn_channel && $rtn_article) {
            $this -> genCache();
            Common::showOkMsg($lang['saveSuccess'], 'channel_edit.php', 'channel_edit.php?act=edit&selectid=' . $to_id, 'channel.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    } 

    function checkMerge($from_id, $to_id, $is_manage) {
        global $db, $lang;

        if ($from_id == '') Common::showWarningMsg($lang['no_changed']);
        $from_id_ary = $from_id;
        $from_id_ary_count = count($from_id_ary);
        if ($from_id_ary_count == 1 && $from_id_ary[0] == $to_id) Common::showWarningMsg($lang['no_changed']);
        if (!$is_manage) {
            $rtn = $this -> getIsChannelAuth($to_id);
            if (!$rtn) Common::showWarningMsg($lang['checkAuth']);
        } 
        for($i = 0; $i < $from_id_ary_count; $i++) {
            $count_sub_id = dbGetRecordCount(TB_CHANNEL, "id like '" . $from_id_ary[$i] . "__' ");
            if ($count_sub_id > 0) Common::showWarningMsg($lang['no_subcategory']);
            if (!$is_manage) {
                $rtn = $this -> getIsChannelAuth($from_id_ary[$i]);
                if (!$rtn) Common::showWarningMsg($lang['checkAuth']);
            } 
        } 
    } 

    function layout_channel_move() {
        global $db, $lang, $clTemplate, $url;
        global $selectid, $selectValue, $act;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        
        if ($selectValue) $selectid = $selectValue;
        $title = $this -> getChannelTile($selectid);
        $from_id_list = Common::creatClassSelect(TB_CHANNEL, 'id', $selectid);
        $to_id_list = Common::creatClassSelect(TB_CHANNEL, 'id');

        $toolbar = Common::createToolbar($url, 'save', 'channel_move.php?act=save_move');
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar,
                'id' => $selectid,
                'title' => $title,
                'from_id_list' => $from_id_list,
                'to_id_list' => $to_id_list
                ));

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

    function layout_channel_merge() {
        global $db, $lang, $clTemplate, $url;
        global $selectid, $selectValue, $act;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        
        if ($selectValue) $selectid = $selectValue;
        $title = $this -> getChannelTile($selectid);
        $from_id_list = Common::creatClassSelect(TB_CHANNEL, 'id', $selectid);
        $to_id_list = Common::creatClassSelect(TB_CHANNEL, 'id');

        $toolbar = Common::createToolbar($url, 'save', 'channel_merge.php?act=save_merge');
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar,
                'id' => $selectid,
                'title' => $title,
                'from_id_list' => $from_id_list,
                'to_id_list' => $to_id_list
                ));

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

    function layout_channel() {
        global $db, $clTemplate, $url;
        $channel_ids = $this -> getUserChannelIDs();
        $toolbar = '';
        $toolbar .= Common::createToolbar($url, 'add', 'channel_edit.php');
        $toolbar .= Common::createToolbar($url, 'edit', 'channel_edit.php?act=edit');
        $toolbar .= Common::createToolbar($url, 'move', 'channel_move.php');
        $toolbar .= Common::createToolbar($url, 'delete', 'channel.php?act=delete'); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                ));

        $channels = array();
        $this -> getChannels($channels);
        if ($channel_ids[0] != '-1') {
            $channels = $this -> getChannelsByIDs($channels, $channel_ids);
        } 

        $this -> channel_show($channels);

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

    function channel_show(&$channels) {
        global $clTemplate, $url;

        $isedit = Common::checkAdminAuth($url, 'edit');
        $num = 0; 
        // show list---start---
        foreach($channels as $key => $row) {
            $num++;
            $id = $row['id'];
            $tr_id = ' id="' . $id . '"';
            $depth = strlen($id)-2;
            $spaces = '';
            $show_arrow = '';
            $is_orderby = false;
            $is_auth = true;
            $is_disabled = '';

            $show_redirecturl = '';
            if ($row['redirecturl'] != '') {
                $show_redirecturl = "<img title='$row[redirecturl]' src='" . SYS_ADMIN_STYLE_PATH . "images/url.png' border='0'>";
            } 

            if (strlen($id) == 2) {
                $is_orderby = true;
            } 

            if ($depth == 0) { // first floor
                    $orderby = '<b>' . $row['ordernum'] . '</b>';
                $tr_css = 'list_parent_tr_bg';
                $td_css = 'list_parent_td_bg';
                if (!$is_auth)$td_css = 'list_parent_td_disabled_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 = '' . $row['ordernum'] . '';
                $tr_css = 'list_sub_tr_bg';
                $td_css = 'list_sub_td_bg';
                if (!$is_auth)$td_css = 'list_sub_td_disabled_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 ($row['eifrtf_haschild']) { // 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>";
            } 

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

            $clTemplate -> assign_block_vars('ListChannel', 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,
                    'show_redirecturl' => $show_redirecturl,
                    'num' => $num,
                    'id' => $id,
                    'title' => $spaces . '|-' . $row['title'],
                    'orderby' => $orderby,
                    'intro' => Common::showTxtAb($row['intro'], 20, '...'),
                    'status' => $row['status']? Common::createFlagTxt('hidden') : Common::createFlagTxt('display'),
                    'flag' => Common::createFlagShow($row['flag'], $this -> flags),
                    'is_disabled' => $is_disabled
                    ));
        } 
        // show list---end---
    } 

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

        if ($selectValue) $selectid = $selectValue;
        $display_parent = '';
        if ($act == 'edit') {
            Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
            $toolbar = Common::createToolbar($url, 'save', 'channel_edit.php?act=save_edit') . Common::createToolbar($url, 'copy', 'channel_edit.php?act=copy') . Common::createToolbar($url, 'delete', 'channel.php?act=delete');

            $sql = "select * from " . TB_CHANNEL . " where id='" . $selectid . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                $selectid = $rs -> fields['id'];
                $id = $rs -> fields['id'];
                if (strlen($id) == 2) $display_parent = 'none';
                $channel_id = $id;
                $channel_title = $channel_title = dbGetFieldValue(TB_CHANNEL, 'title', "id ='" . substr($id, 0, strlen($rs -> fields['id'])-2) . "'");
                $title = $rs -> fields['title'];
                $intro = $rs -> fields['intro'];
                $template_id = $rs -> fields['template_id'];
                $template_title = dbGetFieldValue(TB_TEMPLATE, 'title', "id='" . $rs -> fields['template_id'] . "'");
                $article_template_id = $rs -> fields['article_template_id'];
                $article_template_title = dbGetFieldValue(TB_TEMPLATE, 'title', "id='" . $rs -> fields['article_template_id'] . "'");
                $redirecturl = $rs -> fields['redirecturl'];
                $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'], $this -> flags);
                $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', 'channel_edit.php?act=save_add');

            $id = '';
            $channel_id = '';
            $channel_title = '';
            if ($selectid != '') {
                $channel_id = $selectid;
                $sql = "select title, redirecturl from " . TB_CHANNEL . " where id='" . $channel_id . "'";
                $row = dbGetRecord1($sql);
//              if ($row['redirecturl'] != '') {
//                  Common::showErrorMsg($lang['no_subcategory']);
//              }
                $channel_title = $row['title'];
            } 
            $title = '';
            $intro = '';
            $template_id = '';
            $template_title = '';
            $article_template_id = '';
            $article_template_title = '';
            $redirecturl = '';
            $fileurl = '';
            $show_img = '';
            $status = Common::creatStatusRadio(0);
            $flag = Common::createFlagRadio(0, $this -> flags);
            $uid = getCookie(COOKIE_UID);
            $username = dbGetFieldValue(TB_USER, TF_USER_NAME, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
            $is_edit = '';
            $isdisabled = '';
            $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,
                'channel_title' => $channel_title,
                'channel_id' => $channel_id,
                'title' => $title,
                'intro' => $intro,
                'template_id' => $template_id,
                'template_title' => $template_title,
                'article_template_id' => $article_template_id,
                'article_template_title' => $article_template_title,
                'redirecturl' => $redirecturl,
                'fileurl' => $fileurl,
                'show_img' => $show_img,
                'status' => $status,
                'flag' => $flag,
                'uid' => $uid,
                'username' => $username,
                'ip' => $ip,
                'addtime' => $addtime,
                'is_edit' => $is_edit,
                'display_parent' => $display_parent,
                'isdisabled' => $isdisabled
                ));

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

    function layout_channel_select() {
        global $db, $clTemplate, $url;
        global $form_input, $selectid, $act;

        $channel_ids = $this -> getUserChannelIDs(); 
        // 'all' indicates can select all channels
        if (kGet('selecturl') == 'all') {
            delSession('eifr_tmp_select_root_channels');
        } 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'form_input' => $form_input,
                'act' => $act
                ));

        $channels = array();
        $this -> getAvailableChannels($channels);
        if ($channel_ids[0] != '-1') {
            $channels = $this -> getChannelsByIDs($channels, $channel_ids);
        } 
        $channels = $this -> getSelectChannels($channels);
        $this -> channel_select_show($channels, $selectid);

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

    function channel_select_show(&$channels, $selectid) {
        global $clTemplate;

        $num = 0; 
        // show list---start---
        foreach($channels as $key => $row) {
            // if redirecturl, then can not be selected
            //if ($row['redirecturl'] != '') {
            //    continue;
            //} 
            $num++;
            $id = $row['id'];
            $tr_id = ' id="' . $id . '"';
            $depth = strlen($id)-2;
            $spaces = '';
            $show_arrow = '';
            $is_auth = true;
            $is_display = '';
            $is_disabled = '';

            if ($depth == 0) { // first floor
                    $tr_css = 'list_parent_tr_bg';
                $td_css = 'list_parent_td_bg';
                if (!$is_auth)$td_css = 'list_parent_td_disabled_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);
                $tr_css = 'list_sub_tr_bg';
                $td_css = 'list_sub_td_bg';
                if (!$is_auth)$td_css = 'list_sub_td_disabled_bg';
                $tr_style = ' style="display:"';
                $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 ($id == $selectid) {
                $tr_css = 'list_mouseover_tr_bg';
                $td_css = 'list_mouseover_td_bg';
            } 

            if ($row['eifrtf_haschild']) { // sub menu
                $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>";
            } 

            if (isset($row['eifrtf_isaddid'])) {
                if ($row['eifrtf_haschild'] && $row['eifrtf_isaddid']) {
                    $is_display = "none";
                    $is_disabled = 'disabled';
                } 
            } 

            $clTemplate -> assign_block_vars('ListChannel', 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 . '|-' . $row['title'],
                    'title_info' => $row['title'],
                    'is_display' => $is_display,
                    'is_disabled' => $is_disabled
                    ));
        } 
        // show list---end---
    } 

    function getIsChannelAuth($id) {
        $is_auth = true;
        $channel_ids = $this -> getUserChannelIDs();
        if ($channel_ids[0] != '-1') {
            if (!in_array($id, $channel_ids)) {
                $is_auth = false;
            } 
        } 
        return $is_auth;
    } 

    function getUserChannelIDs() {
        $rtn = array();
        if (Common::checkSysAdmin()) {
            $rtn[0] = '-1';
        } else { // check user
            $user_channel_id = dbGetFieldValue(TB_USER, TFR_CHANNEL_ID, "" . TF_USER_ID . " ='" . getCookie(COOKIE_UID) . "'");
            $user_channel_id = removeCommaHeadTail($user_channel_id);
            if (strpos($user_channel_id, ',') > 0) {
                $rtn = explode(',', $channel_id);
            } else {
                $rtn[0] = $user_channel_id;
            } 
            if ($rtn[0] == '') { // when user not 'channel_id', check user class
                $user_class_channel_id = dbGetFieldValue(TB_USER_CLASS, TFR_CHANNEL_ID, "" . TF_USER_CLASS_ID . " ='" . getCookie(COOKIE_USERCLASS) . "'");
                $user_class_channel_id = removeCommaHeadTail($user_class_channel_id);
                if (strpos($user_class_channel_id, ',') > 0) {
                    $rtn = explode(',', $user_class_channel_id);
                } else {
                    $rtn[0] = $user_class_channel_id;
                } 
            } 
        } 
        return $rtn;
    } 

    function getChannelTile($id = '') {
        global $db;
        $rtn = '';
        $tmp_ary = array();
        $id_len = strlen($id);
        if ($id_len > 0) {
            for($i = 2; $i <= $id_len; $i = $i + 2) {
                $tmp = substr($id, 0, $i);
                $sql = "select title from " . TB_CHANNEL . " where id='$tmp' order by ordernum ";
                $rs = $db -> Execute($sql);
                if (!$rs -> EOF) {
                    $tmp_ary[] = $rs -> fields['title'];
                } 
                $rs -> Close();
            } 
        } 
        $rtn = implode(' -> ', $tmp_ary);

        return $rtn;
    } 

    function getChannels(&$outdata, $parentid = '') {
        global $db;

        $sql = "select * from " . TB_CHANNEL . " where id like '" . $parentid . "__' order by ordernum ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $rs -> fields['eifrtf_haschild'] = false;
            if (dbGetRecordCount(TB_CHANNEL, "id like '" . $rs -> fields['id'] . "__' ") > 0) { // sub menu
                    $rs -> fields['eifrtf_haschild'] = true;
            } 
            $outdata[$rs -> fields['id']] = $rs -> fields;
            $this -> getChannels($outdata, $rs -> fields['id']);
            $rs -> MoveNext();
        } 
        $rs -> Close();
    } 

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

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

        $sql = "select * from " . TB_CHANNEL . " where status=0 and flag<3 and id like '" . $parentid . "__' order by ordernum ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $rs -> fields['eifrtf_haschild'] = false;
            if (dbGetRecordCount(TB_CHANNEL, "id like '" . $rs -> fields['id'] . "__' ") > 0) { // sub menu
                    $rs -> fields['eifrtf_haschild'] = true;
            } 

            $outdata[$rs -> fields['id']] = array('id' => $rs -> fields['id'],
                'title' => $rs -> fields['title'],
                'flag' => $rs -> fields['flag'],
                'redirecturl' => $rs -> fields['redirecturl'],
                'template_id' => $rs -> fields['template_id'],
                'article_template_id' => $rs -> fields['article_template_id'],
                'eifrtf_haschild' => $rs -> fields['eifrtf_haschild']
                );
            $this -> getAvailableChannels($outdata, $rs -> fields['id']);
            $rs -> MoveNext();
        } 
        $rs -> Close();
    } 

    function getChannelsByIDs($channels, $channel_ids) {
        global $db, $clTemplate, $url;

        ksort($channel_ids);

        $rtn = array();
        $channel_ids_len = count($channel_ids);
        for($i = 0; $i < $channel_ids_len; $i++) {
            $id = $channel_ids[$i];
            Log_v('', '', 'id:' . $id);
            $id_len = strlen($id); 
            // add parent id
            for($l = 2;$l <= $id_len; $l = $l + 2) {
                $tmpid = substr($id, 0, $l);
                if (!array_key_exists($tmpid, $rtn)) {
                    $rtn[$tmpid] = $channels[$tmpid];

                    $channels[$tmpid]['eifrtf_haschild'] = false;
                    $channels[$tmpid]['eifrtf_isaddid'] = false;
                    if ($tmpid != $id) {
                        $channels[$tmpid]['eifrtf_isaddid'] = true;
                        $channels[$tmpid]['eifrtf_haschild'] = false;
                    } 
                    // e.g. 02,0201 then 02 has child
                    $pid = substr($tmpid, 0, strlen($tmpid)-2);
                    Log_v('', '', 'tmpid:' . $id . ',pid:' . $pid);
                    if ($pid != '') {
                        $rtn[$pid]['eifrtf_haschild'] = true;
                    } 
                } 
            } 
        } 

        return $rtn;
    } 

    function genCache() {
        $channels = array();
        $cacheHelper = new CCacheHelper('db_channel');
        $cacheHelper -> deleteCache();
        $this -> getAvailableChannels($channels);
        $cacheHelper -> writeCache($channels);
    } 

    public static function getChannelById($id) {
        if (empty($id)) {
            return false;
        } 
        $cacheHelper = new CCacheHelper('db_channel');
        $channels = $cacheHelper -> getCache();
        if ($channels) {
            if (array_key_exists($id, $channels)) {
                Log_v(__FILE__, __LINE__, 'getChannelById from cache');
                return $channels[$id];
            } 
        } else {
            Log_v(__FILE__, __LINE__, 'getChannelById from db');
            return dbGetRecord1("select * from " . TB_CHANNEL . " where id='$id' and status=0 and flag<3 ");
        } 

        return false;
    } 

    function getSelectChannels(&$channels) {
		$rtn = array();
        if (!isSession('eifr_tmp_select_root_channels')) return $channels;

        $channel_ids = getSSession('eifr_tmp_select_root_channels'); 
        // delSession('eifr_tmp_select_root_channels');
        if (!$channel_ids) return $channels;

		if(! is_array($channels)) return $rtn;
		
        foreach($channels as $key => $val) {
            foreach($channel_ids as $k => $v) {
                // if(strpos($key, $v)===0) {
                if (substr($key, 0, strlen($v)) == $v) {
                    $rtn[$key] = $val;
                } 
            } 
        } 
        return $rtn;
    } 

    /**
     * ---isInArray2---
     * check is in array of array
     */
    function isInArray2($inval, $ary2) {
        foreach ($ary2 as $key => $ary) {
            if ($inval == $ary[0]) {
                return true;
            } 
        } 
        return false;
    } 
} 

    ?>
