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

class Common {

    /**
     * ---setLoginErrornum---
     */
    public static function setLoginErrornum() {
        if (isSession(SESSION_ADMIN_LOGIN_ERRORNUM)) {
            setSession(SESSION_ADMIN_LOGIN_ERRORNUM, getSession(SESSION_ADMIN_LOGIN_ERRORNUM) + 1);
        } else {
            setSession(SESSION_ADMIN_LOGIN_ERRORNUM, 1);
        } 
    } 

    /**
     * ---checkLoginErrornum---
     */
    public static function checkLoginErrornum($maxnum = 3) {
        $rtn = true;
        if (isSession(SESSION_ADMIN_LOGIN_ERRORNUM)) {
            if (getSession(SESSION_ADMIN_LOGIN_ERRORNUM) >= $maxnum)
                $rtn = false;
        } 
        return $rtn;
    } 

    public static function setLoginSession($rs_array) {
        $style_id = SYS_DEFAULT_STYLE;
        $only_login = 0;
        if ($rs_array['parameter'] != '') {
            $param_arr = unserialize($rs_array['parameter']);
            if (is_array($param_arr)) {
                if (isset($param_arr['style_id'])) $style_id = $param_arr['style_id'];
                if (isset($param_arr['only_login'])) $only_login = $param_arr['only_login'];
            } 
        } 

        addCookie(COOKIE_USERSTYLE, $style_id);
        addCookie(COOKIE_UID, $rs_array[TF_USER_ID]);
        addCookie(COOKIE_USERNAME, $rs_array[TF_USER_NAME]);
        addCookie(COOKIE_NICKNAME, $rs_array[TF_USER_NICK]);
        addCookie(COOKIE_USERCLASS, $rs_array[TFR_USER_CLASS_ID]);
        addCookie(COOKIE_CHANNELID, '');
        
        require_once(EIFR_ROOT . 'admin/mod_user/class_user.php');
        addCookie(COOKIE_UNDERUIDS, ComUser :: getUidsBossUid($rs_array[TF_USER_ID]));

        if ($only_login == 1) {
            setSession(COOKIE_UID, $rs_array[TF_USER_ID]);
            setSession(COOKIE_USERNAME, $rs_array[TF_USER_NAME]);
        } 
    } 

    public static function addLoginLog() {
        if (! IS_ADDLOG) return;

        global $db;
        $lasttime = time();
        $lastip = getIP();

        $sql = "update " . TB_USER . " set lastip='$lastip', lasttime='$lasttime' where " . TF_USER_ID . "=" . getCookie(COOKIE_UID) . "";
        $rs = $db -> Execute($sql);
        $rs -> Close();
    } 

    public static function checkLogin($username, $password, $maxnum = 3) {
        $rtn = false;
        Log_d(__FILE__, __LINE__, "checkLogin, username:$username, password:$password, maxnum:$maxnum");
        if (self::checkLoginErrornum($maxnum)) {
            global $db;
            $sql = "SELECT * FROM " . TB_USER . " WHERE " . TF_USER_NAME . "='" . $username . "' and " . TF_USER_PASS . "='" . $password . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                self::setLoginSession($rs -> fields);
                self::addLoginLog();

                $rs -> Close();
                delSession(SESSION_ADMIN_LOGIN_ERRORNUM);
                $rtn = true;
            } else {
                $rs -> Close();
                self::setLoginErrornum();
            } 
        } 
        Log_d(__FILE__, __LINE__, 'checkLogin, rc:' . $rtn);
        return $rtn;
    } 

    public static function logout() {
        session_start();
        session_destroy();
        delCookie(COOKIE_UID);
        delCookie(COOKIE_USERNAME);
        delCookie(COOKIE_NICKNAME);
        delCookie(COOKIE_USERCLASS);
        delCookie(COOKIE_UNDERUIDS);
        delCookie(COOKIE_CHANNELID);
    } 


    /**
     * ---checkAdminFileAuth---
     * check admin file authority
     * 
     * @param string $url =''
     */
    public static function checkAdminFileAuth($url = '') {
        $rtn = false;

        if (self::checkSysAdmin()) {
            $rtn = true;
        } else {
            require_once(EIFR_ROOT . 'admin/mod_adminmenu/acl_adminmenu.php');
            $acl_adminmenu = new CAclAdminmenu();
            $rtn = $acl_adminmenu -> checkUrlAccess($url);
        } 

        if (!$rtn) {
            global $lang;
            self::showWarningMsg($lang['checkAuth']);
            exit();
        } 
    } 

    /**
     * ---checkAdminAuth---
     * check admin  authority type
     * 
     * @param string $url ='',$authtype=''
     * @return bool 
     */
    public static function checkAdminAuth($url = '', $authtype = '') {
        if (self::checkSysAdmin()) {
            return true;
        } else {
            require_once(EIFR_ROOT . 'admin/mod_adminmenu/acl_adminmenu.php');
            $acl_adminmenu = new CAclAdminmenu();
            return $acl_adminmenu -> checkActionAccess($authtype, $url);
        } 

        return false;
    } 

    /**
     * ---checkAdminExeAuth---
     * check admin Execute
     * 
     * @param string $url ='',$authtype=''
     */
    public static function checkAdminExeAuth($url = '', $authtype = '') {
        if (!self::checkSysAdmin()) {
            if (!self::checkAdminAuth($url, $authtype)) {
                global $lang;
                self::showWarningMsg($lang['checkAuth']);
                exit();
            } 
        } 
    }
    
    public static function checkAdminExeAuthByUid($uid)
    {
        if ($uid == getCookie(COOKIE_UID)) {
            return;
        }
        
        if(getCookie(COOKIE_UNDERUIDS) != '') {
            $uidArr = explode(',', getCookie(COOKIE_UNDERUIDS));
            if (in_array($uid, $uidArr))
                return;
        }

        global $lang;
        self::showWarningMsg($lang['checkAuth']);
    }
    
    /**
     * ---checkSysAdmin()---
     * is system admin to check
     * 
     * @param string $url ,$authtype
     * @return bool 
     */
    public static function checkSysAdmin() {
        $rtn = false; 
        // Log_v('','checkSysAdmin', getSession('session_sysadmin').' | '.getCookie(COOKIE_USERNAME));
        if (IS_SYSADMIN && getSession('session_sysadmin') != '' && getSession('session_sysadmin') == getCookie(COOKIE_USERNAME)) {
            $rtn = true;
        } 
        return $rtn;
    }

    /**
     * ---creatInputSingleText---
     * 
     * @param string $inputname ='',$value='
     * @return string 
     */
    public static function creatInputSingleText($inputname = '', $value = '') {
        return '<input type="text" name="' . $inputname . '" class="input_text" value="' . $value . '">';
    } 

    /**
     * ---creatInputCheckbox---
     * 
     * @param string $inputname ='',$value='
     * @return string 
     */
    public static function creatInputCheckbox($inputname = '', $value = '', $ischeck = 0) {
        $rtn = '';
        $checkvalue = '';
        if ($ischeck) $checkvalue = ' checked';
        $rtn .= '<input type="checkbox" name="' . $inputname . '" class="input_checkbox" value="' . $value . '" ' . $checkvalue . '>';
        return $rtn;
    } 

    /**
     * ---creatInputMultiText---
     * 
     * @param string $inputname ='',$value='
     * @return string 
     */
    public static function creatInputMultiText($inputname = '', $value = '') {
        return '<textarea name="' . $inputname . '" class="input_textarea" rows="6" style="width:90%">' . $value . '</textarea>';
    } 

    /**
     * ---creatSelect---
     * list common list/menu
     * 
     * @param string $tb table name
     * @param string $fieldname table field name
     * @param string $select =''  selected id
     * @param string $wherevalue =''
     * @return string 
     */
    public static function creatSelect($tablename, $valuefield, $showfield, $select = '', $wherevalue = '') {
        global $db;
        $rtn = '';
        $sqlstr = '';
        if ($wherevalue) {
            $sqlstr = " where " . $wherevalue . "";
        } 

        $sql = "select " . $valuefield . ", " . $showfield . " from " . $tablename . " " . $sqlstr . " ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $e_s = '';
            if ($rs -> fields[$valuefield] == $select) {
                $e_s = " selected";
                $select = '';
            } 
            $rtn .= "<option value='" . $rs -> fields[$valuefield] . "' " . $e_s . ">" . $rs -> fields[$showfield] . "</option>\n";
            $rs -> MoveNext();
        } 
        $rs -> Close();

        return $rtn;
    } 

    /**
     * ---createClassNav---
     * category navigation
     * 
     * @param string $tablename ,$valuefield,$showfield,$selectid=''
     * @param int $idlen 
     * @return string 
     */
    public static function createClassNav($tablename, $valuefield, $showfield, $selectid = '', $idlen = 0) {
        global $db;
        $rtn = '';
        if ($selectid != '' && $idlen < strlen($selectid)) {
            $idlen += 2;
            $sql = "select " . $showfield . " from " . $tablename . " where " . $valuefield . "='" . substr($selectid, 0, $idlen) . "'";
            $rs = $db -> Execute($sql);
            if (!$rs -> EOF) {
                $rtn = "&gt;&gt;" . $rs -> fields[$showfield] . "";
            } 
            $rs -> Close();
            $rtn .= self::createClassNav($tablename, $valuefield, $showfield, $selectid, $idlen);
        } 
        Return $rtn;
    } 

    /**
     * ---creatClassSelect---
     * list class list/menu
     * 
     * @param string $tb table name
     * @param string $fieldname table field name
     * @param string $select =''  selected id
     * @param string $wherevalue =''
     * @return string 
     */
    public static function creatClassSelect($tablename, $fieldname, $select = '', $wherevalue = '') {
        global $db;
        $rtn = '';
        $sqlstr = '';
        if ($wherevalue) {
            $sqlstr = " where " . $wherevalue . "";
        } 

        $sql = "select " . $fieldname . ",title from " . $tablename . " " . $sqlstr . " order by " . $fieldname . " asc";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $depth = strlen($rs -> fields[$fieldname])-2;
            $spaces = '';
            if ($depth > 0) $spaces = str_repeat("&nbsp;", $depth);
            $e_s = '';
            if ($rs -> fields[$fieldname] == $select) {
                $e_s = "selected";
                $select = '';
            } 
            $rtn .= "<option value='" . $rs -> fields[$fieldname] . "' " . $e_s . "> " . $spaces . "├ " . $rs -> fields['title'] . "";
            $rtn .= "</option>\n";

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

        return $rtn;
    } 

    /**
     * ---createOptionsByArray---
     * 
     * @param string $arrname ,$flag=''
     * @return string 
     */
    public static function createOptionsByArray($arrname, $flag = '') {
        global $lang;
        $rtn = '';
        if (!is_numeric($flag)) $flag = -1;
        reset($arrname);
        foreach($arrname AS $key => $value) {
            $is_select = '';
            if ($value == $flag) {
                $is_select = ' selected';
            } 
            $showvalue = $key;
            if (array_key_exists($key, $lang)) $showvalue = $lang[$key];
            $rtn .= "<option value='" . $value . "' " . $is_select . ">" . $showvalue . "</option>\n";
        } 

        return $rtn;
    } 

    /**
     * ---createRadiosByArray---
     * 
     * @param string $input_name ='',$arrname,$flag=''
     * @return string 
     */
    public static function createRadiosByArray($input_name = '', $arrname, $flag = '') {
        global $lang;
        $rtn = '';
        if (!is_numeric($flag)) $flag = -1;
        reset($arrname);
        foreach($arrname AS $key => $value) {
            $is_check = '';
            if ($value == $flag) {
                $is_check = ' checked';
            } 
            $showvalue = $key;
            if (array_key_exists($key, $lang)) $showvalue = $lang[$key];
            $rtn .= "<input type='radio' name='" . $input_name . "' value='" . $value . "' " . $is_check . ">" . $showvalue . "&nbsp;\n";
        } 

        return $rtn;
    } 


    /**
     * ---createTxtShowByArray---
     * 
     * @param string $arrname ,$value=''
     * @return string 
     */
    public static function createTxtShowByArray($arrname, $value = '') {
        global $lang;
        $rtn = array_search($value, $arrname);
        if ($rtn === false) $rtn = 'unknown';
        if (array_key_exists($rtn, $lang)) {
            $rtn = $lang[$rtn];
        } 
        return $rtn;
    } 

    /**
     * ---createFlagTxt---
     * create flag to web gui
     * 
     * @param string $showtype =''
     */
    public static function createFlagTxt($showtype = '') {
        global $lang;
        $rtn = '';
        $flag_value = $showtype;
        if (array_key_exists($showtype, $lang)) {
            $flag_value = $lang[$showtype];
        } 
        switch ($showtype) {
            case 'delete':
                $rtn = "<font color='#800040'>" . $flag_value . "</font>";
                break;
            case 'display':
            case 'open':
                $rtn = $flag_value;
                break;
            case 'locked': // don't deletle by user
            case 'default':
            case 'selected':
            case 'navigation':
                $rtn = "<font color='#0000FF'>" . $flag_value . "</font>";
                break;
            case 'hidden':
            case 'unchecked':
                $rtn = "<font color='#CCCCCC'>" . $flag_value . "</font>";
                break;
            case 'stop':
                $rtn = "<font color='#FF0000'>" . $flag_value . "</font>";
                break;
            case 'unknown':
            default :
                $rtn = "<font color='#000'>" . $flag_value . "</font>";
                break;
        } 
        return $rtn;
    } 

    /**
     * ---createFlagShow---
     * create flag to web gui
     * 
     * @param int $flag =-1
     */
    public static function createFlagShow($flag = -1, $flag_txt_arr = array('unchecked', 'open', 'locked', 'stop', 'delete')) {
        $rtn = '';
        if (array_key_exists($flag, $flag_txt_arr)) {
            $rtn = self::createFlagTxt($flag_txt_arr[$flag]);
        } else {
            $rtn = self::createFlagTxt('unknown');
        } 

        return $rtn;
    } 

    /**
     * ---creatFlagCheck---
     * create input check flag to web gui
     * 
     * @param string $radioname ='',$radiovalue='',$showvalue=''
     * @param bool $ischecked =false,$ischeckbox=false
     * @return string 
     */
    public static function creatFlagCheck($radioname = '', $radiovalue = '', $showvalue = '', $ischecked = false, $ischeckbox = false) {
        global $lang;
        $rtn = '';
        $type = 'radio';
        $class = 'input_radio';
        $checked = '';
        if ($ischecked) {
            $checked = ' checked';
        } 
        if ($ischeckbox) {
            $type = 'checkbox';
            $class = 'input_checkbox';
        } 
        if (array_key_exists($showvalue, $lang)) {
            $rtn = '<input type="' . $type . '" name="' . $radioname . '" class="' . $class . '" value="' . $radiovalue . '" ' . $checked . '>' . $lang[$showvalue] . '';
        } else {
            $rtn = '<input type="' . $type . '" name="' . $radioname . '" class="' . $class . '" value="' . $radiovalue . '" ' . $checked . '>' . $showvalue . '';
        } 

        return $rtn;
    } 
    
    /**
     * ---cTagSelect---
     * create select tag 
     * @param $selectAttrs = array(), $options = array(), $selectValues = array()
     * @return string 
     */
    public static function cTagSelect($selectAttrs = array(), $options = array(), $selectValues = array()) {
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';
        
        // fill options
        foreach ($options as $row) {
            $e_s = '';
            if (in_array($row['value'], $selectValues, true)) {
                $e_s = ' selected';
            } 
            $rtn .= "<option value='" . $row['value'] . "' " . $e_s . ">" . $row['title'] . "</option>\n";
        }
        
        $rtn .= '</select>';
        return $rtn;
    }
    
    public static function cTagFlagSelect($selectAttrs = array(), $flag = '') {
        global $lang;
        $flags = array('flag_select'=>'', 'unchecked'=>0, 'open'=>1, 'locked'=>2, 'stop'=>3, 'delete'=>4);
        $options = array();
        foreach ($flags as $key=>$val) {
            $title = $key;
            if (array_key_exists($key, $lang)) $title = $lang[$key];
            $options[] = array('title'=>$title, 'value'=>$val);
        }

        $selvals = array($flag);
        return Common::cTagSelect($selectAttrs, $options, $selvals);
    }
    
    public static function cTagStatusSelect($selectAttrs = array(), $status = '') {
        global $lang;
        $statuses = array('status_select'=>'', 'display'=>0, 'hidden'=>1);
        $options = array();
        foreach ($statuses as $key=>$val) {
            $title = $key;
            if (array_key_exists($key, $lang)) $title = $lang[$key];
            $options[] = array('title'=>$title, 'value'=>$val);
        }

        $selvals = array($status);
        return Common::cTagSelect($selectAttrs, $options, $selvals);
    }
    
    /**
     * ---cTagChannelSelect---
     * create select tag for Channel
     * @param $selectAttrs = array(), $channelId = ''
     * @return string 
     */
    public static function cTagChannelSelect($selectAttrs = array(), $channelId = '') {
        global $lang;
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';

        // fill options
        $rtn .= '<option value="">+---' . $lang["channel"] . '---</option>';
        
        $cacheHelper = new CCacheHelper('db_channel');
        $channels = $cacheHelper -> getCache();
        if (! $channels) {
            Log_v(__FILE__, __LINE__, 'cTagChannelSelect from db');
            $sql = "select id, title from " . TB_CHANNEL . " where status=0 and flag<3 order by ordernum";
            $channels = dbGetRecordn($sql);
        }
        foreach ($channels as $row) {
            $depth = strlen($row['id'])-2;
            $spaces = '';
            if ($depth > 0) $spaces = str_repeat("&nbsp;", $depth);
            $e_s = '';
            if ($row['id'] == $channelId) {
                $e_s = "selected";
                $channelId = '';
            } 
            $rtn .= "<option value='" . $row['id'] . "' " . $e_s . "> " . $spaces . "├ " . $row['title'] . "</option>\n";
        }
        
        $rtn .= '</select>';
        return $rtn;
    }

    /**
     * ---cTagUserClassSelect---
     * create select tag for User Class
     * @param $selectAttrs = array(), $user_class_id = ''
     * @return string 
     */
    public static function cTagUserClassSelect($selectAttrs = array(), $user_class_id = '') {
        global $lang;
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';

        // fill options
        $rtn .= '<option value="">+---' . $lang["user_class_select"] . '---</option>';
        
        $cacheHelper = new CCacheHelper('db_user_class');
        $userClasses = $cacheHelper -> getCache();
        if (! $userClasses) {
            Log_v(__FILE__, __LINE__, 'cTagUserClassSelect from db');
            $sql = "select id, title from " . TB_USER_CLASS . " where status=0 and flag<3 order by ordernum";
            $userClasses = dbGetRecordn($sql);
        }
        foreach ($userClasses as $row) {
            $depth = strlen($row['id'])-2;
            $spaces = '';
            if ($depth > 0) $spaces = str_repeat("&nbsp;", $depth);
            $e_s = '';
            if ($row['id'] == $user_class_id) {
                $e_s = "selected";
                $user_class_id = '';
            } 
            $rtn .= "<option value='" . $row['id'] . "' " . $e_s . "> " . $spaces . "├ " . $row['title'] . "</option>\n";
        }
        
        $rtn .= '</select>';
        return $rtn;
    }
    
    public static function cTagChannelChildSelect($selectAttrs = array(), $pcid='', $channelId = '') {
        global $lang;
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';

        // fill options
        $cacheHelper = new CCacheHelper('db_channel');
        $channels = $cacheHelper -> getCache();
        if (! $channels) {
            Log_v(__FILE__, __LINE__, 'cTagChannelSelect from db');
            $sql = "select id, title from " . TB_CHANNEL . " where status=0 and flag<3 order by ordernum";
            $channels = dbGetRecordn($sql);
        }
        foreach ($channels as $row) {
            $pcidlen = strlen($pcid);
            if (substr($row['id'], 0, $pcidlen)==$pcid && strlen($row['id']) > $pcidlen) {
                $e_s = '';
                if ($row['id'] == $channelId) {
                    $e_s = "selected";
                    $channelId = '';
                } 
                $rtn .= "<option value='" . $row['id'] . "' " . $e_s . "> " . $row['title'] . "</option>\n";
            }
        }
        
        $rtn .= '</select>';
        return $rtn;
    }
    
    /**
     * ---cTagLayoutMSelect---
     * 
     * @param string $selectAttrs = array(),$selectValues = ''
     * @return string 
     */
    public static function cTagLayoutMSelect($selectAttrs = array(), $selectValues = '') {
        global $db;
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';

        $e_s = ' selected';
        if ($selectValues != '') {
            require_once(EIFR_ROOT . 'admin/mod_template/class_template.php');
            $layoutArr = explode(',', $selectValues);
            foreach ($layoutArr as $val) {
                $layout = ComTemplate::getTemplateLayoutById($val);
                if($layout) {
                    $template = ComTemplate::getTemplateByLayoutId($val);
                    $showtxt = $template['title'];
                    $showtxt .= '->' . $layout['title'];
                    $rtn .= "<option value='" . $layout['id'] . "' selected>" . $showtxt . "</option>\n";
                }
            } 
        }

        $rtn .= '</select>';
        return $rtn;
    } 

    /**
     * ---cTagAddressSelect---
     * create select tag for address
     * @param $selectAttrs = array(), $id = ''
     * @return string 
     */
    public static function cTagAddressSelect($selectAttrs = array(), $id = '') {
        global $lang;
        $rtn = '<select';
        // fill select attr
        foreach ($selectAttrs as $key=>$val) {
            $rtn .= " $key='$val'";
        }
        $rtn .= '>';

        // fill options
        $rtn .= '<option value="">+---' . $lang["address_select"] . '---</option>';
        
        $cacheHelper = new CCacheHelper('db_address');
        $addresses = $cacheHelper -> getCache();
        foreach ($addresses as $row) {
            $depth = strlen($row['id'])-2;
            $spaces = '';
            if ($depth > 0) $spaces = str_repeat("&nbsp;", $depth);
            $e_s = '';
            if ($row['id'] == $id) {
                $e_s = 'selected';
                $id = '';
            } 
            $rtn .= "<option value='" . $row['id'] . "' " . $e_s . "> " . $spaces . "├ " . $row['title'] . "</option>\n";
        }
        
        $rtn .= '</select>';
        return $rtn;
    }
    
    /**
     * ---createFlagSelect---
     * 
     * @param string $flag 
     * @return string 
     */
    public static function createFlagSelect($flag = '') {
        global $lang;
        $rtn = '';
        $flag_txt_arr = array('unchecked', 'open', 'locked', 'stop', 'delete');
        if (!is_numeric($flag)) $flag = -1;
        for($i = 0; $i < count($flag_txt_arr);$i++) {
            $e_s = '';
            if ($i == $flag) {
                $e_s = ' selected';
                $flag = '';
            } 
            $showvalue = $flag_txt_arr[$i];
            if (array_key_exists($flag_txt_arr[$i], $lang)) $showvalue = $lang[$flag_txt_arr[$i]];
            $rtn .= "<option value='" . $i . "' " . $e_s . ">" . $showvalue . "</option>\n";
        } 

        return $rtn;
    } 

    /**
     * ---createFlagRadio---
     * 
     * @param string $flag 
     * @return string 
     */
    public static function createFlagRadio($flag = '', $flag_txt_arr = array('unchecked', 'open', 'locked', 'stop', 'delete')) {
        global $lang;
        $rtn = '';
        if (!is_numeric($flag)) $flag = -1;
        for($i = 0; $i < count($flag_txt_arr);$i++) {
            $e_s = '';
            if ($i == $flag) {
                $e_s = ' checked';
                $flag = '';
            } 
            $showvalue = $flag_txt_arr[$i];
            if (array_key_exists($flag_txt_arr[$i], $lang)) $showvalue = $lang[$flag_txt_arr[$i]];
            $rtn .= "<input type='radio' name='flag' value='" . $i . "' " . $e_s . ">" . $showvalue . "&nbsp;\n";
        } 

        return $rtn;
    } 

    /**
     * ---creatStatusRadio---
     * create starus input radio to web gui
     * 
     * @param string $status =''(0:display,1:hidden)
     * @return string 
     */
    public static function creatStatusRadio($status = '') {
        global $lang;
        $rtn = '';
        $status_arr = array(0, 1);
        $status_txt_arr = array('display', 'hidden');
        if (!is_numeric($status)) $status = -1;
        for($i = 0; $i < 2;$i++) {
            $e_s = '';
            if ($status_arr[$i] == $status) {
                $e_s = ' checked';
                $status = '';
            } 
            $showvalue = $status_txt_arr[$i];
            if (array_key_exists($status_txt_arr[$i], $lang)) $showvalue = $lang[$status_txt_arr[$i]];
            $rtn .= "<input type='radio' name='status' value='" . $status_arr[$i] . "' " . $e_s . ">" . $showvalue . "&nbsp;\n";
        } 

        return $rtn;
    } 

    /**
     * ---createStatusTxt---
     * 
     * @param string $status =''
     * @return string 
     */
    public static function createStatusTxt($status = '') {
        $rtn = '';
        $status_arr = array(0, 1);
        $status_txt_arr = array('display', 'hidden');
        if (!is_numeric($status)) $status = -1;
        if (in_array($status, $status_arr)) {
            $rtn = self::createFlagTxt($status_txt_arr[$status]);
        } else {
            $rtn = self::createFlagTxt('unknown');
        } 

        return $rtn;
    } 

    /**
     * ---createStatusSelect---
     * 
     * @param string $status =''
     * @return string 
     */
    public static function createStatusSelect($status = '') {
        global $lang;
        $rtn = '';
        $status_arr = array(0, 1);
        $status_txt_arr = array('display', 'hidden');
        if (!is_numeric($status)) $status = -1;
        for($i = 0; $i < 2;$i++) {
            $e_s = '';
            if ($status_arr[$i] == $status) {
                $e_s = ' selected';
                $$status = '';
            } 
            $showvalue = $status_txt_arr[$i];
            if (array_key_exists($status_txt_arr[$i], $lang)) $showvalue = $lang[$status_txt_arr[$i]];
            $rtn .= "<option value='" . $status_arr[$i] . "' " . $e_s . ">" . $showvalue . "</option>\n";
        } 

        return $rtn;
    } 

    /**
     * ---createJumpMenu---
     * 
     * @param string $tb ,$valuefield,$showfield,$jumpurl='',$wherevalue=''
     * @return string 
     */
    public static function createJumpMenu($tablename, $valuefield, $showfield, $jumpurl = '', $select = '', $wherevalue = '') {
        global $db;
        $rtn = '';
        $sqlstr = '';
        if ($wherevalue) {
            $sqlstr = " where " . $wherevalue . "";
        } 

        $sql = "select " . $valuefield . ", " . $showfield . " from " . $tablename . $sqlstr . " ";
        $rs = $db -> Execute($sql);
        while (!$rs -> EOF) {
            $e_s = '';
            if ($rs -> fields[$valuefield] == $select) {
                $e_s = ' selected';
                $select = '';
            } 
            $rtn .= "<option value=" . $jumpurl . "=" . $rs -> fields[$valuefield] . " " . $e_s . ">" . $rs -> fields[$showfield] . "</option>\n";

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

    /**
     * ---createArticleSelect---
     * 
     * @param string $article_list 
     * @return string 
     */
    public static function createArticleSelect($article_list) {
        $rtn = '';
        $e_s = ' selected';
        if ($article_list != '') {
            $article_list_arr = explode(',', $article_list);
            $arr_count = count($article_list_arr);
            for($i = 0; $i < $arr_count; $i++) {
                $rtn .= "<option value='" . $article_list_arr[$i] . "' " . $e_s . ">" . dbGetFieldValue(TB_ARTICLE, 'title', "id='" . $article_list_arr[$i] . "'") . "</option>\n";
            } 
        } 
        return $rtn;
    } 

    /**
     * ---createLayoutSelect---
     * 
     * @param string $layout_list 
     * @return string 
     */
    public static function createLayoutSelect($layout_list) {
        global $db;
        $rtn = '';
        $e_s = ' selected';
        if ($layout_list != '') {
            $layout_list_arr = explode(',', $layout_list);
            $arr_count = count($layout_list_arr);
            for($i = 0; $i < $arr_count; $i++) {
                $sql = "select * from " . TB_TEMPLATE_LAYOUT . " where id=" . $layout_list_arr[$i] . "";
                $rs = $db -> Execute($sql);
                if (!$rs -> EOF) {
                    // data
                    $title = $rs -> fields['title'];
                    $template_id = $rs -> fields['template_id'];
                    $template_title = dbGetFieldValue(TB_TEMPLATE, 'title', "id='" . $template_id . "'");
                    if ($template_title) $showtxt = $template_title . '->' . $title;
                    $rtn .= "<option value='" . $layout_list_arr[$i] . "' " . $e_s . ">" . $showtxt . "</option>\n";
                } 
                $rs -> Close();
            } 
        } 
        return $rtn;
    } 

    /**
     * ---createChannelSelect---
     * 
     * @param string $channel_list 
     * @return string 
     */
    public static function createChannelSelect($channel_list) {
        $rtn = '';
        $e_s = ' selected';
        if ($channel_list != '') {
            $channel_list_arr = explode(',', $channel_list);
            $arr_count = count($channel_list_arr);
            for($i = 0; $i < $arr_count; $i++) {
                $rtn .= "<option value='" . $channel_list_arr[$i] . "' " . $e_s . ">" . dbGetFieldValue(TB_CHANNEL, 'title', "id='" . $channel_list_arr[$i] . "'") . "</option>\n";
            } 
        } 
        return $rtn;
    } 

    /**
     * ---checkUsername---
     * check is invalid?
     * 
     * @param string $str 
     * @param int $mixlen =2,$maxlen=20
     */
    public static function checkUsername($str, $minslen = 2, $maxslen = 20) {
        $rtn_len = false;
        $slen = strlen($str);
        if (($slen - $maxslen > 0) || ($minslen - $slen > 0)) $rtn_len = true;
        $rtn_match = preg_match("/[;%'<>\\\?\*\$\r\n\t]/", $str);
        if ($rtn_len || $rtn_match) return false;
        else return true;
    } 

    /**
     * ---checkValid---
     * check input string
     * 
     * @param string $str ,$msg=''
     * @return String 
     */
    public static function checkValid($str, $msg = '') {
        if ($msg) {
            $msg = '"' . $msg . '"';
        } 
        return $str;
    } 

    /**
     * ---checkOverMaxNum---
     * check $num is over $maxnum
     * 
     * @param int $num ,$maxnum
     */
    public static function checkOverMaxNum($num, $maxnum) {
        global $lang;
        if ($num > $maxnum) {
            self::showMsg($lang['overMaxNum'] . '"' . $maxnum . '"', '', '-1');
            exit();
        } 
    } 

    /**
     * ---checkEditDataIsExist---
     * check edit date value to exist.
     * edit data when $newvalue!= $originalvalue.
     * 
     * @param string $tablename 
     * @param string $wherefield 
     * @param string $newvalue 
     * @param string $originalvalue =''
     * @param string $wherevalue =''
     */
    public static function checkEditDataIsExist($tablename, $wherefield, $newvalue, $originalvalue = '', $wherevalue = '') {
        global $db, $lang;

        $rtn = false;
        $sqlstr = '';
        if ($wherevalue) {
            $sqlstr = " and " . $wherevalue . "";
        } 
        if ($newvalue != $originalvalue) {
            $sql = "SELECT count(*) as num FROM " . $tablename . " where " . $wherefield . "='" . $newvalue . "' " . $sqlstr . "";
            $rs = $db -> Execute($sql);
            if ($rs -> fields['num'] != 0) {
                $rtn = true;
            } 

            $rs -> Close();
        } 

        if ($rtn) {
            self::showMsg('"' . $newvalue . '"' . $lang['exist'], '', '-1');
            exit();
        } 
    } 

    /**
     * ---createOrderBy---
     * create html( order by )
     * 
     * @param string $url ='',$exurl=''
     * @return string 
     */
    public static function createOrderBy($url = '', $exurl = '') {
        global $lang;
        return "[<a href=" . $url . "?act=up" . $exurl . " title='" . $lang['orderUp'] . "'><font color=#339900>↑</font></a><a href=" . $url . "?act=down" . $exurl . " title='" . $lang['orderDown'] . "'><font color=#339900>↓</font></a>]";
    } 

    
    /**
     * ---createImgButton---
     * create button
     * 
     * @param string $btn ='',$tourl='',$style=''
     * @param bool $is_confirm =false
     * @return string 
     */  
    public static function createImgButton($label = '', $tourl = '', $target = '', $style = '') {
        global $lang;
        if (array_key_exists($label, $lang)) 
            $btn_value = $lang[$label];
        else 
            $btn_value = $label;

        if ($style === '') {
            $style = 'btn_' . $label;
        } 

        return "<span class='$style'><a href='$tourl' title='$btn_value' target='$target'>$btn_value</a></span>&nbsp;";
    } 
    
    /**
     * ---createButton---
     * create button
     * 
     * @param string $btn ='',$tourl='',$style=''
     * @param bool $is_confirm =false
     * @return string 
     */
    public static function createButton($btn = '', $tourl = '', $is_confirm = false, $style = '', $jsfunc = '') {
        global $lang;
        $rtn = '';

        if ($style == $btn) {
            $style = 'btn_' . $btn;
        } 
        if ($is_confirm) {
            $is_confirm = 'true';
        } else {
            $is_confirm = 'false';
        } 

        if (array_key_exists($btn, $lang)) $btn_value = $lang[$btn];
        else $btn_value = $btn;

        $onclickjs = "submitButton('" . $tourl . "','" . $btn_value . "'," . $is_confirm . ")";
        if ($jsfunc) $onclickjs = $jsfunc;

        $rtn = "<input type='button' name='btn_" . $btn . "' id='btn_" . $btn . "' class='" . $style . "' value='" . $btn_value . "' onclick=\"" . $onclickjs . "\">&nbsp;";

        return $rtn;
    } 

    /**
     * ---createToolbar---
     * create action
     * 
     * @param string $url ,$action='',$tourl='',$showvalue=''
     * @return string 
     */
    public static function createToolbar($url, $action = '', $tourl = '', $showvalue = '', $dojs = '') {
        global $lang;

        if ($showvalue != '') {
            $btn_value = $showvalue;
        } else if (array_key_exists($action, $lang)) {
            $btn_value = $lang[$action];
        } else {
            $btn_value = $action;
        } 

        $toolbar = '<input type="button" name="btn_' . $action . '" id="btn_' . $action . '" class="btn_' . $action . '" value="' . $btn_value . '" onclick="submitsSelect(\'' . $action . '\',\'' . $tourl . '\',\'' . $dojs . '\')">&nbsp;';
        if (self::checkSysAdmin()) {
            return $toolbar;
        } 
        require_once(EIFR_ROOT . 'admin/mod_adminmenu/acl_adminmenu.php');
        $acl_adminmenu = new CAclAdminmenu();
        if (array_key_exists($action, $acl_adminmenu -> getAccess()) && ! $acl_adminmenu -> checkActionAccess($action, $url)) {
            return '';
        } 

        return $toolbar;
    } 

    /**
     * ---createSplitLine---
     * create split line
     * 
     * @param string $showtype =''
     * @param int $height =18
     * @return string 
     */
    public static function createSplitLine($showtype = '', $height = 18) {
        $rtn = '<img src="' . SYS_ADMIN_STYLE_PATH . 'images/blank.gif" align="absmiddle" style="width:1px; height:' . $height . 'px; border:1px solid; border-color:	ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;">&nbsp;';
        return $rtn;
    } 

    /**
     * createAdminMenuNav
     * admin menu navigation
     * 
     * @param string $url ,$subtitle=''
     * @return string 
     */
    public static function createAdminMenuNav($url, $subtitle = '') {
        require_once(EIFR_ROOT . 'admin/mod_adminmenu/class_adminmenu.php');
        $clComAdminmenu = new ComAdminmenu();
        return $clComAdminmenu -> createAdminMenuNav($url, $subtitle);
    } 

    public static function adapterJS($str) {
        $str = str_replace("\r\n", "", $str);
        $str = str_replace("\n", "", $str);
        $str = addslashes($str);
        return $str;
    } 

    /**
     * ---returnWinOpener---
     * return open window form
     * 
     * @param string $editForm 
     * @param string $editInput 
     * @param string $resValue 
     */
    public static function returnWinOpener($editForm, $editInput, $resValue = '') {
        echo "<script type=\"text/javascript\">";
        echo "window.opener.document." . $editForm . "." . $editInput . ".value='" . $resValue . "';";
        echo "window.close();" ;
        echo "</script>" ;
        exit ;
    } 

    /**
     * ---showTxtAb---
     * show txt ab.
     * 
     * @param string $str 
     * @param int $strlen 
     */
    public static function showTxtAb($str = '', $slen = 10, $extype = '') {
        $j = 0;
        for($i = 0;$i < $slen;$i++) {
            if (ord(substr($str, $i, 1)) > 0xa0) $j++;
        } 
        if ($j % 2 != 0) {
            $slen++;
        } 
        $rstr = substr($str, 0, $slen);
        if (strlen($str) > $slen) {
            $rstr .= $extype;
        } 
        return $rstr;
    } 

    /**
     * ---showMsg---
     * alert message and turn url
     * 
     * @param string $msg 
     * @param string $page_to 
     */
    public static function showMsg($msg = '', $showtype = '', $page_to = '') {
        if ($msg) {
			echo '<meta http-equiv="Content-Type" content="text/html; charset=' . SYS_CHARSET . '" />';
            if ($showtype) {
                switch ($showtype) {
                    case 'success':
                        echo"<SCRIPT LANGUAGE='JavaScript'>window.top.curShowMsg=\"<font color='#0000FF'>" . $msg . "</font>\";</SCRIPT>";
                        break;
                    case 'fail':
                        echo"<SCRIPT LANGUAGE='JavaScript'>window.top.curShowMsg=\"<font color='#FF0000'>" . $msg . "</font>\";</SCRIPT>";
                        break;
                    default :
                        echo"<SCRIPT LANGUAGE='JavaScript'>alert('" . $lang['msgParamInvalid'] . "');</SCRIPT>";
                        break;
                } 
            } else {
                echo"<SCRIPT LANGUAGE='JavaScript'>alert('" . $msg . "');</SCRIPT>";
            } 
        } 

        if ($page_to == '-1') {
            echo"<SCRIPT LANGUAGE='JavaScript'>history.go(-1);</SCRIPT>";
        } else if ($page_to == 'top') {
            echo"<SCRIPT LANGUAGE='JavaScript'>top.location='index.php';</SCRIPT>";
        } else if ($page_to == 'reload') {
            echo"<SCRIPT LANGUAGE='JavaScript'>location.reload();</SCRIPT>";
        } else if ($page_to) {
            echo"<SCRIPT LANGUAGE='JavaScript'>location='$page_to';</SCRIPT>";
        }
    } 

    /**
     * ---showWinMsg---
     * show window message
     * 
     * @param string $msg 
     */
    public static function showWinMsg($msgtype = '', $msg = '', $goback = '', $add = '', $edit = '', $manage = '', $subject = '') {
        global $lang, $url;
        $nav = self::createAdminMenuNav($url);
        echo "
		<html>
		<head>
		<title>edit message</title>
		<meta http-equiv='Content-Type' content='text/html; charset=" . SYS_CHARSET . "' />
		<link href='" . SYS_ADMIN_STYLE_PATH . "style/common.css' rel='stylesheet' type='text/css'>
		<script src='" . SYS_ADMIN_STYLE_PATH . "js/common.js'></script>
		<base target='_self'/>
		</head>
		<script>
		printWinMsg(\"$msgtype\",\"$msg\",\"$nav\",\"$goback\",\"$add\",\"$edit\",\"$manage\",\"$subject\");
		</script>
		</html>
	";
        exit();
    } 

    /**
     * ---showWarningMsg---
     * show window message
     * 
     * @param string $msg 
     */
    public static function showWarningMsg($msg = '') {
        self::showWinMsg('warning', $msg, '-1');
    } 

    /**
     * ---showErrorMsg---
     * show window message
     * 
     * @param string $msg 
     */
    public static function showErrorMsg($msg = '') {
        self::showWinMsg('error', $msg, '-1');
    } 

    /**
     * ---showOkMsg---
     * show window message
     * 
     * @param string $msg 
     */
    public static function showOkMsg($msg = '', $add = '', $edit = '', $manage = '', $subject = '') {
        self::showWinMsg('ok', $msg, '', $add, $edit, $manage, $subject);
    } 

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

    public static function checkSubmit($value, $extrakey = '') {
        global $lang;
        $sessionkey = 'eifr_admin_has_submitted';
        if ($extrakey) {
            $sessionkey .= '_' . $extrakey;
        } 

        if (getSession($sessionkey) == $value) {
            self::showMsg($lang['has_submitted'] . ' ' . $value, '', '-1');
            exit();
        } else {
            setSession($sessionkey, $value);
        } 
    } 

    public static function stripTags($str, $allow = '') {
        return stripTags($str, $allow);
    } 
    
    public static function getImageByFileurl($fileurl='', $defurl='images/noneimg.gif', $index=0) {
        $fileurl_ary = explode('|',$fileurl);

        if (array_key_exists($index,$fileurl_ary)) {
            if($fileurl_ary[$index] != '') 
                return $fileurl_ary[$index];
        }
        
        if($fileurl_ary[0] != '')
            return $fileurl_ary[0];

        return $defurl;
    }

} 

?>
