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

require_once(EIFR_ROOT . 'libraries/template.php');

class ComUser {
    function setUserFieldRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?	
        global $selectid, $selectValue, $field_name, $field_value;

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

    function deleteRecords() {
        global $db, $lang, $url;
        Common::checkAdminExeAuth($url, 'delete'); //have delete authority ?
        global $selectValue;

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

    function addRecords() {
        global $lang, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?	
        $is_manage = Common::checkAdminAuth($url, 'manage');

        $username = kPost('username');
        if (!Common::checkUsername($username, 2, 20)) {
            Common::showMsg($lang['user_username_invalide'], '', '-1');
            exit();
        } 
        $username = filterUsername($username);
        Common::checkEditDataIsExist(TB_USER, TF_USER_NAME, $username);

        $parameter = '';
        $param_arr = array();
        if (kPost('style_id') != '') $param_arr['style_id'] = kPost('style_id');
        if (kPost('only_login') != '') $param_arr['only_login'] = kPost('only_login');
        if ($param_arr) $parameter = serialize($param_arr);

        $boss_uid = kPost('boss_uid');
        if (!$is_manage) {
            $boss_uid = getCookie(COOKIE_UID);
        } 

        $record_arr = array('username' => $username,
            'password' => md5(kPost('password')),
            'email' => kPost('email'),
            'nickname' => kPost('nickname'),
            'realname' => kPost('realname'),
            'tel' => kPost('tel'),
            'fax' => kPost('fax'),
            'mobile' => kPost('mobile'),
            'regtime' => time(),
            'regip' => getIP(),
            'fileurl' => kPost('fileurl'),
            'parameter' => $parameter,
            'boss_uid' => $boss_uid,
            TFR_USER_CLASS_ID => kPost('user_class_id'),
            TFR_CHANNEL_ID => kPost('channel_id')
            );

        $rtn = dbInsert(TB_USER, $record_arr);
        if ($rtn) {
            $uid = dbGetFieldValue(TB_USER, TF_USER_ID, "" . TF_USER_NAME . "='" . $username . "'");
            Common::showOkMsg($lang['saveSuccess'], 'user_edit.php', 'user_edit.php?act=edit&edittype=all&selectid=' . $uid, 'user.php');
        } else {
            Common::showErrorMsg($lang['addFail']);
        } 
        
    } 

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

        $edittype = kPost('edittype');
        if ($edittype == 'all') {
            $username = kPost('username');
            if (!Common::checkUsername($username, 2, 20)) {
                Common::showMsg($lang['user_username_invalide'], '', '-1');
                exit();
            } 
            $username = filterUsername($username);
            if (Common::checkAdminAuth($url, 'manage')) {
                Common::checkEditDataIsExist(TB_USER, TF_USER_NAME, $username, kPost('username_old'));
            } else {
                $username = kPost('username_old');
            } 

            Common::checkEditDataIsExist(TB_USER, 'email', kPost('email'), kPost('email_old'));

            $record_arr = array(
                TF_USER_NAME => $username,
                'email' => kPost('email'),
                'nickname' => kPost('nickname'),
                'realname' => kPost('realname'),
                'tel' => kPost('tel'),
                'fax' => kPost('fax'),
                'mobile' => kPost('mobile'),
                'fileurl' => kPost('fileurl'),
                TFR_ADDRESS_ID => kPost('address_id')
                );

        } else {
            $channel_id = addCommaHeadTail(kPost('channel_id'));
            if (kPost('channel_type') == '1') $channel_id = '-1';
            $layoutIds = '';
            if (kPost('layout_id') != '') $layoutIds = implode(',', kPost('layout_id'));
            $parameter = '';
            $param_arr = array();
            if (kPost('style_id') != '') $param_arr['style_id'] = kPost('style_id');
            if (kPost('only_login') != '') $param_arr['only_login'] = kPost('only_login');
            if ($param_arr) $parameter = serialize($param_arr);

            $record_arr = array(
                TFR_CHANNEL_ID => $channel_id,
                TFR_USER_CLASS_ID => kPost('user_class_id'),
                'layout_id' => $layoutIds,
                'parameter' => $parameter
                );
        } 

        if (kPost('password_new') != '') {
            $record_arr[TF_USER_PASS] = md5(kPost('password_new'));
        } 
        Log_d(__FILE__,__LINE__,'[editRecords] edittype:'.$edittype);
        if (dbUpdate(TB_USER, $record_arr, TF_USER_ID . "=" . $selectid)) {
            Common::showOkMsg($lang['saveSuccess'], 'user_edit.php', 'user_edit.php?act=edit&edittype=' . $edittype . '&selectid=' . $selectid, 'user.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    } 
    
    function editFieldDetail() {
        global $lang, $url;
        Common::checkAdminExeAuth($url, 'edit'); //have edit authority ?
        $selectid = kRequest('selectid');
        if (kPost('selectValue')) $selectid = kPost('selectValue');
        $field = kPost('field');
        
        $detail = dbGetFieldValue(TB_USER, 'detail', "uid =$selectid");
        $detail_arr = unserializeFixed($detail);
        if (! is_array($detail_arr)) {
            $detail_arr = array();
        }
        
        $detail = '';
        if ($field != '') $detail_arr[$field] = kPost('content');
        if ($detail_arr) $detail = serialize($detail_arr);
        $record_arr = array('detail' => $detail);

        if (dbUpdate(TB_USER, $record_arr, TF_USER_ID . "=" . $selectid)) {
            Common::showOkMsg($lang['saveSuccess'], 'user_edit.php', 'user_edit.php?act=edit_detail&field=' . $field . '&selectid=' . $selectid, 'user.php');
        } else {
            Common::showErrorMsg($lang['saveFail']);
        } 
    }

    public static function getUsersByBossUid($boss_uid) {
        $sql = "select uid, username, nickname, fileurl from " . TB_USER . " where boss_uid=$boss_uid";
        return dbGetRecordn($sql);
    }

    public static function getUidsBossUid($boss_uid) {
        $users = self::getUsersByBossUid($boss_uid);
        $uids = '';
        foreach($users as $row) {
            $uids .= ',' . $row['uid'];
        }
        if($uids != '') $uids = substr($uids, 1);
        return $uids;
    }

    function getUsersBySearch($querys = array(), $is_manage = false) {
        $query_arr = array();
        $query_sql = '1';
        if (!$is_manage) {
            $query_sql .= ' and flag<>4';
            $query_sql .= " and boss_uid='" . getCookie(COOKIE_UID) . "'";
        } 
        if ($querys['layout_id'] != '') $query_sql .= " and find_in_set(" . $querys['layout_id'] . ",layout_id) ";
        if ($querys['flag'] != '') $query_sql .= " and flag='" . $querys['flag'] . "' ";
        if ($querys['user_class_id'] != '') $query_sql .= " and user_class_id ='" . $querys['user_class_id'] . "' ";
        if ($querys['search_field'] != '' && $querys['search_keyword'] != '') {
            $query_sql .= " and " . $querys['search_field'] . " like '%" . $querys['search_keyword'] . "%'";
        } 

        $sql = "select uid,username,nickname,email,user_class_id,layout_id,fileurl,regtime,lasttime,flag from " . TB_USER . " where " . $query_sql . " order by uid desc";
        $query_string = 'act=' . $querys['act'] . '&user_class_id=' . $querys['user_class_id'] . '&flag=' . $querys['flag'] . '&layout_id=' . $querys['layout_id'] . '&search_field=' . $querys['search_field'] . '&search_keyword=' . $querys['search_keyword'] . '';

        return dbGetRecordPages($sql, $query_string);
    }
    
    function get_layout_user() {
        global $lang, $url;
        $querys = kRequests('act,search_keyword,search_field,user_class_id,flag,layout_id');
        $is_manage = Common::checkAdminAuth($url, 'manage');
        
        $toolbar = Common::createToolbar($url, 'add', 'user_edit.php');
        $toolbar .= Common::createToolbar($url, 'edit', 'user_edit.php?act=edit');
        $toolbar .= Common::createToolbar($url, 'delete', 'user.php?act=setvalue&field_name=flag&field_value=4');

        if ($is_manage) {
            $toolbar .= Common::createToolbar($url, 'delete_forever', 'user.php?act=delete_forever');
            $toolbar .= Common::createSplitLine();
            $toolbar .= Common::createToolbar($url, 'unchecked', 'user.php?act=setvalue&field_name=flag&field_value=0');
            $toolbar .= Common::createToolbar($url, 'open', 'user.php?act=setvalue&field_name=flag&field_value=1');
            $toolbar .= Common::createToolbar($url, 'locked', 'user.php?act=setvalue&field_name=flag&field_value=2');
            $toolbar .= Common::createToolbar($url, 'stop', 'user.php?act=setvalue&field_name=flag&field_value=3');
        } 
        
        $layout_title = $lang['layout_select'];
        if ($querys['layout_id'] != '') {
            require_once(EIFR_ROOT . 'admin/mod_template/class_template.php');
            $tpl = ComTemplate::getTemplateLayoutById($querys['layout_id']);
            $layout_title = $tpl['title'];
        }

        $rtnLayout = array(
            'eifr_pages' => $this -> getUsersBySearch($querys, $is_manage),
            'is_manage' => $is_manage,
            'menu_nav' => Common::createAdminMenuNav($url),
            'toolbar' => $toolbar,
            'search_field' => $querys['search_field'],
            'list_flag' => $this -> cTagFlagSelect($querys['flag']),
            'list_user_class' => $this -> cTagUserClassSelect($querys['user_class_id']),
            'layout_id' => $querys['layout_id'],
            'layout_title' => $layout_title,
        );

        return $rtnLayout;
    } 

    function get_layout_user_select() {
        global $lang, $url;
        $querys = kRequests('act,search_keyword,search_field,user_class_id,flag,layout_id');
        $is_manage = Common::checkAdminAuth($url, 'manage');

        $rtnLayout = array(
            'eifr_pages' => $this -> getUsersBySearch($querys, $is_manage),
            'is_manage' => $is_manage,
            'search_field' => $querys['search_field'],
            'list_flag' => $this -> cTagFlagSelect($querys['flag']),
            'list_user_class' => $this -> cTagUserClassSelect($querys['user_class_id']),
        );

        return $rtnLayout;
    } 

    function layout_user_edit_add() {
        global $db, $url;
        Common::checkAdminExeAuth($url, 'add'); //have add authority ?
        $is_manage = Common::checkAdminAuth($url, 'manage');
        $toolbar = Common::createToolbar($url, 'save', 'user_edit.php?act=save_add');
        $list_class_sql = '';
        if (!$is_manage) {
            $user_class_id = dbGetFieldValue(TB_USER, 'user_class_id', "uid='" . getCookie(COOKIE_UID) . "'");
            $list_class_sql = "id like '" . $user_class_id . "%' and id<>'" . $user_class_id . "'";
        } 
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array(
                'sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'sys_dir' => DIR_INSTALL,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'list_style' => Common::creatSelect(TB_STYLE, 'id', 'title'),
                'list_only_login' => $this -> creatOnlyLoginRadio(),
                'list_class' => Common::creatClassSelect(TB_USER_CLASS, TF_USER_CLASS_ID, '', $list_class_sql),
                'list_channel' => Common::creatClassSelect(TB_CHANNEL, TF_CHANNEL_ID),
                'toolbar' => $toolbar
                ));

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

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

        global $selectid, $selectValue;

        $toolbar = Common::createToolbar($url, 'save', 'user_edit.php?act=save_edit');
        $toolbar .= Common::createToolbar($url, 'delete', 'user.php?act=setvalue&field_name=flag&field_value=4');
        if ($is_manage) {
            $toolbar .= Common::createToolbar($url, 'delete_forever', 'user.php?act=delete_forever');
        } 
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'sys_dir' => DIR_INSTALL,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                ));

        if ($selectValue) $selectid = $selectValue;

        $sql = "select * from " . TB_USER . " where " . TF_USER_ID . "=" . $selectid . "";
        $rs = $db -> Execute($sql);
        if (!$rs -> EOF) {
            // data
            $channel_list = '';
            $channel_checked_1 = '';
            $channel_checked_2 = '';
            $channel_display = 'none';
            $display_layout = '';
            $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';
            $param_arr = unserializeFixed($rs -> fields['parameter']);
            $style_id = '';
            $only_login = '';
            if (is_array($param_arr)) {
                if (array_key_exists('style_id', $param_arr)) $style_id = $param_arr['style_id'];
                if (array_key_exists('only_login', $param_arr)) $only_login = $param_arr['only_login'];
            }

            $list_class_sql = '';
            if (!$is_manage) {
                $display_layout = 'display:none;';
                $boss_class_id = dbGetFieldValue(TB_USER, TFR_USER_CLASS_ID, "uid='" . $rs -> fields['boss_uid'] . "'");
                $list_class_sql = "id like '" . $boss_class_id . "%' and id<>'" . $boss_class_id . "'";
            } 
            $clTemplate -> assign_vars(array('selectid' => $selectid,
                    'username' => $rs -> fields[TF_USER_NAME],
                    'password' => '',
                    'list_style' => Common::creatSelect(TB_STYLE, 'id', 'title',  $style_id),
                    'list_only_login' => $this -> creatOnlyLoginRadio($only_login),
                    'list_class' => Common::creatClassSelect(TB_USER_CLASS, TF_USER_CLASS_ID, $rs -> fields[TFR_USER_CLASS_ID], $list_class_sql),
                    'channel_id' => $channel_id,
                    'layout_id' => $rs -> fields['layout_id'],
                    'layout_id_list' => Common::createLayoutSelect($rs -> fields['layout_id']),
                    'channel_checked_1' => $channel_checked_1,
                    'channel_checked_2' => $channel_checked_2,
                    'channel_display' => $channel_display,
                    'display_layout' => $display_layout
                    ));
        } 
        $rs -> Close();

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

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

        global $selectid, $selectValue;

        $toolbar = Common::createToolbar($url, 'save', 'user_edit.php?act=save_edit');
        $toolbar .= Common::createToolbar($url, 'delete', 'user.php?act=setvalue&field_name=flag&field_value=4');
        if ($is_manage) {
            $toolbar .= Common::createToolbar($url, 'delete_forever', 'user.php?act=delete_forever');
        } 
        $clTemplate = new Template(getAdminTemplateDir($url)); 
        // common
        $clTemplate -> assign_vars(array('sys_charset' => SYS_CHARSET,
                'style_id' => SYS_DEFAULT_STYLE,
                'adminStylePath' => SYS_ADMIN_STYLE_PATH,
                'sys_dir' => DIR_INSTALL,
                'menu_nav' => Common::createAdminMenuNav($url),
                'toolbar' => $toolbar
                ));

        if ($selectValue) $selectid = $selectValue;

        $sql = "select * from " . TB_USER . " where " . TF_USER_ID . "=" . $selectid . "";
        $rs = $db -> Execute($sql);
        if (!$rs -> EOF) {
            // data

            $clTemplate -> assign_vars(array('selectid' => $selectid,
                    'username' => $rs -> fields[TF_USER_NAME],
                    'username_old' => $rs -> fields[TF_USER_NAME],
                    'password' => '',
                    'list_address' => Common::creatClassSelect(TB_ADDRESS, TF_ADDRESS_ID, $rs -> fields[TFR_ADDRESS_ID]),
                    'email' => $rs -> fields['email'],
                    'email_old' => $rs -> fields['email'],
                    'nickname' => $rs -> fields['nickname'],
                    'realname' => $rs -> fields['realname'],
                    'fileurl' => $rs -> fields['fileurl'],
                    'show_img' => $rs -> fields['fileurl'] ? "<img src='" . CSafeData::getImgSrc($rs -> fields['fileurl']) . "' align='absmiddle'>" : '',
                    'tel' => $rs -> fields['tel'],
                    'fax' => $rs -> fields['fax'],
                    'mobile' => $rs -> fields['mobile']
                    ));
        } 
        $rs -> Close();

        $clTemplate -> set_filenames(array('body' => 'user_edit_all.tpl.html'));
        $clTemplate -> pparse("body");
    } 
    
    function get_layout_edit_detail() {
        global $url;
        Common::checkAdminExeAuth($url, 'edit');

        $field = kGet('field');
        $selectValue = kRequest('selectValue');
        $selectid = kRequest('selectid');
        if ($selectValue) $selectid = $selectValue;

        $rtnLayout = array();
        $content = '';
        $detail = dbGetFieldValue(TB_USER, 'detail', "uid =$selectid");
        $detail_arr = unserializeFixed($detail);
        if (is_array($detail_arr)) {
            if (array_key_exists($field, $detail_arr)) $content = $detail_arr[$field];
        }

        $rtnLayout = array(
            'eifrtf_selectid' => $selectid,
            'eifrtf_menu_nav' => Common::createAdminMenuNav($url),
            'eifrtf_toolbar' => Common::createToolbar($url, 'save', '?act=save_edit_detail'),
            'eifrtf_field' => $field,
            'eifrtf_content' => $content,
        );

        return $rtnLayout;
    } 
    
    function creatOnlyLoginRadio($status = 0) {
        global $lang;
        $rtn = '';
        $status_arr = array(0, 1);
        $status_txt_arr = array('no', 'yes');
        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='only_login' value='" . $status_arr[$i] . "' " . $e_s . ">" . $showvalue . "&nbsp;\n";
        } 
        return $rtn;
    } 
    
    function cTagFlagSelect($flag = '') {
        $selectAttrs = array('name'=>'flag', 'class'=>'input_select');
        return Common::cTagFlagSelect($selectAttrs, $flag);
    }
   
    function cTagUserClassSelect($user_class_id = '') {
        $selectAttrs = array('name'=>'user_class_id', 'class'=>'input_select');
        return Common::cTagUserClassSelect($selectAttrs, $user_class_id);
    }
    
} 

?>
