<?php
/*
* 安全考虑, 功能为用户操作项
* 程序及模板都依user_开始, 放至在default目录中.
* 编辑时间 星期一, 19 十二月 2012 Yuan(fenanr@hotmail.com)
*/
defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
# 定义公共颜色
$c1 = '#74ACDE';
$c2 = '#EBF5FC';
$c3 = '#303324';

# 定义左侧列表
$left_meun = temp_get_meun();

# 记录不需要登录的功能块.
$user_method = array('register_ajax', 'login', 'image', 'qqlogin', 'qqreg','syno','userout');

if(USER_UID && app_user(true) === false && $default_parem[2] !== 'userout'){
    fun_message('./index.php?user=userout.html',1);
}

if(in_array($default_parem[2],$user_method) === false && !USER_UID){
    fun_message('./index.php?user=login.html',1); 
}

$admin_css = fun_enhtml($default_parem[2]);
$include_file = 'user_index';
switch($default_parem[2]) {
    case 'index':
        // TODO: 用户中心默认首页.
        $include_str = '用户中心';
        $html['title'] .= ' - 用户中心';
        common_function_template('admincp_iframe');
        break;
    case 'newthread':
        // TODO: 用户中心投稿功能.
        if(IS_POST && empty($user_posts) === true){
            fun_message('<span style="color:red">投稿权限不足, 请返回</span>');
        }
        
        $edit = $intattcount =  $opens = 0;
        $open = 'none';
        
        # 当隐藏时, 删除配置文件.
        if(IS_POST && $default_post['stus'] == 0){
            unset($default_post['TFG']);
            $default_post['th_status'] = 0;
        }
        
        #基础变量
        empty($default_post['th_status']) === true?$thread_state = 0:$thread_state = $default_post['th_status']+0;
        $thread_history = 0;
        
         # 重组主题设置相关.      
        if(IS_POST && empty($default_post['TFG']) === false){
            if(empty($default_post['TFG']['th_replays']) === false){
                $default_post['TFG']['th_replay'] = strtotime($default_post['TFG']['th_replays']);
            }
            unset($default_post['TFG']['th_replays'],$default_post['th_status']);
            # 数据需要原始化.
            if(empty($default_post['TFG']) === false){
                $state = 0;
                foreach($default_post['TFG'] AS $val){
                    if(isset($val) === true)
                        $state = 1;
                }

                if($state === 1){
                    $default_post['TFG'] = fun_stripslashes($default_post['TFG']);
                    $thread_history = addslashes(serialize($default_post['TFG']));
                }
            }
        }
        
        if(IS_POST){
            if(empty($default_post['scat']) === true){
                fun_message('<span style="color:red">请选择主题所属栏目分类!!</span>');
            }
            
            if(empty($default_post['title']) === true && empty($default_post['message']) === true){
                fun_message('<span style="color:red">标题及信息不可为空!!</span>');
            }
            
            
            $thread_fid = $default_post['scat']+0;
            $thread_title = $default_post['title'];
            $default_post['thread_view'] += 0;
            
            # 信息的重组开始
            $default_post['message'] = strtr($default_post['message'],array('[code]'=>'[code=default]'));
            function base_code_highlight($mess,$code){$mess = base64_encode(fun_stripslashes(strtr($mess,array('\\\"'=>'"'))));return "[code=$code]{$mess}[/code]";}
            $default_post['message'] = preg_replace('/\[code=(.+)\](.*)\[\/code\]/iseU','base_code_highlight(\'$2\',\'$1\')',$default_post['message']);
            $default_post['message'] = strtr($default_post['message'],array('<?'=>'&lt;?','?>'=>'?&gt;'));
            $thread_message = strip_tags($default_post['message']);
            $thread_message = strtr($thread_message,array('&lt;?'=>'<?','?&gt;'=>'?>'));
            // 还原所有的html代码.
            function uncode_html($mess){$mess = base64_decode(strtr($mess,array('\"'=>'"')));return "[html]{$mess}[/html]";}
            $thread_message = preg_replace('/\[html\](.*)\[\/html\]/iseU','uncode_html(\'$1\')',$thread_message);
            #end

           #处理缩略图片及首页展示.
            $sele_id =array();
            if(empty($default_post['imgshow']) === false){
                $sele_id[] = $default_post['imgshow']+0;
            }else{
                $thread_index_img = 0;
            }
            if(empty($default_post['thum']) === false){
                 $sele_id[] = $default_post['thum']+0;
            }else{
                if(is_file($thread['thread_thum']) === true)
                    unlink($thread['thread_thum']);
                $thread_thum = 0;
            }

            $thread_thum = $thread_index_img = 0;
            if(empty($sele_id) === false){
                if(is_file($thread['thread_thum']) === true)
                    unlink($thread['thread_thum']);
                $sele_id = implode(',',$sele_id);
                $query = mysql::query("SELECT `aid`,`tid`,`atime`,`amname` FROM `DB_attachments` WHERE aid IN($sele_id)");
                include_once(DIR_FUNCTION.'function_images.php');
                while($row = mysql::fetch_array($query)){
                    $row['path'] = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
                    if($default_post['thum'] == $row['aid']){
                        $thread_thum = fun_imageresize($row['path'], 260, 200);
                    }
                    
                    if($default_post['imgshow'] == $row['aid']){
                       $thread_index_img = $row['path'];
                    }
                }
            }
            
            $thread_update = $thread_date = GET_TIME;
            $thread_ip = fun_get_ip();

                $thread_attch = 0;
            if(empty($default_post['attch']) === false || empty($attch_array) === false){
                $thread_attch = 1;
            }
            
            #如果edit为0, 就先值入主题, 然后再更改.
            if(empty($edit) === true){
                $sql = "INSERT INTO DB_thread(thread_uid,thread_fid, thread_first, thread_title, thread_message, thread_update, thread_date, thread_ip,thread_attch,thread_state,thread_history,thread_view) VALUES ($user_uid,'$thread_fid', '0', '0', '0', '0', '$thread_date', '$thread_ip','0','0','0','{$default_post['thread_view']}')";
                mysql::query($sql);
                $edit = mysql::insert_id();
            }
            
             $thread_admin = 0;
            if($default_post['TFG']['th_sync'] === '1'){
                $thread_admin = 2;
            }
            
            #对发表时间进行更新
            if(empty($default_post['thread_date']) === false){
                $default_post['thread_date'] = strtotime($default_post['thread_date']);
            }else{
                $default_post['thread_date'] = GET_TIME;
            }
            
            $sql = "UPDATE DB_thread SET thread_fid='$thread_fid',thread_admin='$thread_admin', thread_date='{$default_post[thread_date]}', thread_title='$thread_title',thread_attch='$thread_attch',thread_message='$thread_message',thread_update='$thread_update',thread_state='$thread_state', thread_history='$thread_history',thread_index_img='$thread_index_img',thread_thum='$thread_thum',thread_view='{$default_post['thread_view']}' WHERE thread_id='$edit'";
            
            mysql::query($sql);
            // 更新附件
            if (empty($default_post['attch']) === false){
                foreach($default_post['attch'] AS $key => $val){
                    $default_post['attch'][$key] += 0;
                }
				$attch = implode(',', $default_post['attch']);
				mysql::query("UPDATE `DB_attachments` SET tid='$edit',temp='1',fid='$thread_fid' WHERE aid IN ($attch)");
			}
            # 更新附件描述
            foreach($default_post['attchmess'] AS $key => $val){
                $key +=0;
                $val = trim($val);
                if(empty($val) === false)
                mysql::query("UPDATE DB_attachments SET atag = '$val' WHERE aid = '$key'"); 
            }
            
            mysql::query("UPDATE DB_user SET user_exp = (user_exp+$mainpost_exp) WHERE user_id = '$user_uid'"); // $main_exp增加积分
            
            cache::dele('default_list.php');
            fun_message(fun_parse_url("./index.php?main=read&$edit.html"),1);
        }
        
        if(empty($cat_array) === true){
           fun_message('站点暂时没有栏目信息, 无法投稿主题!!!');
        }
        
        $include_str = '我要投稿';
        $include_file = 'user_'.$default_parem[2];
        $html['title'] .= ' - '.$include_str;
        common_function_template('admincp_iframe');
        break;
    case 'enlist':
        // TODO: 用户中心我的文章列表功能.
        $num = 50;
        $ts = $default_get['ts']+0;
        $page = max(1, $page);
        
        # 条件相关
        $where = '';
        if(!USER_ADMIN){
            $where .= ' AND T.thread_uid='.USER_UID;
        }
        if(empty($default_get['search']) === false){
            $search = $default_get['search'];
            $search = trim($search,'_');
            $search = trim($search,'%');
            $search = trim($search,'&');
            $search = trim($search,'*');
            empty($search) === true && $search = '00000000';
            $where .= " AND T.thread_title LIKE '%{$search}%'";
        }else{
            $search = 0;
        }
        if(empty($ts) === true){
            $where .= " AND T.thread_first='0'";
        }else{
            $where .= " AND T.thread_first != '0'";
        }
        $re = ($page - 1) * $num;
        $query = mysql::query("SELECT T.*,U.user_name,C.c_name FROM `DB_thread` AS T LEFT JOIN `DB_user` AS U ON U.user_id = T.thread_uid LEFT JOIN `DB_cat` AS C ON C.c_id=T.thread_fid WHERE 1 {$where} ORDER BY `thread_id` DESC LIMIT $re, $num");
        $thread_array = array();
        while($row = mysql::fetch_array($query)){
            if($row['thread_state'])
                $row['thread_state'] = $ico_array[$row['thread_state']];
            
            if(empty($ts) === false){
                $row['thread_title'] = $row['thread_message'];
                $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_first']}.html");
            }else{
                $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");  
            }
            
            $row['thread_attch'] = $row['thread_attch']?'<span style="color:green">√</span>':'<span style="color:red">×</span>';
            $row['thread_date'] = fun_date($row['thread_date']);
            $row['fidlink'] = fun_parse_url("./index.php?main=cat&{$row['thread_fid']}.html");
            
            # 主题高亮.
            $row['css'] = '';
            if(empty($row['thread_history']) === false){
              $threads = unserialize($row['thread_history']);
              if(empty($threads['th_color']) === false)
                $threads['th_color'] = fun_enhtml($threads['th_color']);
                $row['css'] = "color: {$threads['th_color']};";
              if(empty($threads['th_weight']) === false){
                $row['css'] .= "font-weight: bolder;";
              }
            }
            unset($row['thread_message'],$row['thread_history']);
            $thread_array[] = $row;
        }
        
        # 分页
        $count = mysql::get_one("SELECT count(1) AS counts FROM `DB_thread` AS T WHERE 1 {$where}");
        $page_list = fun_multi($count['counts'],$num,$page,"./index.php?user=enlist&ts={$ts}&search={$search}&page={#1}.html");
        $include_str = '我的帖子';
        $include_file = 'user_'.$default_parem[2];
        $html['title'] .= ' - '.$include_str;
        common_function_template('admincp_iframe');
        break;
   case 'dele':
        // TODO: 用户中心回复删除功能, 二个小时.
        $dele = $default_parem[3] + 0;
        if(empty($user_deles) === true){
            fun_message('<span style="color:red">信息删除权限不足, 请联系管理员</span>');
        }
        $get_one = mysql::get_one("SELECT `thread_update` FROM DB_thread WHERE thread_id='$dele' OR thread_first='$dele'");
        
        if(empty($get_one['thread_update']) === false && $get_one['thread_update']+ 7200 > GET_TIME){
            app_thdele($dele);
            fun_message('信息删除操作已经完成, 现在返回');
        }else{
            fun_message('<span style="color:red">权限下仅许可删除二个小时内信息.删除操作无法完成, 请联系管理员</span>');
        }
        break;
   case 'useredit':
        // TODO: 用户信息编辑功能.
        $user_id = USER_UID;
        if($default_get['up']){
            if(USER_ADMIN === 2){
                exit("{success:'受限用户禁止更新头像'}");
            }
           $input = fopen("php://input", "r");
            $temp = tmpfile();
            $realSize = stream_copy_to_stream($input, $temp);
            fclose($input);
            $maxsize = 204800;
            $allowedExtensions = array('jpeg', 'jpg', 'gif', 'png');
            if($realSize !== $_SERVER["CONTENT_LENGTH"]+0)
                exit("{success:'文件容量异常'}");
            
            $logo_path = "./Data/user_logo/{$user_id}.jpg";
            $target = fopen($logo_path, "w+");        
            fseek($temp, 0, SEEK_SET);
            stream_copy_to_stream($temp, $target);
            fclose($target);
            $rand = rand(1,999);
            # 缩略图 120 120
            include_once(DIR_FUNCTION.'function_images.php');
            fun_imageresize($logo_path, 120, 120,$logo_path);
            echo "{success:true,path:'$logo_path?r={$rand}'}";
            
            if(is_file($logo_path) === true)
                mysql::query("UPDATE DB_user SET user_logo='1' WHERE user_id ='$user_id'");
            
            exit();
        }

        $user_one = mysql::get_one("SELECT * FROM `DB_user` WHERE user_id ='$user_id'");
        if(empty($user_one) === true){
            fun_message('错误的用户id');
        }
        $default_post['user_admin'] = 0;
        if($user_one['user_id'] == 1){
            $default_post['user_admin'] = $user_one['user_admin']; // 直接沿用管理组.
        }
        
        $user_email = fun_enhtml($user_email);
        $user_logo = fun_getlogo($user_one['user_id'],$user_one['user_logo']);
        
        # QQ用户可以更改用户名.
        $qqedit = 0;
        if(USER_QQ && USER_EXP === 2 && ($user_one['user_regtime'] + 172800) >= GET_TIME){
            $qqedit = 1;
        }
        
        if(IS_POST){
            $upload_id = 0;
            if(empty($_FILES) === false){
                $upload = $_FILES['user_logo'];
                $logo_path = "./Data/user_logo/{$user_id}.jpg";
                if(strpos($upload['type'],'image/') !== false && $upload['error'] == 0 && $upload['size'] < 100000){
                    move_uploaded_file($upload['tmp_name'],$logo_path);
                    $upload_id = 1;
                    # 打击非法上传
                    $temp_array = getimagesize($logo_path);
                    if(empty($temp_array) === true){
                        unlink($logo_path);
                        $upload_id = 0;
                    }else{
                        include_once(DIR_FUNCTION.'function_images.php');
                        fun_imageresize($logo_path,120,120,$logo_path);
                    }
                }
            }

            # 组合更新用户的项目
            $update = "user_email='{$default_post['user_email']}'";
            if(empty($default_post['user_pass']) === false){
                $pass = md5(md5($default_post['user_pass']));
                $update .=",user_pass='$pass'";
            }
            
            if($qqedit && $user_one['user_name'] !== $default_post['user_name']){
                $default_post['user_name'] = fun_enhtml($default_post['user_name']);
                $default_post['user_name'] = fun_cutstr($default_post['user_name'],26);
                $default_post['user_name'] = strtr($default_post['user_name'],array('　'=>''));
                empty($default_post['user_name']) === true && $default_post['user_name'] = 'User';
                $update .=",user_name='{$default_post['user_name']}'";
            }
            
            $times = GET_TIME;
            
            # 过滤投稿申请信息.
            if($user_posts === 0 && $default_post['upost'] && $user_one['user_posts'] == 0){
                $update .=",user_posts='1',user_app='$times'";
                fun_log(USER_NAME."提交了投稿申请, 请审核 \n");
            }
            
            if(empty($default_post['upost']) === true){
                $update .=",user_posts='0',user_app='0'";
            }
            
            
            if(empty($default_post['user_pass']) === false){
                if(strlen($default_post['user_pass']) < 4){
                    $default_post['user_pass'] = $user_one['user_pass']; // 直接沿用旧用户.
                }else{
                    $default_post['user_pass'] = md5(md5($default_post['user_pass']));
                }
                $update .= ",user_pass ='{$default_post['user_pass']}'";
            }
            if(USER_EXP === 0)
                $update .=",useropenid='{$default_post['useropenid']}'";
            
            mysql::query("UPDATE DB_user SET user_admin='{$default_post['user_admin']}', {$update} WHERE user_id ='$user_id'");         
            fun_message('更新用户信息成功');
        }
        $include_str = '个人信息';
        $include_file = 'user_useredit';
        $html['title'] .= ' - '.$include_str;
        common_function_template('admincp_iframe');
        break;
    case 'syno':
        // TODO: 用户中心同步功能.
        $reurl = $_SESSION['reurl'];
        $qqinfo = $_SESSION['qqinfo'];
        if($qqinfo){
            $tem = unserialize(base64_decode($qqinfo));
            $openid = $tem['0'];
            if(USER_QQ === $openid){
                $openid = USER_QQ;
                $nickname = USER_NAME;
            }else{
                $nickname = $tem['1'];
            }
        }else{
            $openid = USER_QQ;
            $nickname = USER_NAME;
        }
        
        # QQ登录后注入用户信息.
        if($default_get['synos'] && !USER_UID && $openid && !$user_exp){
            $passmd5 = md5(md5($qqinfo));
			$times = GET_TIME;
            empty($nickname) === true && $nickname = 'Qempty';
            mysql::query("INSERT INTO `DB_user`(`user_id`, `user_name`, `user_pass`, `user_email`, `user_logo`, `user_admin`, `user_regtime`, `user_posts`, `user_edits`, `user_deles`, `user_app`, `useropenid`, `user_exp`,`user_logtime`) VALUES (NULL, '{$nickname}', '{$passmd5}', '0', '0', '0', '{$times}', '0', '0', '0', '0', '$openid', '2','$times')");
            $usid = mysql::insert_id();
            
            $codata = array('user_id'=>$usid,'user_name'=>$nickname,'user_pass'=>$passmd5);
            fun_setcookie('http_user', fun_authcode(fun_http_build_query($codata)),COOKIETIME);
            unset($_SESSION['qqinfo']);
            fun_message("欢迎QQ用户: $nickname 加入站点,现在返回",$_SESSION['reurl']);
        }
        
        if($default_post['not'] && USER_UID && !$user_exp){
            mysql::get_one("UPDATE `DB_user` SET useropenid ='0' WHERE user_id ='{$user_uid}'");
            fun_message('QQ账号绑定解除成功,欢迎再次绑定QQ账号');
            unset($_SESSION['qqinfo']);
        }
        
        if( (IS_POST === true || $default_get['synos']) && USER_UID && $openid){
            mysql::get_one("UPDATE `DB_user` SET useropenid ='{$openid}' WHERE user_id ='{$user_uid}'");
            fun_message('QQ账号绑定成功,登录QQ将享受更便捷服务');
            unset($_SESSION['qqinfo']);
        }
        
        $include_str = 'QQ互联';
        $include_file = 'user_syno';
        if($openid)
        $openid = substr_replace($openid,'******',8,14);
        $html['title'] .= ' - '.$include_str;
        common_function_template('admincp_iframe');
        break;
    case 'register_ajax':
             // TODO: 检测用户ajax, 无界面.
            $err = array();
            $default_get['username'] = strip_tags($default_get['username']);
            $default_get['useremal'] = strip_tags($default_get['useremal']); 
            $check = strtr($_SESSION['image_check'],array(' '=>''));
            if(strtoupper($default_get['check']) !== $check || empty($check) === true){
                $err['check'] = 1;
            }
            $one = mysql::get_one("SELECT `user_name`,`user_email` FROM DB_user WHERE user_name ='{$default_get['username']}' OR user_email ='{$default_get['useremal']}' LIMIT 1");
            if(empty($default_get['username']) === true || $one['user_name'] === $default_get['username']){
               $err['name'] = 2;
            }
            if($one['user_email'] === $default_get['useremal'] || fun_isemail($default_get['useremal']) === false){
                $err['email'] = 3;
            }
            if(empty($err) === true)
                $err['ok'] = 0;
            echo json::encode($err);
        break;
    case 'login':
        // TODO: 用户登录,注册功能集合.
        unset($_SESSION['reurl']);
        $_SESSION['reurl'] = fun_referer();
        if(strpos($_SESSION['reurl'],'user=login') !== false || strpos($_SESSION['reurl'],'user=userout') !== false){
            $_SESSION['reurl'] = './index.php';
        }
        $reurl = $_SESSION['reurl'];
        if(USER_UID){
            fun_message($_SESSION['reurl'],1);
        }
        
        # 通过第三参数确认是否注册
        empty($default_parem[3]) === true && $default_parem[3] = 'login';
        
        if(IS_POST && $default_parem[3] === 'register'){
             # 控制禁止用户在某些时间使用功能
            if(empty($cfg_login_redate) === false){
                if(in_array(date('H'),$cfg_login_redate) === true){
                    $tem = array();
                    $tem[0] = str_pad($cfg_login_redate[0],2,'0',STR_PAD_LEFT);
                    $tem[1] = str_pad(end($cfg_login_redate),2,'0',STR_PAD_LEFT);
                    fun_message("系统禁止此 {$tem[0]} 至 {$tem[1]} 时间内注册系统!");
                }
            }
            fun_setcookie('http_user',null,0);
            $default_post['username'] = strip_tags($default_post['username']);
            $default_post['userpass'] = md5(md5($default_post['userpass']));
            $default_post['useremal'] = strip_tags($default_post['useremal']);
            $ret = temp_register_user($default_post);
            $check = strtr($_SESSION['image_check'],array(' '=>''));
            if(strtoupper($default_post['check']) !== $check){
                fun_message('验证码错误');
            }
            
            if(strlen($default_post['username']) > 32 || strlen($default_post['useremal']) > 128){
                fun_message('用户名及邮件太长,请返回修改!!!');
            }
            
            if($ret === 1) {
                fun_message('用户名,密码,邮件为必填项');
            } else if($ret === 2) {
                fun_message('此用户已经存在');
            } elseif($ret === 3) {
                fun_message('此邮件已经注册过');
            } else {
                // 插入新会员
                $user_regtime = GET_TIME;
                mysql::query("INSERT INTO DB_user( user_name, user_pass, user_email, user_regtime,user_logtime) VALUES ('{$default_post['username']}', '{$default_post['userpass']}', '{$default_post[useremal]}', '$user_regtime','$user_regtime')");
                $uid = mysql::insert_id();            
                if( $uid == 1){
                    mysql::query("UPDATE DB_user SET user_admin='1' WHERE user_id = '1'");
                }
                if($uid){
                     cache::dele('index_user_list.php');
                     $codata = array('user_id'=>$uid,'user_name'=>$default_post['username'],'user_pass'=>$default_post['userpass']);
                     fun_setcookie('http_user', fun_authcode(fun_http_build_query($codata)),COOKIETIME);
                     fun_header($default_post['reurl']);
                }else{
                    fun_message('无法注册新会员, 请联系管理员!');
                }
                exit();
            }
        }
        
        if(IS_POST && $default_parem[3] === 'login') {
            $user_logtime = GET_TIME;
            fun_setcookie('http_user',null,0);
            $default_post['username'] = strip_tags($default_post['username']);
            $default_post['userpass'] = md5(md5($default_post['userpass']));
            $user_data = mysql::get_one("SELECT user_id,useropenid,user_admin FROM DB_user WHERE user_name='{$default_post['username']}' AND user_pass = '{$default_post['userpass']}'");
            // 数据转化成对应的值.
            if(empty($user_data) === false && empty($user_data['user_id']) === false) {
                # 控制禁止用户在某些时间使用功能
                if($user_data['user_admin'] !== '1' && empty($cfg_login_redate) === false && in_array($default_parem[2], array('login', 'qqlogin', 'qqreg')) === true ){
                    if(in_array(date('H'),$cfg_login_redate) === true){
                        $tem = array();
                        $tem[0] = str_pad($cfg_login_redate[0],2,'0',STR_PAD_LEFT);
                        $tem[1] = str_pad(end($cfg_login_redate),2,'0',STR_PAD_LEFT);
                        fun_message("系统禁止在 {$tem[0]} 至 {$tem[1]} 时间内登录系统!");
                    }
                }
                $temid = $user_data['user_id'] + 0;
                mysql::query("UPDATE DB_user SET user_logtime = '$user_logtime' WHERE user_id = '$temid'");
                $codata = array('user_id'=>$user_data['user_id'],'user_name'=>$default_post['username'],'user_pass'=>$default_post['userpass']);
                fun_setcookie('http_user', fun_authcode(fun_http_build_query($codata)),COOKIETIME);
                fun_header($default_post['reurl']);
            }else{
                fun_message('登录失败,请检查你的用户名及密码');
            }
        }
        // 查询出来, 显示最近注册用户
        $query = mysql::query("SELECT `user_id`,`user_name`,`user_regtime` FROM DB_user ORDER BY `user_id` DESC LIMIT 10");
        $user_list = array();
        while(($row = mysql::fetch_array($query)) !== false) {
            $row['user_regtime'] = fun_date($row['user_regtime']);
            $user_list[] = $row;
        }
        
        common_function_template('user_login');
        break;
    case 'userout':
            // TODO: 用户退出功能.
            if(empty($_SESSION['qqinfo']) === false)
                unset($_SESSION['qqinfo'],$_SESSION['reurl'],$_SESSION['state']);
            fun_setcookie('http_user',null,0);
            fun_message('用户登出成功');
        break;
	case 'image':
        // TODO: 验证码图片功能.
		$_SESSION['image_check'] = '';
		$im = imagecreate(60, 20); //制定图片背景大小
		$red = imageColorallocate($im, 255, 0, 0); //设定三种颜色
		$white = imageColorallocate($im, 255, 255, 255);
		$gray = imageColorallocate($im, 200, 200, 200);
		imagefill($im, 0, 0, $white); //ed
		$list = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
		shuffle($list);
        
		for($i = 0; $i < 4; $i ++){
			$authnum .= strtoupper($list[$i]); //
		}

		$_SESSION['image_check'] = $authnum;
		imagestring($im, 5, 10, 2, $authnum, $red);

		for($i = 0; $i < 400; $i ++){
			imagesetpixel($im, rand() % 90, rand() % 30, $gray);
		}
		header("Content-type: image/png");
		imagepng($im);
		imagedestroy($im);
		break;     
    case 'qqlogin':
        // TODO: QQ登录功能.跳转QQ
        if(empty($qq_config['open']) === true){
            fun_message('QQ在线登录功能未开放');
        }
        
        unset($_SESSION['reurl']);
        $_SESSION['reurl'] = fun_referer();
        // 得到返回值, 但有些需要过滤.
        if(strpos($_SESSION['reurl'],'user=login') !== false || strpos($_SESSION['reurl'],'user=qqlogin') !== false || strpos($_SESSION['reurl'],'user=userout') !== false){
            $_SESSION['reurl'] = './index.php';
        }
        unset($_SESSION['state'],$_SESSION['openid'],$_SESSION['state']);
        $appid = trim($qq_config['oauth_consumer_key']);
        $scope = urlencode('get_user_info,add_share');
        $callback = urlencode($qq_config['oauth_callback']); // http://www.fenanr.com/index.php?user=qqreg
        $_SESSION['state'] = md5(uniqid(GET_TIME, true)); //CSRF protection
        $login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={$appid}&redirect_uri={$callback}&state={$_SESSION['state']}&scope={$scope}";
        fun_header($login_url);
        break;
    case 'qqreg':
        // TODO: QQ登录:回调url.实现登录注册.
        $reurl = $_SESSION['reurl'];
        unset($_SESSION['qqinfo'],$_SESSION['reurl']);
        $login_url = './index.php?user=login.html';
        
        if(empty($qq_config['open']) === true){
            fun_message('QQ在线登录功能未开放',$login_url);
        }
        if(empty($_REQUEST['code']) === true){
            fun_message('QQ登录功能测试',$login_url);
        }
        function QQ_url_contents($url){
           if (function_exists('curl_init') === false)
                return file_get_contents($url);
                
            $ch = curl_init();
            if(stripos($url,"https://") !== false){
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            }
            curl_setopt($ch, CURLOPT_URL, $url );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
            $result =  curl_exec($ch);
            curl_close($ch);
            return $result;
        }
        $appid = trim($qq_config['oauth_consumer_key']);
        $appkey = trim($qq_config['oauth_consumer_secret']);
        $callback = urlencode($qq_config['oauth_callback']);
        
        #判断是否刚才的state值,
        if($_REQUEST['state'] === $_SESSION['state']){
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={$appid}&redirect_uri={$callback}&client_secret={$appkey}&code={$_REQUEST['code']}";

            $response = QQ_url_contents($token_url);
            if (strpos($response, "callback") !== false){
                fun_message('QQ在线登录失败,请联系技术员',$login_url);
            }
            $params = array();
            parse_str($response, $params);
            
            $access_token = $params["access_token"];
            
            #取得用户openid.
            $graph_url = "https://graph.qq.com/oauth2.0/me?access_token={$access_token}";
            $response  = QQ_url_contents($graph_url);
            if (strpos($response, "callback") !== false){
                    $lpos = strpos($response, "(");
                    $rpos = strrpos($response, ")");
                    $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
                    $userinfo = json::decode($response,true);
            }
            
            if (isset($userinfo['error'])){
                fun_message('QQ在线登录失败,请联系技术员',$login_url);
            }
            
            $openid = $userinfo['openid'];
            unset($userinfo,$response,$params);
            $get_user_info = "https://graph.qq.com/user/get_user_info?access_token={$access_token}&oauth_consumer_key={$appid}&openid={$openid}&format=json";
            $info = QQ_url_contents($get_user_info);
            $userinfo = json::decode($info, true);
            
            if(empty($userinfo) === true)
                fun_message('QQ在线登录失败,请联系技术员',$login_url);
            
            $_SESSION['qqinfo'] = base64_encode(serialize(array('0'=>$openid,
            '1'=>fun_enhtml($userinfo['nickname']),
            '2'=>urlencode($userinfo['figureurl_2']),
            '3'=>fun_enhtml($userinfo['gender']),
            '4'=>$userinfo['']
            )));
            cache::dele('index_user_list.php');
            # 处理登录关连.
            $user_data = mysql::get_one("SELECT user_id, user_name,user_pass,user_admin FROM `DB_user` WHERE useropenid ='{$openid}'");
            if(empty($user_data) === false && empty($user_data['user_id']) === false){
                 # 控制禁止用户在某些时间使用功能
                if($user_data['user_admin'] !== '1' && empty($cfg_login_redate) === false && in_array($default_parem[2], array('login', 'qqlogin', 'qqreg')) === true ){
                    if(in_array(date('H'),$cfg_login_redate) === true){
                        $tem = array();
                        $tem[0] = str_pad($cfg_login_redate[0],2,'0',STR_PAD_LEFT);
                        $tem[1] = str_pad(end($cfg_login_redate),2,'0',STR_PAD_LEFT);
                        fun_message("系统禁止在 {$tem[0]} 至 {$tem[1]} 时间内登录系统!");
                    }
                }
                $user_logtime = GET_TIME;
                $temid = $user_data['user_id'] + 0;
                mysql::query("UPDATE DB_user SET user_logtime = '$user_logtime' WHERE user_id = '$temid'");
                
                $codata = array('user_id'=>$user_data['user_id'],'user_name'=>$user_data['user_name'],'user_pass'=>$user_data['user_pass']);
                fun_setcookie('http_user', fun_authcode(fun_http_build_query($codata)),COOKIETIME);
                fun_message(" 欢迎QQ用户:{$user_data['user_name']} 登录站点,现正返回链接", $reurl);
            }else{
                if($userinfo['nickname'] === 'qzuser'){
                    fun_message('<span style="color:red">非授权QQ用户,系统暂时无法处理登录工作,请授权后访问!!!!</span>',$login_url);
                }
                if($qq_config['qq_content']){
                    header('location: ./index.php?user=syno&synos=1.html');
                }else{
                    header('location: ./index.php?user=syno.html');
                }
            }
            exit();
        }
        
        fun_message('QQ在线登录失败,请联系技术员',$login_url);
        break;
    case 'resume':
        // TODO: 用户简历编辑功能.
        if(USER_ADMIN === 2)
            fun_message('受限用户禁止使用此功能');
        define('RE_TIP', '#_#');
        $data = mysql::get_one("SELECT * FROM DB_resume WHERE user_id = '$user_uid'");
        $user_update = GET_TIME;
        $isuser = 1;
        if(!$data){
            $isuser = 0;
           $data = get_resume();
           $user_randmd5 = strtoupper(md5(GET_TIME));
           $ips = fun_get_ip();
           mysql::query("INSERT INTO DB_resume (user_id,user_randmd5,user_update,user_ip,user_cretime) VALUES ($user_uid,'$user_randmd5',$user_update,'$ips',$user_update)");
        }else{
            $user_randmd5 = $data['user_randmd5'];
        }
        
        foreach($data AS $key => $val){
            if(empty($val) === true)
                $data[$key] = get_resume($key);
            
            if(strpos($data[$key], RE_TIP) !== false){
                 $data[$key] = explode(RE_TIP, $data[$key]);
            }
        }
        
        if($default_get['ajaxin']){
            # 个人权限设置独立设置
            if($default_get['power']){
                $userpower = fun_enhtml($default_get['userpower']);
                $newurl = $default_get['newurl']+0;
                $user_randmd5 = $data['user_randmd5'];
                if($newurl){
                    $mdrrand = array(USER_NAME, GET_TIME, $userpower, GET_URL,$data['user_randmd5']);
                    shuffle($mdrrand);
                    $mdrrand = implode(rand(1,255), $mdrrand);
                    $user_randmd5 = strtoupper(md5($mdrrand));
                }
                if(is_numeric($userpower) === true && strlen($userpower) === 1){
                    $userpower += 0;
                }else{
                    $userpower = md5($userpower);
                }
                
                mysql::query("UPDATE DB_resume SET user_randmd5 = '$user_randmd5', user_power = '$userpower' WHERE user_id = '$user_uid'");
                
                echo $user_randmd5;
                exit();
            }
            
            # 返回ajax数据.
            $type = htmlspecialchars($default_get['type'],ENT_NOQUOTES);
            if(strpos($type, 'user_Skills') !== false || strpos($type, 'user_introduce') !== false){
                $default_get['mess'] = strtr($default_get['mess'], array('<br'=>'[br]<br'));
                $mess = strip_tags($default_get['mess']);
                $mess = strtr($mess , array('[br]'=>'<br />'));
            }else{
                $mess = strip_tags($default_get['mess']);
            }
            $smess = $mess;
            # 进某一段进行更新的.
            if(strpos($type, 'user_Education') !== false || strpos($type, 'user_workexper') !== false || strpos($type, 'user_Training') !== false){
                $tem = explode('-',$type);
                $type = $tem[0];
                $i = $tem[1];
            
                $tem = $data[$type];
                if(is_array($tem) === false)
                    $tem = array();
                
                $tem[$i] = $mess;
                $mess = implode(RE_TIP, $tem);
            }
            $s = mysql::get_one("SELECT char_length('$mess') AS lens");
            if($s['lens'] > 255)
                exit('-1');
            mysql::query("UPDATE DB_resume SET $type = '$mess',user_update='$user_update' WHERE user_id = '$user_uid'");
            echo $smess;
            exit();
        }
        
        
        #一些变量判断
        $user_power_text = '';
        if(is_numeric($data['user_power'])){
             $user_power = $data['user_power']+0;
        }else{
            $user_power = 0;
            $user_power_text =  $data['user_power'];
        }
        $data['user_lookcount'] += 0;
        $data['user_update'] = date('Y-m-d', $data['user_update']);
        $user_link = fun_parse_url("./plugin.php?user=resume&sid={$user_randmd5}.html");
        if(!$data['user_history'])
            $data['user_history'] = '暂时无查阅用户';
        # 取得头像.
        $t = max(1, intval(USER_UID / 3000));
        $t = str_pad($t,6,'0',STR_PAD_LEFT);
        if(is_dir("./Data/user_logo/$t/") === false)
            mkdir("./Data/user_logo/$t/");

        $md5 = md5(USER_UID);
        $path = "./Data/user_logo/$t/".$md5.'.gif';
        
        $userlogo = './Data/user_logo/logo.jpg';
        if(is_file($path) === true)
            $userlogo = $path;
            
        if($data['user_history']){
            $user_history_array = unserialize($data['user_history']);
        }
        $include_str = '我的简历';
        $include_file = 'user_resume';
        $html['title'] .= ' - '.$include_str;
        common_function_template('admincp_iframe');
        break;
    case 'resume_upload':
        // TODO: 简历头像上传支持,无界面
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $i    = 1;
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        $maxsize = 204800;
        $allowedExtensions = array('jpeg', 'jpg', 'gif', 'png');
        if($realSize !== $_SERVER["CONTENT_LENGTH"]+0)
            return false;
        
        $t = max(1, intval(USER_UID / 3000));
        $t = str_pad($t,6,'0',STR_PAD_LEFT);
        if(is_dir("./Data/user_logo/$t/") === false){
            if(mkdir("./Data/user_logo/$t/")){
                $i = 0;
            }
        }
        
        $md5 = md5(USER_UID);
        $path = "./Data/user_logo/$t/".$md5.'.gif';
        
        if($i){
            $target = fopen($path, "w+");  
            fseek($temp, 0, SEEK_SET);
            stream_copy_to_stream($temp, $target);
            fclose($target);
            $rand = rand(1,999);
            # 缩略图 150 132
            include_once(DIR_FUNCTION.'function_images.php');
            fun_imageresize($path, 150, 162,$path);
            echo "{success:true,path:'$path?r={$rand}'}";
        }else{
            echo "{success:false,path:'0'}";
        }
        exit();
        break;
    default:
        // TODO: 默认跳转到首页.
        fun_header();
        break;
}

// TODO: 函数开始
function temp_get_meun(){
   $temp = array();
   $temp['信息管理'][] = array('name'=>'我要投稿','link'=>'./index.php?user=newthread.html','cls'=>'newthread');
   $temp['信息管理'][] = array('name'=>'我的帖子','link'=>'./index.php?user=enlist.html','cls'=>'enlist');
   
   $temp['用户操作'][] = array('name'=>'我的信息','link'=>'./index.php?user=useredit.html','cls'=>'useredit');
   //$temp['用户操作'][] = array('name'=>'我的简历','link'=>'./index.php?user=resume.html','cls'=>'resume');
   $temp['用户操作'][] = array('name'=>'邦定中心','link'=>'./index.php?user=syno.html','cls'=>'syno');
   $temp['用户操作'][] = array('name'=>'退出系统','link'=>'./index.php?user=userout.html','cls'=>'0'); // 
   return $temp;
}

function temp_register_user($array) {
    /* 检查用户注册信息, 返回int */
    $error = 0;
    if(empty($array['username']) === true || empty($array['userpass']) === true || empty($array['useremal']) === true || fun_isemail($array['useremal']) === false)
        return 1;

    $one_data = mysql::get_one("SELECT user_name,user_email FROM DB_user WHERE user_name='{$array['username']}' OR user_email = '{$array['useremal']}'");
    
    if(empty($one_data) == false)
        $error = 1;
    if($one_data['user_name'] == $array['username']) {
        $error = 2;
    } elseif($one_data['user_email'] == $array['useremal']) {
        $error = 3;
    }
    return $error;
}

# 我的简历功能需要,
function get_resume($i = 0){
   $datas = array (
      'user_id' => '1',
      'user_name' => USER_NAME,
      'user_sex' => '女',
      'user_age' => '23 岁',
      'user_height' => '160CM',
      'user_marriage' => '未婚',
      'user_domicile' => '潼南',
      'user_record' => '大专',
      'user_worker' => '1-3年',
      'user_addr' => '潼南',
      'user_lodjob' => '文员',
      'user_nature' => '全职',
      'user_monpay' => '面议',
      'user_hopejober' => '行政专员/助理,人事专员/助理,文员/秘书,其他文职类职位,其他后勤类职位,咨询/顾问',
      'user_hopeguild' => '贸易/进出口,批发/零售,办公用品及设备,印刷/包装/造纸,其他行业',
      'user_Skillsa' => '在大学主修的专业是劳动与社会保障、保险学等。熟悉企业人力资源管理的六大模块。熟悉办公软件等，有一定的写作能力，有较好的沟通能力、组织能力等。<br />学习主动，有上进心，工作认真负责，有责任心，踏实肯干，有团队精神，容易相处，个人素质较好.',
      'user_Skillsb' => '0',
      'user_Skillsc' => '0',
      'user_Educationa' => '重庆城市管理职业学院#_#劳动与社会保障#_#大专#_#2007年9月至2010年7月',
      'user_Educationb' => '0#_#0#_#0#_#0',
      'user_Educationc' => '0#_#0#_#0#_#0',
      'user_workexpera' => '潼南县卧佛镇社保所#_#社保员#_#2500元#_#2010年7月至2012年7月',
      'user_workexperb' => '0#_#0#_#0#_#0',
      'user_workexperc' => '0#_#0#_#0#_#0',
      'user_Traininga' => '重庆城市管理职业学院#_#2009年10月至2009年11月#_#重庆城市管理职业学院#_#企业人力资源管理师#_#获得企业人力资源管理师资格证',
      'user_Trainingb' => '广东商学院#_#0#_#0#_#0#_#0',
      'user_introduce' => '在大学主修的专业是劳动与社会保障、保险学等。熟悉企业人力资源管理的六大模块。熟悉办公软件等，有一定的写作能力，有较好的沟通能力、组织能力等。
     学习主动，有上进心，工作认真负责，有责任心，踏实肯干，有团队精神，容易相处，个人素质较好。',
      'user_tel' => '13713595741',
      'user_qq' => '104569854',
      'user_email' => '1001@qq.com',
      'user_site' => 'www.fenanr.com',
      'user_power'=>0,
      'user_lookcount'=>0,
      'user_update'=>GET_TIME,
    );
    if($i === 0){
        return $datas;
     }else{
        return $datas[$i];
     }
}