<?php
/*
* 功能为管理员操作
* 此功能仅限管理员进入, 其它用户可以进入用户中心.
* 编辑时间 2013/01/02 10:52:33 Yuan(fenanr@hotmail.com)
*/

defined('IN_SYSTEM') === false && exit('PHPnew Blog..');
define('APP_ADMIN',true);

# 定义管理后台的配色, 不一定正确.
$c1 = '#ACCDE1';  // 边框线
$c2 = '#EBF5FC';  // 背景色
$c3 = '#303324';  // 文字颜色.
$c4 = '#46B2E5';  // 导航背景色, 
$c5 = '#EEF1E7';  // 底部背景色.

# 取得左侧列表项
$left_meun = temp_get_meun();

# 3.1版本开始建立用户管理中心.
if(app_user(true) === false){
    fun_message('./index.php?user=userout.html',1);
}

if(USER_ADMIN !== 1){
    fun_message('./index.php?user=index.html',1);
}else if(!USER_UID){
    fun_message('./index.php?user=login.html',1);
}

# 默认的一些变量
$meun_link = array();
$html['title'] = $html['title'];
$admin_css = fun_enhtml($default_parem[2]);
$include_file = 'admincp_index';
include(DIR_FUNCTION.'function_images.php');

# 流程分发功能块.
switch($default_parem[2]) {
    case 'enlink':
        // TODO: 后台管理, 链接管理功能.
        #　计算出主题数.
        $link_arrays = fun_source('enlink');
        if(IS_POST){
            if(is_numeric($default_post['catid']) === true){
                $default_post['ltitle'] = stripslashes($default_post['ltitle']);
                $default_post['lurl'] = stripslashes($default_post['lurl']);
                $keys = $default_post['catid'] + 0;
                $link_arrays[$keys] = array('ltitle'=>$default_post['ltitle'], 'lurl'=>$default_post['lurl']);
            }else{
                $link_arrays[] = array('ltitle'=>$default_post['ltitle'], 'lurl'=>$default_post['lurl']);
            }
            
            if($default_post['deles']){
                $enlink_count = fun_source('enlink_count');
                unset($enlink_count[$keys]);
                fun_source('enlink_count', $enlink_count);
                unset($link_arrays[$keys]);
            }
            
            fun_source('enlink', $link_arrays);
            exit('1');
        }
        
        empty($link_arrays) === true && $link_arrays = array();
        $link_arrays[] = array('lid'=>'news','ltitle' => '创建新链接',
                      'link' => '创建栏目');
        $enlink_count = fun_source('enlink_count');
        $new_arr = array();
        $i = $keys =0;
        foreach($link_arrays AS $key => $val){
            $i ++;
            if(!$val['lid'])
            $val['lid'] = $key;
            $val['count'] = $enlink_count[$key]+ 0;
            # 组成分享链接,以方便计算次数,
            $val['furl'] = URL_HOST . ltrim(fun_parse_url("./index/ajax/jump/link_{$key}.html"),'./');
            if($i > 5){
                $i = 0;
                $keys += 1;
            }
            $link_arrays[$key] = $val;
            $new_arr[$keys][$key] = $val;
        }
        
        $json_array = json::encode($link_arrays);
        $include_str = '链接管理';
        $include_file = 'admincp_'.$default_parem[2];
        break;
    case 'index':
        // TODO: 后台首页功能.
        $meun_link[] = array('默认','./index.php?admincp=index.html','default');
        $meun_link[] = array('系统环境','./index.php?admincp=index&syscheck.html','syscheck');
        $meun_link[] = array('安全维护','./index.php?admincp=index&safecheck.html','safecheck');
        $meun_class = $default_parem[3]?$default_parem[3]:'default';
        switch($default_parem[3]){
            case 'safecheck':
                $lastdate = fun_source('safechecktime');
                $lastdate = $lastdate[0];
                if($lastdate) 
                    $lastdate = fun_date($lastdate);
                    # 再继续一段分流
                    switch($default_get['safecheck']){
                        case '0':
                            echo json::encode(array('tag'=>'第一步: 对index.php循环访问十次.','i'=>'1','err'=>'0','errtag'=>''));
                            exit();
                            break;
                        case '1':
                            $url = URL_HOST.'index.php';
                            $err = 0;
                            for($i=0; $i<= 10; $i++){
                                $data = fun_geturl($url);
                                if(empty($data) === true){
                                    $err ++;
                                }
                            }
                            echo json::encode(array('tag'=>'检查根目录权限设置开始.','i'=>'2','err'=>1,'errtag'=>"index.php 共有 {$err} 次访问错误"));
                            fun_source('safechecktime',GET_TIME);
                            exit();
                            break;
                        case '2':
                            echo json::encode(array('tag'=>'体检功能不免费开放.','i'=>'0','err'=>'0','errtag'=>''));
                            fun_source('safechecktime',GET_TIME);
                            exit();
                            break;
                    }
                break;
            case 'phpinfo';
                ob_start();
                phpinfo();
                $phpinfomess = ob_get_contents();
                ob_end_clean();
                preg_match('/<body>(.*)<\/body>/isU',$phpinfomess,$reg);
                $phpinfomess = $reg[1];
                break;
            case 'syscheck':
                @clearstatcache();
                $getpath = empty($default_parem[4]) === false? $default_parem[4]:'./';

                if(substr_count($getpath,'/') <= 2){
                    $backpathlink = './index.php?admincp=index&syscheck.html';
                }else{
                    $getback = rtrim(dirname($getpath),'/').'/';
                    $backpathlink = './index.php?admincp=index&syscheck='.urlencode($getback).'.html'; 
                }
                
                $alldf = scandir($getpath);
                ksort($alldf);
                $end_info = array();
                
                $all_size = $filecount = $dircount = 0;
                foreach($alldf AS $val){
                    if($val === '.' || $val === '..')
                        continue;
                    
                    $dir = $getpath.$val.'/';
                    if(is_dir($dir) === true){
                        $dirsize = filesize($dir);
                        $dircount ++;
                        $all_size += $dirsize;
                        $dirsize = fun_sizecount($dirsize); 
                        
                        $link = './index.php?admincp=index&syscheck='.urlencode($dir).'.html';
                        $is_writable = is_writable($dir)?' ✔':'<span style="color:red"> ✘</span>';
                        $is_readable = is_readable($dir)?' ✔':'<span style="color:red"> ✘</span>';
                        $end_info['dir'][] = array(iconv('gbk','UTF-8', $val),$is_writable,$is_readable,date('Y-m-d H:i:s',filemtime($dir)), $dirsize,$link);
                    }else{
                        @clearstatcache();
                        $filesize = filesize($getpath.$val);
                        $all_size += $filesize;
                        $filecount ++;
                        $filesize = fun_sizecount($filesize);
                        $ftem = explode('.',$val);
                        $ftem = strtolower(end($ftem));
                        
                        $shoimg = array('css','gif','jpg','js','png','txt','html','php');
                        $fileimg = './Static/Images/filetype/typenone.gif';
                        if(in_array($ftem,$shoimg) === true){
                            $fileimg = "./Static/Images/filetype/type{$ftem}.gif";
                        }
                        
                        if($filecount > 300){
                            $omit = 1;
                            continue;
                        }
                       $end_info['file'][] = array(iconv('gbk','UTF-8', $val),is_writable($getpath.$val)?'✔':'<span style="color:red">✘</span>',is_readable($getpath.$val)?'✔':'<span style="color:red">✘</span>',date('Y-m-d H:i:s',filemtime($getpath.$val)),$filesize,$fileimg);
                    }
                }
                
                if(empty($end_info['file']) === false)
                $end_info['file'] = fun_array_sort($end_info['file'],array('3'=> SORT_DESC));
                
                $all_size = fun_sizecount($all_size);
                break;
                case 'ajax_url':
                    if(preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\’:+!]*([^<>\"])*$/", $default_parem[4])){
                        $rand = range(1, $default_get['count']+0);
                        $link = array();
                        foreach($rand AS $key => $val){
                            $rands = rand(1000000,9999999).str_pad($val,3,'0',STR_PAD_LEFT);
                            $link[$key] = $default_parem[4].'?'.$rands;
                            $rand[$key] = $rands;
                        }
                        $atime = microtime(true);
                        
                        $data = array();
                        if($default_get['type'] === 'curl'){
                           $data = fun_geturl($link); 
                        }else if($default_get['type'] === 'fsockopen'){
                            foreach ($link AS $key => $val){
                                $data[$key] = fun_fsockopen($val);
                            }
                        }else if($default_get['type'] === 'file_get_contents'){
                            foreach ($link AS $key => $val){
                                $data[$key] = fun_get_contents($val);
                            }
                        }else{
                            exit('错误方式');
                        }
                        
                        
                        $all_atime = sprintf('%01.2f', microtime(true) - $atime);
                        $i = 0;
                        $leftdata = '';
                        $urldata = fun_enhtml($default_parem[4])." (<span style=\"color:red\">系统无法检测小于200字节的网页</span>)";
                        $x_time = sprintf('%01.2f',$all_atime / $default_get['count']);
                        $leftdata .= "　<span style=\"color:blue\">同步采集{$default_get['count']}次数, 共花费: {$all_atime}秒, 平均每次花费: $x_time 秒</span><br />";
                        foreach($data AS $key => $val){
                            if(strlen($val) > 200){
                              $len = fun_sizecount(strlen($val));  
                            }else{
                               $len = ' - 采集错误';
                            }
                            $i ++;
                            $i = str_pad($i,3,'0',STR_PAD_LEFT);
                            $leftdata .= "　第 {$i} 次, 参数: {$rand[$key]}" .', 结果值: <span style="color:blue">'. $len.'</span><br />';
                        }
                        echo json::encode(array('left'=>$leftdata,'right'=>implode('<br />',temp_get_headers($default_parem[4])),'url'=>$urldata));
                    }else{
                       echo json::encode(array('left'=>'请输入正确的url','right'=>'','url'=>fun_enhtml($default_parem[4])));
                    }
                    exit();
                    break;
                default:
                    
                    if(is_file(DIR_DATA.'install_lock') === true){
                        $firtime = date('Y-m-d H:i:s',filemtime(DIR_DATA.'install_lock'));  
                    }
                    if(extension_loaded('mysqli')){
                        $mysqlver = mysql::server_info();
                    }else{
                        $mysqlver = mysql_get_server_info();
                    }
                    
                    
                    
                    $os = explode(' ', php_uname());
                break;
        }
        
        $include_str = 'Index';
        $admincp_class = 'admincp_'.$default_parem[2];
        break;
     case 'edit':
        // TODO: 文章创建及编辑功能.
        $edit = $default_parem[3] + 0;
        if(strpos($default_parem[3],'C') !== false){
            $thread['thread_fid'] = strtr($default_parem[3],array('C'=>''));
        }
        
        $intattcount = 0;
        
        $open = 'none';
        $opens = 0;
        if($edit != 0){
            $thread = mysql::get_one("SELECT thread_uid,thread_id, thread_fid, thread_message, thread_title,thread_date, thread_view, thread_history,thread_state,thread_index_img,thread_thum FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id=T.thread_uid WHERE T.thread_id='$edit' AND thread_first='0'");

            if(empty($user_edits) === true){
                fun_message('<span style="color:red">主题无法被编辑</span>');
            }
            
            function unbase_code_highlight($arrayvar){$mess = $arrayvar[2];$code = $arrayvar[1];$mess = fun_enhtml(base64_decode($mess));return "[code=$code]{$mess}[/code]";}
            $thread['thread_message'] = preg_replace_callback('/\[code=(.+)\](.*)\[\/code\]/isU','unbase_code_highlight',$thread['thread_message']);
            $thread['thread_message'] = fun_enhtml($thread['thread_message']);
            $thread['thread_link'] = fun_parse_url("./index.php?main=read&$edit.html");
            $thread['thread_title'] = fun_enhtml($thread['thread_title']);
            $thread['thread_fid'] = fun_enhtml($thread['thread_fid']);
            $thread['thread_history'] = empty($thread['thread_history']) === false? unserialize($thread['thread_history']):array();
            $thread['thread_history'] = fun_enhtml($thread['thread_history']);
            $thread['thread_date'] = date('Y-m-d H:i:s',$thread['thread_date']);
            empty($thread['thread_history']) === false && $open = '';
            empty($thread['thread_history']) === false && $opens = 1;
            # 主题高亮.
            $row['css'] = '';
            if(empty($thread['thread_history']) === false){
                $threads = $thread['thread_history'];
              if(empty($threads['th_color']) === false){
                $threads['th_color'] = fun_enhtml($threads['th_color']);
                $thread['css'] = "color: {$threads['th_color']};";
              }
              if(empty($threads['th_weight']) === false){
                $thread['css'] .= "font-weight: bolder;";
              }
            }
            $thread['thread_history']['th_replays'] = '';
            if($thread['thread_history']['th_replay'] !== '0' && empty($thread['thread_history']['th_replay']) === false){
               $thread['thread_history']['th_replays'] = date('Y-m-d H:i:s',$thread['thread_history']['th_replay']);
            }
            
            $thread['thread_message'] = nl2br($thread['thread_message']);
            
    		// 取得附件
    		$query = mysql::query("SELECT `aid`,`atime`,`amname`,`aname`,`asize`,`atag` FROM `DB_attachments` WHERE tid = '$edit' ORDER BY aid ASC");
    		$attch_array = array();
    		while($row = mysql::fetch_array($query)){
    			$row['path'] = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
                $row['img'] = '';
                $row['tag'] = 0;
                if(stripos($row['aname'],'.jpg') !== false ||stripos($row['aname'],'.gif') !== false || stripos($row['aname'],'.png') !== false){   
                    $row['img'] = '';//' onmouseover="$(this).next().show();" onmouseout="$(this).next().hide()"';
                    $row['tag'] = 1;
                }
                $row['asize'] = fun_sizecount($row['asize']);
                $row['atag'] = fun_enhtml($row['atag']);
                $row['thum'] = 0;
                if($thread['thread_thum'] === fun_thumpath($row['path'])){
                    $row['thum'] = 1;
                }
                $row['index'] = 0;
                if($thread['thread_index_img'] === $row['path']){
                    $row['index'] = 1;
                }
    			$attch_array[] = $row;
    		}
            $intattcount = count($attch_array);
        }
        
        # 当隐藏时, 删除配置文件.
        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 && $default_post['setting'] !== '1'){
                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($arravr){$mess = $arravr[2]; $code=$arravr[1]; $mess = base64_encode(fun_stripslashes(strtr($mess,array('\\\"'=>'"'))));return "[code=$code]{$mess}[/code]";}
            $default_post['message'] = preg_replace_callback('/\[code=(.+)\](.*)\[\/code\]/isU','base_code_highlight',$default_post['message']);
            $default_post['message'] = strtr($default_post['message'],array('<?'=>'&lt;?','?>'=>'?&gt;'));
            $thread_message = fun_enhtml($default_post['message']);
            $thread_message = strtr($thread_message,array('&lt;?'=>'<?','?&gt;'=>'?>','　'=>''));
            
            // 还原所有的html代码.
            function uncode_html($mess){ $mess = $mess[1]; $mess = base64_decode(strtr($mess,array('\"'=>'"')));return "[html]{$mess}[/html]";}
            $thread_message = preg_replace_callback('/\[html\](.*)\[\/html\]/isU','uncode_html',$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)");
                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;
            }
            
            #对发表时间进行更新
            if(empty($default_post['thread_date']) === false){
                $default_post['thread_date'] = strtotime($default_post['thread_date']);
            }else{
                $default_post['thread_date'] = GET_TIME;
            }
            
            $insert_new = 0;
            #如果edit为0, 就先值入主题, 然后再更改.
            if(empty($edit) === true){
                # 仅在新发表时有效.
                $thread_admin = 0;
                if($default_post['TFG']['th_sync'] === '1'){
                    $thread_admin = 2;
                }
                $sql = "INSERT INTO DB_thread(thread_uid,thread_fid, thread_first,thread_admin, thread_title, thread_message, thread_update, thread_date, thread_ip,thread_attch,thread_state,thread_history,thread_view) VALUES ($user_uid,'$thread_fid', '0', '$thread_admin', '0', '0', '0', '$thread_date', '$thread_ip','0','0','0','{$default_post['thread_view']}')";
                mysql::query($sql);
                $edit = mysql::insert_id();
                $insert_new = 1;
            }
            
            if($default_post['setting'] !== '1'){
                $update = "thread_title='$thread_title',thread_message='$thread_message',thread_fid='$thread_fid',thread_attch='$thread_attch',thread_thum='$thread_thum',thread_index_img='$thread_index_img',";
            }
            
            $sql = "UPDATE DB_thread SET $update thread_update='$thread_update',thread_date='{$default_post[thread_date]}',thread_state='$thread_state', thread_history='$thread_history',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)");
			}
            empty($default_post['attchmess']) === true && $default_post['attchmess'] = array();
            # 更新附件描述
            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'"); 
            }
            # 更新缓存
            cache::dele('default_list.php');
            if(empty($insert_new) === false){
                fun_message(fun_parse_url("./index.php?main=read&$edit.html"),1);
            }else{
                fun_message("./index.php?admincp=edit&$edit.html",1);  
            }
            
        }
        
        # 实际值的转换
        if(empty($thread['thread_title']) === true){
            $thread['thread_link'] = './index.php?admincp=edit.html';
            $thread['thread_titles'] = '';
        }else{
            $thread['thread_titles'] = $thread['thread_title'];
        }
        
        $thread['thread_message'] = strtr($thread['thread_message'], array('　'=>''));
        $include_str = '创建|编辑';
        $include_file = 'admincp_edit';
        break;
    case 'cache':
        // TODO: 后台管理, 日志管理功能. 
        $error_data = '';
        if($default_get['types'] === 'tpl'){
            // 删除掉模板缓存及数据缓存, 两个地址均来自模板及cache类.
            if(is_dir('./Data/cache_tpl/') === true){
                $return_str = '';
                $diropen = opendir('./Data/cache_tpl/');
                while($read = readdir($diropen)){
                    if($read =='.' || $read =='..')
                        continue;
                    if(is_file('./Data/cache_tpl/'.$read) === true){
                        if(unlink('./Data/cache_tpl/'.$read)){
                            $return_str .= "模板文件: /cache_tpl/$read 删除完成\n";
                        }else{
                            $return_str .= "模板文件: /cache_tpl/$read 删除失败,请检查权限\n";
                        }
                        
                    }
                }
                closedir($diropen);
            }
            if(empty($return_str) === true){
                echo 'Tpl无清理数据,更新完成';
            }else{
               echo $return_str; 
            }
            
            exit();
        }else if($default_get['types'] === 'data'){
            $return_str = '';
            // 删除掉模板缓存及数据缓存, 两个地址均来自模板及cache类.
             if(is_dir('./Data/cache_data/') === true){
                $diropen = opendir('./Data/cache_data/');
                while($read = readdir($diropen)){
                    if($read =='.' || $read =='..')
                        continue;
                    if(is_file('./Data/cache_data/'.$read) === true){
                        if(unlink('./Data/cache_data/'.$read)){
                            $return_str .= "缓存文件: ./cache_data/$read 删除完成\n";
                        }else{
                            $return_str .= "缓存文件: ./cache_data/$read 删除失败,请检查权限\n";
                        }
                    }
                }
                closedir($diropen);
            }
            if(empty($return_str) === true){
                echo 'Data无清理数据,更新完成';
            }else{
               echo $return_str; 
            }
            exit();
        }else if($default_get['types'] === 'mysql'){
            $return_str = '';
    		$query = mysql::query("SELECT `aid`,`atime`,`amname` FROM `DB_attachments` WHERE temp = '0'");
    		$attch_array = $dele = array();
    		while($row = mysql::fetch_array($query)){
    			$row['path'] = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
                if(is_file($row['path']) === true){
                    if(unlink($row['path'])){
                        $return_str .= "成功: 附件表: {$row['path']} 删除完成\n";
                    }else{
                        $return_str .= "失败: 附件表: {$row['path']} 删除失效,请检查权限\n";
                    }
                }
                $dele[] = $row['aid']+0;
    		}
            // 删除掉记录
            if(empty($dele) === false){
                $dele = implode(',',$dele);
                mysql::query("DELETE FROM `DB_attachments` WHERE aid IN ($dele)");
                $delecount = mysql::affected_rows();
                $return_str .='mysql附件记录删除'.$delecount."条\n";
            }
            
            # 优化数据表.
            $query = mysql::query('SHOW TABLE STATUS FROM '.DBNAME);
            while($row = mysql::fetch_array($query)){
                # 计算可以优化的表
                if($row['Data_length'] <= 500000000){ // 500MB
                    mysql::query("OPTIMIZE TABLE {$row['Name']}");
                    $return_str .= "数据表: {$row['Name']} 优化完成\n";
                }else{
                    $return_str .= "数据表: {$row['Name']} 表容量过大,无法优化\n";
                }
            }
            
            if(empty($return_str) === true){
                echo 'Mysql无清理数据,更新完成';
            }else{
               echo $return_str; 
            }
            exit();
      }else if($default_get['types'] === 'ftp'){
        @clearstatcache();
        $dir = temp_dir_list();
        echo "====================================================\n";
        echo "===   目录数量: ".$dir['dir']."个 \n";
        echo "===   文件数量: ".$dir['file']."个 \n";
        echo "===   FTP占用容量: ".fun_sizecount($dir['size'])."\n";
        echo '===================================================='."\n";
        echo implode($dir['data']);
        exit();
      }else if($default_get['types'] === 'log'){
        $log_file = DIR_ROOT.'/Data/run_log/'.strtoupper(md5($_config['default']['ankey']));
        echo 'log文件路径: '. $log_file."\n";
        if(is_file($log_file) === true){
            echo 'log文件容量: '. filesize($log_file)."\n";
            if(unlink($log_file)){
                echo "log文件删除成功 \n";
            }
        }else{
            echo 'log文件容量:0 (文件不存在)'."\n";
            echo "log文件删除失败 \n";
        }
        exit();
      }
      
      $file = DIR_ROOT.'/Data/run_log/'.strtoupper(md5($_config['default']['ankey']));
      if(is_file($file) === true)
        $error_data = file_get_contents($file);
  
   
        $include_str = '缓存管理';
        $include_file = 'admincp_cache';
        break;
    case 'thdele':
        // TODO: 文章删除功能, 无界面显示.
        if(is_numeric($default_parem[4]) === true){
            $dele = $default_parem[4]+0;
            $i = 1;
        }else{
            $dele = $default_parem[3]+0;
        }
        app_thdele($dele);
        
        if($i === 1)
            exit('1');
        
        fun_header();
        break;
    case 'cats':
        // TODO: 栏目管理功能.
        $times = GET_TIME;
        # 处理post数据
        if(IS_POST){
                $default_get['type'] = 'ajax';
                $default_get['c_name'] = trim($default_post['icat']);
                $default_get['c_tags'] = rtrim($default_post['tags']);
                $default_get['c_tpl'] = in_array($default_post['istyle'], array('0','gen','show')) === false? 0:$default_post['istyle'];
                $default_get['c_asc'] = $default_post['iasc']+0;
                $default_get['deles'] = $default_post['deles']+0;
                
                if($default_post['catid'] === 'news')
                    $default_get['type'] = 'up';
            if($default_get['type'] === 'ajax'){
                 cache::dele('main_cats.php');
                $c_id = $default_post['catid'] + 0;
                
                // 删除栏目自然要删除所有的主题及附件
                if(empty($default_get['deles']) === false){
                    mysql::query("DELETE FROM DB_cat WHERE c_id = '$c_id'");
                
                    $query = mysql::query("SELECT thread_id FROM DB_thread WHERE thread_fid = '$c_id'");
                    $dele_array = array();
                    while($row = mysql::fetch_array($query)){
                        $dele_array[] = $row['thread_id']+0;
                    }
                    if(empty($dele_array) === false){
                        $dele_array = implode(',',$dele_array);
                        mysql::get_one("DELETE FROM DB_thread WHERE thread_id IN ($dele_array) OR thread_first IN ($dele_array)"); // 主题
                        mysql::query("UPDATE DB_attachments SET `temp`='0' WHERE tid IN ($dele_array)"); // 附件只需要设置状态即可,更新缓存时再清除. 
                    }
                    echo json::encode(array('s'=>'dele', 'cls'=>'.catid_'+$c_id));
                    exit();
                }
                // 更新一下栏目库
                mysql::query("UPDATE DB_cat SET c_name = '{$default_get['c_name']}',c_tags='{$default_get['c_tags']}',c_asc='{$default_get['c_asc']}',c_tpl='{$default_get['c_tpl']}' WHERE c_id = '$c_id'");
                echo json::encode(array('s'=>'up','count'=>mysql::affected_rows(), 'm'=>$default_get['c_name']));
                exit();
            }
            # 插入新记录.
           if(IS_POST && empty($default_get['c_name']) === false && empty($default_get['deles']) === true){
                cache::dele('main_cats.php');
                $cats = mysql::get_one("SELECT c_id FROM DB_cat WHERE c_name='{$default_get['c_name']}'");
                if(empty($cats) === true){
                    mysql::query("INSERT INTO DB_cat (`c_name`, `c_tags`, `c_asc`, `c_tpl`, `c_time`) VALUES ('{$default_get['c_name']}', '{$default_get['c_tags']}','{$default_get['c_asc']}','{$default_get['c_tpl']}', $times)");
                }
                echo json::encode(array('s'=>'news', 'cls'=>'.catid_'+$c_id));
                exit();
            }
            
            echo json::encode(array('s'=>'none', 'cls'=>''));
            exit();
        }
        
        #　计算出主题数.
        $all_count = cache::read('cat_list_count','cat_list_count.inc.php', false);
        $page = max(1, $default_parem[3]);
        $re = ($page - 1) * 50;
        $query = mysql::query("SELECT c_id,c_name,c_tags,c_asc,c_tpl FROM DB_cat ORDER BY c_asc DESC LIMIT $re,50");
        $json_array = array();
        while($row = mysql::fetch_array($query)){
            $row['clink'] = fun_parse_url("./index.php?main=cat&{$row['c_id']}.html");
            $row['c_name'] = $row['c_name'];
            if($all_count[$row['c_id']] >= 999)
                $all_count[$row['c_id']] = 999;
            $row['counts'] = $all_count[$row['c_id']]+0;
            $row['attcount'] = 0;
            $json_array[$row['c_id']] = $row;
        }
        $json_array = fun_array_sort($json_array,array('c_asc'=>SORT_DESC, 'c_id'=>SORT_DESC));
        $json_array['news'] = $newarr = array('c_id' => 'news',
      'c_name' => '创建栏目',
      'c_tags' => '0',
      'c_asc' => '0',
      'c_tpl' => '0',
      'clink' => '0',
      'counts' => 0,
      'attcount' => 0);
        
        if(count($json_array) > 1){
            $query = mysql::query("SELECT count(aid) AS counts, fid FROM `DB_attachments` GROUP BY fid ORDER BY aid DESC LIMIT 1000000");
            while($row = mysql::fetch_array($query)){
                if($row['counts'] >= 9999)
                    $row['counts'] = 9999;
                if($json_array[$row['fid']])
                    $json_array[$row['fid']]['attcount'] = $row['counts'];
            }
        }
        # 切分为5个一行排.
        $i = $keys = 0;
        $cat_array = array();
        foreach($json_array AS $key => $val){
            $i ++;
            $cat_array[$keys][$key] = $val;
            if($i === 5){
                $keys += 1;
                $i = 0;
            }
        }
        $json_array = json::encode($json_array);
        
        # 分页
         $count = mysql::get_one("SELECT count(c_id) AS counts FROM DB_cat");
         $page_list = fun_multi($count['counts'],50,$page,'./index.php?admincp=cats&{#1}.html');
         empty($page_list) === true && $page_list = '<span style="color:#CCCCCC">暂时没有分页信息</span>';
        $include_str = '栏目管理';
        $include_file = 'admincp_cats';
        break;
    case 'useradmin':
        // TODO: 用户管理功能
        # 查询条件
        $where = '';
        if(empty($default_get['search']) === false){
            $search = $default_get['search'];
            if(is_numeric($search) === true){
                $where = ' AND user_id ='.(int) $search;
            }else if(strpos($search,'@') !== false){
                $where = " AND user_email  = '$search'";
            }else{
                $where = " AND user_name ='$search'";
            }
            if($search == 'admin-1'){
                $where = " AND user_admin ='1'";
            }
            if($search == 'posts-1'){
                $where = " AND user_posts ='1'";
            }
            if($search == 'deles-1'){
                $where = " AND user_deles ='1'";
            }
            if($search == 'app-1'){
                $where = " AND user_app != '0'";
            }
        }
        $page = max(1,$_GET['page']+0);
        $re = ($page - 1) * 50;
        
        # 处理排序
        $dec = 'user_logtime';
        if($default_get['sort'] === 'user_id'){
            $dec = 'user_id';
        }
        
        // 查询出来, 显示最近注册用户
        $query = mysql::query("SELECT * FROM DB_user WHERE 1 {$where} ORDER BY $dec DESC LIMIT $re,50");
        $user_list = array();

        while($row = mysql::fetch_array($query)) {
            $row['user_regtime'] = fun_date($row['user_regtime']);
            if(empty($row['user_app']) === false){
                $row['user_posts']= empty($row['user_posts']) === true?'color:#000':'color:blue';
                $row['user_edits']= empty($row['user_edits']) === true?'color:#000':'color:blue';
                $row['user_deles']= empty($row['user_deles']) === true?'color:#000':'color:blue';
                $row['user_admin']= $row['user_admin'] != 1?'color:#000':'color:blue';                
            }else{
                $row['user_posts']= empty($row['user_posts']) === true?'color:#000':'color:red';
                $row['user_edits']= empty($row['user_edits']) === true?'color:#000':'color:red';
                $row['user_deles']= empty($row['user_deles']) === true?'color:#000':'color:red';
                $row['user_admin']= $row['user_admin'] != 1?'color:#000':'color:red';
            }
            
            $row['logo'] = './App/default_tpl/source/feuser.gif';
            if($row['useropenid']){
                $row['logo'] = './App/default_tpl/source/qquser.gif';
                $row['openid'] = 'QQ USERID: '.$row['useropenid'];
            }else{
                $row['openid'] = '普通会员ID: '.$row['user_id'];
            }
            
            $row['openid'] = '用户上次登录时间: '. date('Y-m-d H:i:s',$row['user_logtime']).'\n '.$row['openid'];
            
            $user_list[] = $row;
        }
        
        # 分页
        $count = mysql::get_one("SELECT count(1) AS counts FROM DB_user WHERE 1 {$where}");
        $page_list = fun_multi($count['counts'],50,$page,"./index.php?admincp=useradmin&search=$search&page={#1}.html");
        
        $include_str = '用户管理';
        $include_file = 'admincp_useradmin';
        break;
   case 'enadmin':
        // TODO: 主题管理功能.
        $num = 50;
        $page = max(1,$default_get['page']+0);
        # 条件相关
        $where = '';
        if(empty($default_get['search']) === false){
            $search = trim($default_get['search']);
            $types = $default_get['types'];
            # 分切几个条件
            if($types === 'thread_title'){
                $where .= " AND T.thread_title LIKE '%{$search}%'";
            }else if($types === 'thread_state'){
                $types_array = array('精华'=>2,'推荐'=>4,'热贴'=>3,'置顶'=>1,'编辑采用'=>5);
                if(is_numeric($search) === true && in_array($search+0,array_values($types_array))){
                    $search +=0;
                }else{
                    $search = $types_array[$search];
                }
                $where .= " AND T.thread_state = '$search'";
                
            }else if($types === 'thread_uid'){
                $one = app_user($search);
                $one['user_id'] +=0;
                $where .= " AND T.thread_uid = '{$one['user_id']}'";
            }else if($types === 'thread_update'){
                $temp = explode('=',$search);
                if(empty($temp[0]) === false){
                    $temp[0] = strtotime($temp[0]) + 0;
                    $where .= " AND T.thread_date >={$temp[0]}";
                }
                if(empty($temp[1]) === false){
                    $temp[1] = strtotime($temp[1]) + 0;
                    $where .= " AND T.thread_date <={$temp[1]}";
                }
            }else if($types === 'thread_fid'){
                foreach($cat_array AS $key => $val){
                    if($val['c_name'] === $search){
                        $fid = $key+0;
                        break;
                    }
                }
                if($fid)
                   $where .= " AND thread_fid = '$fid'"; 
            }
        }

        $re = ($page - 1) * $num;
        $query = mysql::query("SELECT T.thread_id,T.thread_fid,T.thread_title,T.thread_date,T.thread_history,T.thread_attch,U.user_name FROM `DB_thread` AS T LEFT JOIN `DB_user` AS U ON U.user_id = T.thread_uid WHERE T.thread_first='0' {$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']];
            
            $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['link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
            $row['c_name'] = $cat_array[$row['thread_fid']]['c_name'];
            
            # 主题高亮.
            $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;";
              }
            }
            $thread_array[] = $row;
        }
        
        # 分页
        $count = mysql::get_one("SELECT count(1) AS counts FROM `DB_thread` AS T WHERE T.thread_first='0' {$where}");
        $page_list = fun_multi($count['counts'],$num,$page,"./index.php?admincp=enadmin&search={$search}&types=$types&page={#1}.html");
        $include_str = '主题管理';
        $include_file = 'admincp_enadmin';
        break; 
  case 'replays':
        // TODO: 回复管理功能.
       $num = 50;
       $page = max(1,$default_get['page']+0);
       
        # 条件相关
        $where = '';
        if(empty($default_get['search']) === false){
            $search = trim($default_get['search']);
            $types = $default_get['types'];
            # 分切几个条件
            if($types === 'thread_title'){
                $where .= " AND T2.thread_title LIKE '%{$search}%'";
            }else if($types === 'thread_state'){
                $where .= " AND T.thread_message LIKE '%$search%'";
            }else if($types === 'thread_uid'){
                $one = app_user($search);
                $one['user_id'] +=0;
                $where .= " AND T.thread_uid = '{$one['user_id']}'";
            }else if($types === 'thread_update'){
                $temp = explode('=',$search);
                if(empty($temp[0]) === false){
                    $temp[0] = strtotime($temp[0]) + 0;
                    $where .= " AND T.thread_date >=$temp[0]";
                }
                if(empty($temp[1]) === false){
                    $temp[1] = strtotime($temp[1]) + 0;
                    $where .= " AND T.thread_date <=$temp[1]";
                }
            }
        }
        
        $re = ($page - 1) * $num;
        $query = mysql::query("SELECT T.*,U.user_name,T2.thread_title,T2.thread_history FROM `DB_thread` AS T LEFT JOIN `DB_user` AS U ON U.user_id = T.thread_uid LEFT JOIN `DB_thread` AS T2 ON T2.thread_id = T.thread_first WHERE T.thread_admin = '1' {$where} ORDER BY `thread_id` DESC LIMIT $re, $num");

        $thread_array = array();
        while($row = mysql::fetch_array($query)){
            $row['thread_date'] = fun_date($row['thread_date']);
            $row['fidlink'] = fun_parse_url("./index.php?main=cat&{$row['thread_fid']}.html");
            $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_first']}.html");
            $row['c_name'] = $cat_array[$row['thread_fid']]['c_name'];
            
            # 主题高亮.
            $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;";
              }
            }
            
            $thread_array[] = $row;
        }
        
        # 分页
        $count = mysql::get_one("SELECT count(T.thread_uid) AS counts FROM `DB_thread` AS T LEFT JOIN `DB_user` AS U ON U.user_id = T.thread_uid LEFT JOIN `DB_thread` AS T2 ON T2.thread_id = T.thread_first WHERE T.thread_admin = '1' {$where}");

        $page_list = fun_multi($count['counts'],$num,$page,"./index.php?admincp=replays&search={$search}&types=$types&page={#1}.html");
        $include_str = '回复管理';
        $include_file = 'admincp_replays';
        break;
  case 'stop_user':
        // TODO: 禁闭用户功能, 无界面显示.
        $userid = $default_parem[3] + 0;
        
        # 并且关闭用户的权限.
        mysql::query("UPDATE `DB_user` SET user_admin = '2' WHERE user_id = '$userid' AND user_admin != '1'");
        $i = mysql::affected_rows();
        
        # 后果相当严重, 请小心使用
        if(empty($i) === false){
            $query = mysql::query("SELECT `thread_id` FROM `DB_thread` WHERE thread_uid = '$userid'");
            while($row = mysql::fetch_array($query)){
                app_thdele($row['thread_id']);
            }
            fun_message('用户被禁闭成功, 共影响用户:'.$i.'位');
        }else{
            fun_message('用户被禁闭失败, 共影响用户:'.$i.'位');
        }
        
        exit();
        break;
  case 'setlink':
        // TODO: 友情链接功能.
        if(empty($link_array) === true){
            $link_array = array();
        }
        
        $type = 0;
        $post_array = array();
        # 更新友情链接
        if(empty($default_get['type']) === false){
            $type = 1;
            if(empty($default_get['deles']) === false){
                unset($link_array[$default_get['c_id']]);
            }else{
                if(empty($link_array[$default_get['c_id']]) === false){
                    $default_get['c_id'] +=0;
                    $link_array[$default_get['c_id']]['link_name'] = ($default_get['link_name']);
                    $link_array[$default_get['c_id']]['link_alink'] = ($default_get['link_alink']);
                    $link_array[$default_get['c_id']]['link_tags'] = ($default_get['link_tags']);
                    $link_array[$default_get['c_id']]['link_ico'] = ($default_get['link_ico']);
                    $link_array[$default_get['c_id']]['link_asc'] = $default_get['link_asc']+0;
                    //$link_array[$default_get['c_id']]['link_time'] = GET_TIME;
                }else{
                    # 新增加内容.
                    $link_array[] = array(
                        'link_name' => ($default_get['link_name']),
                        'link_alink' => ($default_get['link_alink']),
                        'link_tags' => ($default_get['link_tags']),
                        'link_ico' => ($default_get['link_ico']),
                        'link_asc' => $default_get['link_asc']+0,
                        'link_time'=> GET_TIME,
                    );
                }
            }
            $post_array = $link_array;
        }
        
        
        if($type === 1){
            # 数组排序好.
            if(empty($post_array) === false){
                # 分开排序.
                $ascarr = $timearr = array();
                foreach($post_array AS $val){
                    if($val['link_asc']){
                       $ascarr[] = $val;  
                    }else{
                       $timearr[] = $val;
                    }
                }
                
                if(empty($ascarr) === false)
                    $ascarr = fun_array_sort($ascarr,array('link_asc'=>SORT_DESC));
                if(empty($timearr) === false){
                    $timearr = fun_array_sort($timearr,array('link_time'=>SORT_ASC));
                    foreach($timearr AS $val){
                        $ascarr[] = $val;
                    }
                }
                if(empty($default_get['deles']) === true)
                    $post_array = $ascarr;
            }else{
                $post_array = array();
            }
            
            fun_source('setlink', $post_array);
            cache::dele('setting_cache.php');
            if(empty($default_get['type']) === false)
                exit('1');
        }
        
        $page_list = '变更需要勾中前面选项';
        $return_data = tem_multi($link_array, './index.php?admincp=setlink&page={#1}.html');
        if($return_data['data'])
            $link_array = $return_data['data'];
        if($return_data['page_list'])
            $page_list = $return_data['page_list'];

        $include_str = '友情链接';
        $include_file = 'admincp_setlink';
        break;
  case 'useredit':
        // TODO: 用户编辑功能, 个人信息等.
        $user_id = empty($default_parem[3]) === true? USER_UID:$default_parem[3]+0;
        $user_one = mysql::get_one("SELECT * FROM `DB_user` WHERE user_id ='$user_id'");
        
        if(empty($user_one) === true){
            fun_message('错误的用户id');
        }
        
        if($user_one['user_app'])
            $user_one['user_app'] = fun_date('Y-m-d H:i:s',$user_one['user_app']);
        $user_email = fun_enhtml($user_email);
        $user_logo = fun_getlogo($user_one['user_id'],$user_one['user_logo']);
        
        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){
                    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{
                        fun_imageresize($logo_path,120,120,$logo_path);
                    }
                }
            }
            $default_post['user_name'] = fun_enhtml($default_post['user_name']);
            strlen($default_post['user_name']) < 4 && $default_post['user_name'] = 'User';
            
            # 禁止对管理员组进行特殊权限的设置, 永久设置为1
            $default_post['user_deles'] += 0;
            $default_post['user_posts'] += 0;
            if($default_post['user_admin'] === '1'){
                $default_post['user_posts'] = 1;
                $default_post['user_deles'] = 1;
            }
            if($user_one['user_id'] == 1){
                $default_post['user_admin'] = $user_one['user_admin']; // 直接沿用管理组.
            }
            # 组合更新用户的项目
            $update = "user_email='{$default_post['user_email']}',user_posts='{$default_post['user_posts']}',user_deles='{$default_post['user_deles']}'";
            if(empty($default_post['user_pass']) === false){
                $pass = md5(md5($default_post['user_pass']));
                $update .=",user_pass='$pass'";
            }
            
            if(empty($upload_id) === false){
                $update .=",user_logo='1'";
            }

            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']}'";
            }
            $update .=",useropenid='{$default_post['useropenid']}'";
            $default_post['user_exp']+=0;
            $update .=",user_exp='{$default_post['user_exp']}'";
            mysql::query("UPDATE DB_user SET user_name = '{$default_post['user_name']}',user_app='0',user_admin='{$default_post['user_admin']}', {$update} WHERE user_id ='$user_id'");         
            fun_message(fun_referer(),1);
        }
        $include_str = '个人信息';
        $include_file = 'admincp_useredit';
        break;      
    case 'setting':
        // TODO: 系统设置功能.
        if(IS_POST){
            $default_post['attch_array'] = strtolower($default_post['attch_array']);
            $default_post['editday'] = max(1,$default_post['editday']+0);
            $default_post['indexcount'] = max(1,$default_post['indexcount']+0);
            $default_post['replay_exp'] = max(1,$default_post['replay_exp']+0);
            $default_post['user_exp'] = max(1,$default_post['user_exp']+0);
            $default_post['img_maxread'] = max(1,$default_post['img_maxread']+0);
            $default_post['replay_time'] += 0;
            # 检测伪静态是否可以开启
            if($default_post['htaccess'] === '1'){
                $getdata = fun_get_contents(URL_HOST.'index/main/htaccess.html');
                if($getdata !== 'htaccess OK'){
                    $default_post['htaccess'] = 0;
                }
            }
            $setting = $default_post;
            cache::dele('setting_cache.php');
            fun_source('setting',$setting);
            fun_message(fun_referer(),1);
        }else{
            $setting = fun_source('setting');
            $setting = fun_enhtml($setting);
        }
        
        # 独立于前端, 如果用户需要独立设置自我的时区, 此时就有效了.
        empty($setting['timeoffset']) === true && $setting['timeoffset'] = '0';
        if(function_exists('date_default_timezone_set')) {
        	@date_default_timezone_set('Etc/GMT'.($setting['timeoffset'] > 0 ? '-' : '+').(abs($setting['timeoffset'])));
        }else{
            @ini_set('date.timezone','Etc/GMT'.($setting['timeoffset'] > 0 ? '-' : '+').(abs($setting['timeoffset'])));
        }
        $htaccess = URL_HOST.'index/main/htaccess.html';
        $a_date = date('Y-m-d H:i:s',GET_TIME);
        $include_str = '系统设置';
        $include_file = 'admincp_setting';
        break;
    case 'attachments';
        // TODO: 附件管理功能.
        $page = max(1,$default_parem[3]+0);
        $re = ($page - 1) * 20;
        $query = mysql::query("SELECT A.*,T.thread_title FROM DB_attachments AS A LEFT JOIN DB_thread AS T ON T.thread_id=A.tid WHERE temp='1' ORDER BY aid DESC LIMIT $re,20");
        $attalist = array();
        while($row = mysql::fetch_array($query)){
            $path = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
            if(strpos($row['atype'],'image') !== false){
                $imginfo = getimagesize($path);
                $path = '<img class="aimg" src="'.$path.'" />';
                $info = "W:{$imginfo[0]} H:{$imginfo[1]}";
            }else{
                $info = '<a href="'.$path.'">downloads</a>';
                $path = '<img class="aimg" src="./Data/attachments/attach.jpg" />'; 
            }
            $title = $row['thread_title'];
            $size = fun_sizecount($row['asize']);
            $link = fun_parse_url("./index.php?main=read&{$row['tid']}.html");
            $row = array();
            $row['path'] = $path;
            $row['title'] = fun_cutstr($title,30,'');
            $row['size']= $size;
            $row['info'] = $info;
            $row['link'] = $link;
            $attalist[]=$row;
        }
        $count = mysql::get_one("SELECT count(tid) AS counts FROM DB_attachments WHERE temp=1");
        $page_list = fun_multi($count['counts'],20,$page,'./index.php?admincp=attachments&{#1}.html');
        $include_str = '附件管理';
        $include_file = 'admincp_attachments';
        break;
    case 'allcode':
            // TODO: 耦合管理功能,
            $meun_link[] = array('系统变量','./index.php?admincp=allcode.html','default');
            $meun_link[] = array('普通变量','./index.php?admincp=allcode&types=1.html','code_1');
            $meun_link[] = array('勾注变量','./index.php?admincp=allcode&types=2.html','code_2');
            $meun_link[] = array('广告变量','./index.php?admincp=allcode&types=3.html','code_3');
            $meun_link[] = array('自定义变量','./index.php?admincp=allcode&types=4.html','code_4');
            $meun_class = $default_parem[4]?'code_'.$default_parem[4]:'default';
        
            $data = array();
            empty($default_get['types']) === true && $default_get['types'] = 0;
            $data = fun_source('allcode');
            # 代码类型
            $type_arr = array();
            $type_arr[0] = '系统变量';
            $type_arr[1] = '普通变量';
            $type_arr[2] = '勾注变量';
            $type_arr[3] = '广告变量';
            $type_arr[4] = '自定义变量';

            if($default_parem[3] === 'editor'){
                $keyid = 0;
                if(isset($default_parem[4]) === true)
                    $keyid = $default_get['editor'];
                
                $editor = 1;
                if(IS_POST){
                  $default_post['tags'] = fun_cutstr($default_post['tags'],220);
                  $default_post['vars'] = fun_cutstr($default_post['vars'],50);
                  if($keyid === 0){
                     $md5 = md5($default_post['types'].'_'.trim($default_post['vars']));
                      if(empty($default_post['types']) === true || strpos($default_post['vars'],'Hook_') !== false){ 
                        fun_message('<span style="color:red">创建操作被拒绝!</span>');
                      }
                      $data[$md5] = array(
                          'types' => $default_post['types']+0,
                          'vars' => fun_enhtml($default_post['vars']),
                          'tags' => fun_enhtml($default_post['tags']),
                          'codes' => stripslashes($default_post['codes']),
                          'times' => GET_TIME,
                      );
                      $re = 1;
                  }else{
                      if(empty($default_post['types']) === false && strpos($default_post['vars'],'Hook_') !== false){ 
                        fun_message('<span style="color:red">修改操作被拒绝!</span>');
                      }
                      $md5 = $keyid;
                      $data[$md5] = array(
                          'types' => $default_post['types']+0,
                          'vars' => fun_enhtml($default_post['vars']),
                          'tags' => fun_enhtml($default_post['tags']),
                          'codes' => stripslashes($default_post['codes']),
                          'times' => GET_TIME,
                      );
                      $re = 0;
                  }
                  
                  if($data && $re >= 0){
                      $data = fun_array_sort($data, array('times'=>SORT_DESC));
                      fun_source('allcode',$data);
                      cache::dele('allcode_cache.php');
                  }
                  
                  if($re === 0){
                    fun_message("./index.php?admincp=allcode&editor={$md5}.html",1);
                  }else{
                    fun_message("./index.php?admincp=allcode&types={$default_post['types']}.html",1);
                  }
                }

                if($keyid !== 0){
                    $data = $data[$keyid];
                }else{
                    $data['vars'] = '变量名';
                    $data['tags'] = '说明';
                    $data['codes'] = '显示代码';
                }
            }
             
             if($default_parem[3] === 'delete'){
                
                $tem = $data[$default_parem[4]];
                
                if( (strpos($tem['vars'],'Hook_') !== false || $tem['vars'] === 'All_var') && $tem['types'] == 0){
                    fun_message('<span style="color:red">禁止删除默认的变量!</span>');
                } 
                unset($data[$default_parem[4]]);
                fun_source('allcode', $data);
                cache::dele('allcode_cache.php');
                fun_message(fun_referer(),1);
             }
             
            # 列表显示将有所不同.
            $get_var = array();
            foreach($data AS $key => $val){
                $val['size'] = fun_sizecount(strlen($val['codes']));
                $types = $val['types'];
                $val['types'] = $type_arr[$val['types']];
                
                if(isset($default_get['types']) === true && $types != $default_get['types']){
                    continue;
                }
                $get_var[$key] = $val;
            }
            
                $return_data = tem_multi($get_var, './index.php?admincp=allcode&types='.$default_get['types'].'&page={#1}.html');
                if($return_data['data'])
                    $get_var = $return_data['data'];
                if($return_data['page_list'])
                    $page_list = $return_data['page_list'];
            
            $include_str = '耦合管理';
            $include_file = 'admincp_allcode';
            break;
        case 'source':
            // TODO: 资源管理功能, 可上传文件存储.
            $data = fun_source('upfile');
            
            #删除操作
            if($default_get['delete'] && empty($data[$default_get['delete']]) === false){
                $dele = $data[$default_get['delete']];
                $delepath = './Data/cache_upload/'.$dele['md5file'];
                
                if(is_file($delepath) === true)
                    $bool = unlink($delepath);
                
                unset($data[$default_get['delete']]);
                
                fun_source('upfile', $data);    
                fun_message('删除上传文件成功, 现在返回!');
            }
            
            #上传操作
            if(IS_FILES){
                $file = $_FILES['upfile'];
                $extension = substr($file['name'],-4);
                $update = $_REQUEST['update'];
                if($data[$update]['md5file']){
                    $md5 = $update;
                    $file_path = './Data/cache_upload/'.$data[$update]['md5file'];
                    $i = 0;
                }else{
                    $md5 = md5($file['name']);
                    $file_path = './Data/cache_upload/'.$md5.$extension;
                    $i =1;
                }
                
                if(in_array($extension, array('.php')) === true)
                    fun_message('禁止上传php文件, 谢谢');                
                $bool = move_uploaded_file($file['tmp_name'],$file_path);
                
                if($bool){
                   # 改变当前数据值, 以便入库
                   $newarr = array();
                   $newarr['name'] = $file['name'];
                   $newarr['type'] = $file['type'];
                   $newarr['md5file'] = $md5.$extension;
                   $newarr['size'] = $file['size'];
                   $newarr['time'] = GET_TIME;
                   
                        $data[$md5] = $newarr;
                       $data = fun_array_sort($data, array('time'=>SORT_DESC));
                       fun_source('upfile', $data);
                   //}
                   
                   fun_message(fun_referer(),1);
                }
            }
            
            foreach($data AS $key => $val){
                $val['size'] = fun_sizecount($val['size']);
                $val['time'] = fun_date($val['time']);
                $val['type'] = strtok($val['type'],'/');
                $val['md5file2'] = $val['md5file'];
                if($val['type'] === 'image'){
                    $val['md5file'] = fun_enhtml('<img src="./Data/cache_upload/'.$val['md5file'].'" />');
                }else{
                    $val['md5file'] = fun_enhtml('<a href="./Data/cache_upload/'.$val['md5file'].'">'.$val['name'].'</a>');
                }
                $data[$key] = $val;
            }
            
            $return_data = tem_multi($data, './index.php?admincp=source&page={#1}.html');
            if($return_data['data'])
                $data = $return_data['data'];
            if($return_data['page_list'])
                $page_list = $return_data['page_list'];
        
            
            $include_str = '资源管理';
            $include_file = 'admincp_source';
            break;
        case 'db_back':
            // TODO: 数据库备份管理功能.
            # phpnew blog 安全功能.
            
            ##################### DELE ####################################
            if($default_get['dele']){
                $name = basename($default_get['dele'],'.sql');
                $name = fun_enhtml($name);
                $name = "./Data/run_log/$name.sql";
                if(is_file($name) === true){
                    $bool = unlink($name);
                }
                if($bool){
                    fun_message($name.' 备份文件删除成功!');
                }else{
                    fun_message($name.' 备份文件删除失败!');
                }
            }
            ##################### DELE ####################################
            if(empty($default_get['name']) === false){
                $DBNAME = $default_get['name'];
            }else{
                $DBNAME = DBNAME;
            }
            $filemd5 = md5(GET_ANKEY.implode(',',$default_post['fields']));
            $sqlpath = "./Data/run_log/[$DBNAME]_{$filemd5}.sql";
            if(IS_POST){
                set_time_limit(0);
                if(is_file($sqlpath) === true){
                   $bool = unlink($sqlpath); 
                   if(!$bool)
                     fun_message($sqlpath.'无法删除,请手工删除文件!');
                }
                
                $fields_arr = $default_post['fields'];
                # 数据库创建.
                $sql = "SHOW CREATE DATABASE `$DBNAME`";
                $cresql = mysql::get_one($sql);
                if(mysql_error()){
                    fun_message('mysql 用户权限不足');
                }
            }
            
            # 定义基础内容.
            $cretime = fun_date('Y 年 m 月 d 日 H:i:s',GET_TIME);
            $sqlver = mysql::get_one('SELECT version() AS version');
            $phpver = phpversion();
            $timezone = GET_TIMEZONE;
            $charset = strtr(GET_CHARSET, array('-'=>''));
            $varsql = mysql::get_one("SHOW VARIABLES like '%max_allowed_packet%'");
            $show_err = mysql_error();
            $max_allowed_packet = $varsql['Value'];
            if(empty($max_allowed_packet) === true)
                $max_allowed_packet = '1024000';
            
            $str = "-- PHPnew SQL Dump
-- version 1.0.0.0
-- http://www.fenanr.com
--
-- 主机: {$_SERVER['HTTP_HOST']}
-- 生成日期: {$cretime}
-- 服务器版本: {$sqlver['version']}
-- PHP 版本: {$phpver}
-- max_allowed_packet: {$max_allowed_packet}

SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";
SET time_zone = \"+00:00\";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES {$charset} */;
-- {$cresql['Create Database']}; ";
            if(IS_POST){
                fun_put_contents($sqlpath, $str, FILE_APPEND | LOCK_EX);
                unset($str);
                $str = '';
            }
            # 先查询出所有表的信息
            $sql = "SHOW TABLE STATUS FROM `$DBNAME`";
            $query = mysql::query($sql);
            $dbinfo_array = array();
            while($row = mysql::fetch_array($query)){
                $dbinfo_array[$row['Name']]['Rows'] = $row['Rows'];
                $dbinfo_array[$row['Name']]['Data_length'] = ceil($row['Data_length'] / $max_allowed_packet);
                $dbinfo_array[$row['Name']]['Rows_limit'] = ceil($row['Rows'] / $dbinfo_array[$row['Name']]['Data_length']);
            }

            # 开始工作
            if(empty($cresql) === false && IS_POST){
                function table_info($page=0,$limit = 0){
                    global $DBNAME,$val;
                    $page = ($page - 1) * $limit;
                    $rows =  mysql::query("SELECT * FROM `$DBNAME`.`$val` LIMIT $page, $limit");
                    $instr = '';
                    $instrarr = array();
                    while ($row = mysql::fetch_array($rows)){
                        if(!$instr){
                            $instr = implode('`,`',array_keys($row));
                            $instr = "INSERT INTO `$val` (`$instr`) VALUES ";
                        }
                        
                        foreach($row AS $key => $vals){
                            $vals = addslashes($vals);
                            $vals = "'{$vals}'";
                            $row[$key] = $vals;
                        }
                        
                        if(empty($row) === false){
                            $tem = implode(',',$row);
                            $instrarr[] = "\n($tem)";
                        }
                    }
                    if($instrarr){
                        $instrarr = implode(',',$instrarr);
                        $instr .= $instrarr.";\n"; 
                    }
                    return $instr;
                }
                # 表的创建.
                foreach($fields_arr AS $val){
                    $tablesql = mysql::get_one("SHOW CREATE TABLE `$DBNAME`.`$val`");
                    $str = "\n\n--\n-- 表的结构 `{$val}`\n--";
                    $tablesql = strtr($tablesql['Create Table'], array('CREATE TABLE'=>'CREATE TABLE IF NOT EXISTS'));
                    $str .= "\n\n".$tablesql.';';
                    fun_put_contents($sqlpath, $str, FILE_APPEND | LOCK_EX);
                    
                     $sql = "SHOW FULL FIELDS FROM `$DBNAME`.`{$val}`";
                    $tableinfo = mysql::get_one($sql);
                    
                    fun_put_contents($sqlpath, "\n\n--\n-- 表的数据 `{$val}`\n--\n\n", FILE_APPEND | LOCK_EX);

                    
                    for($i = 1; $i<=$dbinfo_array[$val]['Data_length']; $i++){
                        $sqldata = table_info($i, $dbinfo_array[$val]['Rows_limit']);
                        
                        if($sqldata)
                            fun_put_contents($sqlpath, $sqldata, FILE_APPEND | LOCK_EX);
                    }
                }
                fun_message($DBNAME.'数据库备份完成');
            }
                
            
            
            # 前台显示出有多少个数据表.
            $sql = "SHOW TABLE STATUS FROM `$DBNAME`";
            $query = mysql::query($sql);
            $err = mysql_error();
            $dbpriv = array();
            $allcount = $indexcount = 0;
            if(empty($err) === true){
                # 能够进到这儿来, 就查询一下是否有其它数据库
                $dbquery = mysql::query("SHOW DATABASES");
                $dbarr = array();
                while($row = mysql::fetch_array($dbquery)){
                    $dbarr[] = $row['Database'];
                }
                
                while($row = mysql::fetch_array($query)){
                    $allcount += $row['Data_length'];
                    $indexcount += $row['Index_length'];
                    
                    $row['safedata'] = 1;
                    if($row['Data_length'] >= 500000000){
                        $row['safedata'] = 0;
                    }
                    
                    $row['Index_length'] = fun_sizecount($row['Index_length']);
                    $row['Data_length'] = fun_sizecount($row['Data_length']);
                    $row['Max_data_length'] = fun_sizecount($row['Max_data_length']);
                    # 直接查出它下面的字段信息.
                    $sql = "SHOW FULL FIELDS FROM `$DBNAME`.`{$row['Name']}`";
                    $queryfields = mysql::query($sql);
                    $e = mysql_error();
                    $subset = array();
                    while($rows = mysql::fetch_array($queryfields)){
                        if(!$rows['Comment'])
                            $rows['Comment'] = '/';
                        if(!$rows['Default'])
                            $rows['Default'] = '/';
                        if(!$rows['Extra'])
                            $rows['Extra'] = '/';    
                            
                        $subset[] = $rows;
                    }
                    
                    $row['fields'] = count($subset);
                    $row['subset'] = $subset;
                    if($row['fields'] === 0)
                        $row['error'] = $e;
                        
                    $dbpriv[] = $row;
                }
            }
            $allcount = fun_sizecount($allcount);
            $indexcount = fun_sizecount($indexcount);
            
            # 读取所有已经备份文件.
            $filearr = array();
            $filearr = glob('./Data/run_log/*.sql');
            foreach($filearr AS $key => $val){
                $vals = $val;
                $val = array();
                $val['ctime'] = fun_date('Y-m-d H:i:s',filemtime($vals));
                $val['size'] = fun_sizecount(filesize($vals));
                $val['name'] = fun_enhtml($vals);
                $val['sqlname'] = trim(substr_replace(basename($val['name']),'',-37),'[]');
                $val['ensqlname'] = urlencode($val['name']);
                $filearr[$key] = $val;
            }
            $filearr = fun_array_sort($filearr,array('size'=>SORT_DESC));
            $include_str = '备份管理';
            $include_file = 'admincp_db_back';
            break;
        case 'resume':
            // TODO: 简历系统管理功能.
            define('STOP_USER', 4);
            
            # 禁用功能
            if($default_get['stop']){
                $uids = $default_get['stop']+0;
                mysql::query("UPDATE DB_resume SET user_power = if(user_power=4,'1','4') WHERE user_id = '$uids' LIMIT 1");
                fun_header();
            }
            
            $resume_arr = array();
            $page = max($default_get['page'] +0,1);
            $re = ($page - 1) * 30;
            $query = mysql::query("SELECT U.user_name AS user_names , `user_power`,R.user_name, R.user_id,`user_cretime`,`user_update`,`user_randmd5` FROM DB_resume AS R LEFT JOIN DB_user AS U ON U.user_id = R.user_id ORDER BY R.user_update DESC LIMIT $re, 30");
            while($row = mysql::fetch_array($query)){
                $row['user_cretime'] = fun_date($row['user_cretime']);
                $row['user_update'] = fun_date($row['user_update']);
                
                # 计算权限在后台显示.
                
                if(is_numeric($row['user_power'])){
                    $t = array('游客访问','本人访问','会员访问','开放访问','禁止访问');
                    $row['user_power'] = $t [$row['user_power']];
                }else if (strlen($row['user_power']) === 32){
                    $row['user_power'] = '凭密码访问';
                }else{
                    $row['user_power'] = '默认';
                }
                $row['link'] = fun_parse_url("./plugin.php?user=resume&sid={$row['user_randmd5']}.html");
                $resume_arr[] = $row;
            }
        
            $include_str = '简历列表';
            $include_file = 'admincp_resume';
            break;
        default:exit('功能块未启用');break;
}

$html['title'] .= ' - '.$include_str;
common_function_template('admincp_iframe');

// TODO: 函数开始.
function temp_get_meun(){
   $temp = array();
   $temp['信息管理'][] = array('name'=>'创建|编辑','link'=>'./index.php?admincp=edit.html','cls'=>'edit');
   $temp['信息管理'][] = array('name'=>'栏目管理','link'=>'./index.php?admincp=cats.html','cls'=>'cats');
   $temp['信息管理'][] = array('name'=>'主题管理','link'=>'./index.php?admincp=enadmin.html','cls'=>'enadmin');
   $temp['信息管理'][] = array('name'=>'回复管理','link'=>'./index.php?admincp=replays.html','cls'=>'replays');
   $temp['信息管理'][] = array('name'=>'附件管理','link'=>'./index.php?admincp=attachments.html','cls'=>'attachments');
   
   $temp['运营工具'][] = array('name'=>'耦合管理','link'=>'./index.php?admincp=allcode.html','cls'=>'allcode');
   $temp['运营工具'][] = array('name'=>'资源管理','link'=>'./index.php?admincp=source.html','cls'=>'source');
   $temp['运营工具'][] = array('name'=>'备份管理','link'=>'./index.php?admincp=db_back.html','cls'=>'db_back');
   
   $temp['用户管理'][] = array('name'=>'用户列表','link'=>'./index.php?admincp=useradmin.html','cls'=>'useradmin');
   //$temp['用户管理'][] = array('name'=>'简历列表','link'=>'./index.php?admincp=resume.html','cls'=>'resume');
   $temp['用户管理'][] = array('name'=>'我的信息','link'=>'./index.php?admincp=useredit.html','cls'=>'useredit');
   
   $temp['常规操作'][] = array('name'=>'系统设置','link'=>'./index.php?admincp=setting.html','cls'=>'setting');
   $temp['常规操作'][] = array('name'=>'友情链接','link'=>'./index.php?admincp=setlink.html','cls'=>'setlink');
   $temp['常规操作'][] = array('name'=>'管理日志','link'=>'./index.php?admincp=cache.html','cls'=>'cache');
   
   $temp['特色功能'][] = array('name'=>'链接管理','link'=>'./index.php?admincp=enlink.html','cls'=>'enlink');
   return $temp;
}

function tem_multi($link_array , $link_str){
    global $default_get;
    $allcount = count($link_array);
    $page = max(1,$default_get['page'] + 0);
    $pagelimit = 30;
    if($allcount >= $pagelimit)
        $page_list = fun_multi($allcount,$pagelimit,$page,$link_str);
    
    $i = 1;
    $re = ($page - 1) * $pagelimit;
    $link_arrays = $link_array;
    $link_array = array();
    foreach($link_arrays AS $key => $val){
        if($i > $re && $i <= ($re + $pagelimit)){
            $link_array[$key] = $val;
        }
        $i ++;
    }
    unset($link_arrays);
    return array('data'=>$link_array, 'page_list'=>$page_list);
}

function cfg_show($varName){
    if($varName === 'CURL'){
        if(function_exists('curl_init')){
            return '<font color="green">Yes</font>';
        }else{
            return '<font color="red">Not</font>';
        }
    }
	switch($result = get_cfg_var($varName)){
		case 0:
			return '<font color="red">Not</font>';
		break;
		case 1:
			return '<font color="green">Yes</font>';
		break;
		default:
			return $result;
		break;
	}
}
function temp_get_headers($url, $format=0) { 
     $headers = array(); 
     $url = parse_url($url); 
     $host = isset($url['host']) ? $url['host'] : ''; 
     $port = isset($url['port']) ? $url['port'] : 80; 
     $path = (isset($url['path']) ? $url['path'] : '/') . (isset($url['query']) ? '?' . $url['query'] : ''); 
     $fp = fsockopen($host, $port, $errno, $errstr, 3); 
     if ($fp){ 
         $hdr = "GET $path HTTP/1.1\r\n"; 
         $hdr .= "Host: $host \r\n"; 
         $hdr .= "Connection: Close\r\n\r\n"; 
         fwrite($fp, $hdr); 
         while (!feof($fp) && $line = trim(fgets($fp, 1024))) 
         { 
             if ($line == "\r\n") break; 
             list($key, $val) = explode(': ', $line, 2); 
             if ($format) 
                 if ($val) $headers[$key] = $val; 
                 else $headers[] = $key; 
             else $headers[] = $line; 
         } 
         fclose($fp); 
         return $headers; 
     } 
     return array(); 
} 
function temp_get_user($user){
    $where = '';
    if(is_numeric($user) === true || empty($user) === true){
        $user += 0;
        $where = "user_id = $user";
    }else{
        $where = "user_name = '$user'";
    }
    $one = mysql::get_one("SELECT `user_id` FROM DB_user WHERE $where LIMIT 1");
    if(empty($one) === false)
        return $one;
    return array();
}
 function temp_dir_list($path = './'){
        static $dir = array();
        $open = opendir($path);
        $size = $index = 0;
        $index = 'index.html Not';
        while($file = readdir($open)){
           if($file === '.' || $file === '..')
                continue;
           if(is_file($path.$file) === true){
                $size += filesize($path.$file);
                if('index.html' === $file || $path === './')
                    $index = 'index.html Ok';
                $dir['file'] += 1;
           }else{
                if(strpos($file,'attachments') === false)
                temp_dir_list($path.$file.'/');
                $dir['dir'] += 1;
           }
        }
        $dir['size'] += $size;
        $size = fun_sizecount($size);
        $dir['data'][] = "[path]: $path [size]: $size [index]: $index \n"; 
        return $dir;
 };