<?php
/*
  # $default_parem, $default_post,$default_get三个数组非常重要.
  code user: tuesday(104979058@qq.com) 2012/10/19 22:58:00
*/

defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
define('SCTIME',3600); // 缓存过期时间,如果是3600就可以省略,

$run_action = fun_enhtml($default_parem[2]);
switch($run_action){
    case 'default':
    // TODO: 默认首页, 无GET参数时.
    $page = max(1, $default_parem[3]+0);
    
    # 首页进行缓存记录.
    $loop_list = cache::read('default_list_'.$page,'default_list.php',SCTIME); 
    if(empty($loop_list) === true){
        $re = ($page - 1) * $index_indexcount;
        $query = mysql::query("SELECT thread_id,thread_state, thread_fid, thread_first, thread_title, thread_message, thread_update, thread_date,thread_attch,thread_view,thread_history,thread_index_img FROM DB_thread WHERE thread_first='0' ORDER BY thread_id DESC LIMIT $re, $index_indexcount");
        
        $loop_list = $attch_id = array();
        while($row = mysql::fetch_array($query)){
            $row['thread_top'] = 0;
            $loop_list[] = $row;
        }
        
        if($page === 1){
            $state = THREAD_EDIT;
            $state2 = THREAD_TOP;
            $query = mysql::query("SELECT thread_id,thread_state, thread_fid, thread_first, thread_title, thread_message, thread_update, thread_date,thread_attch,thread_view,thread_history,thread_index_img FROM DB_thread WHERE thread_state='$state' ORDER BY thread_id ASC LIMIT 2");
            while($row = mysql::fetch_array($query)){
                if($row['thread_update']+ $index_editday*86400 < GET_TIME){
                    $row['thread_id'] += 0;
                    mysql::query("UPDATE DB_thread SET thread_state = '$state2' WHERE thread_id = '{$row['thread_id']}'");
                    continue;
                }
                $row['thread_top'] = 1;
                array_unshift($loop_list,$row); //写入的上数组中.
            }
        }
        $loop_lists = $loop_list;
        #集体循环
        $loop_list = array();
        foreach($loop_lists AS $key => $row){
            if(empty($loop_list[$row['thread_id']]) === false)
                continue;
            $row['thread_view'] = str_pad($row['thread_view'],3,0,STR_PAD_LEFT);
            if($row['thread_view'] >= 999)
                $row['thread_view'] = '＋';
            $row['thread_fidlink'] = fun_parse_url("./index.php?main=cat&{$row[thread_fid]}.html");
            $row['thread_date'] = fun_date($row['thread_date']);
            $row['thread_fid'] = fun_enhtml($cat_array[$row['thread_fid']]);
            if($row['thread_top']){
                $row['thread_message'] = '';
            }else{
                $row['thread_message'] = fun_cutstr($row['thread_message'],600);
                $row['thread_message'] = fun_ubb2html(strip_tags($row['thread_message'],'<br>'));
                $row['thread_message'] = preg_replace('/\[code=(.+)\](.*)\[\/code\]/iseU','temp_code_highlight(\'$2\')',$row['thread_message']);
            }

            if($row['thread_state'])
                $row['thread_state'] = $ico_array[$row['thread_state']];
            
            $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
            $row['thread_title2'] = fun_enhtml($row['thread_title']);
            
            # 勾注功能.
            $var = 'Hook_Index_'.$row['thread_id'];
            $row['hook'] = $$var;
            
            // 去掉所有的附件标识
            $row['thread_message'] = preg_replace("/\[attch\][0-9]*\[\/attch\]/isU",'',$row['thread_message']);
            # 主题高亮.
            $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;";
              }
            }
            if($threads['th_admread'] === '1'){
                $row['thread_message'] = '<span style="color:blue"> * 此主题仅限管理员查看</span>';
            }
            $row['th_sync'] = $threads['th_sync'];
            unset($row['thread_history'],$row['thread_first'],$row['thread_update'],$row['thread_admin'],$row['thread_attch'],$threads);
            # 计算宽度限制
            if(empty($row['thread_index_img']) === false && is_file($row['thread_index_img']) === true){
                $t = getimagesize($row['thread_index_img']);
                $t[0] = min(656,$t[0]);
                $row['path'] = "<img width=\"{$t[0]}\" src=\"{$row['thread_index_img']}\" class=\"gray\" /><br />";
            }
            
            $loop_list[$row['thread_id']] = $row;
            }
            cache::write('default_list_'.$page,'default_list.php',$loop_list);
        }
        #缓存结束
        
        # 支持下一页功能.
        $allcount = cache::read('default_list_count','default_list.php',86400);
        if(!$allcount){
            $allcount = mysql::get_one("SELECT count(thread_id) AS counts FROM DB_thread WHERE thread_first='0'");
            cache::write('default_list_count','default_list.php',$allcount);
        }
        
        # 计算出下一页及上一页链接
        $pagecount = ceil($allcount['counts'] / $index_indexcount);
        $backpage = $nextpage = $page;
        $pagecount > 100 && $pagecount = 100;
        if($page !== 1){
            $backpage = $page - 1;
        }
        if($pagecount > $page){
            $nextpage = $page + 1;
        }
        
        $nextpage = fun_parse_url("./index.php?main=default&{$nextpage}.html");
        $backpage = fun_parse_url("./index.php?main=default&{$backpage}.html");
        $pagestr = str_pad($page,2,'0',STR_PAD_LEFT);
        
        # 最新回复
        $new_replay = cache::read('index_new_replay','index_new_replay.php',86400);
        if(!$new_replay){
            $new_replay = temp_get_replay(); 
            cache::write('index_new_replay','index_new_replay.php',$new_replay);   
        }
        
        
        # 最新注册用户
        $user_list = cache::read('index_user_list','index_user_list.php',86400);
        if(!$user_list){
            $query = mysql::query("SELECT `user_name`,`user_regtime`,`useropenid` FROM DB_user ORDER BY user_id DESC LIMIT 10");
            $user_list = array();
            while($row = mysql::fetch_array($query)) {
                $row['user_name'] = fun_enhtml($row['user_name']);
                $row['img'] = 'feuser';
                if($row['useropenid']){
                    $row['img'] = 'qquser';
                }
                $len = mb_strlen($row['user_name']);
                if($len  <= 24){
                    $row['user_regtime'] = fun_date('Y-m-d',$row['user_regtime']);
                }else{
                    if($len  >= 37)
                      $row['user_name'] = fun_cutstr($row['user_name'],36);
                    $row['user_regtime'] = '';
                }
                unset($row['useropenid']);
                $user_list[] = $row;
            }
            cache::write('index_user_list','index_user_list.php',$user_list);
        }
        
        $rss_url = fun_parse_url("./index.php?main=rss&index.html");
        $url_rss = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{$html['title']}\" href=\"{$rss_url}\" />";
        common_function_template('main_index');
        break;
    case 'cat':
        // TODO: 栏目列表页功能. 
        $page = max(1,$default_parem[4]+0);
        $default_parem[3] += 0;
        $catid = $default_parem[3];
        $cat = $cat_array[$default_parem[3]]['c_name'];
        $tpl = $cat_array[$default_parem[3]]['c_tpl'];
        empty($tpl) === true && $tpl = 'default';
        $state = THREAD_TOP;
        $stateb = THREAD_EDIT;
        $statec = THREAD_HOT;
        $img_attch = $attch_id = $loop_list = array();
        if(empty($cat) == true)
            fun_message('类别信息不存在');
        $all_count = cache::read('cat_list_count','cat_list_count.inc.php',72000);
        if($default_parem[3] && $cat && empty($all_count) === true){
            $query = mysql::query("SELECT count(thread_id) AS counts,thread_fid FROM DB_thread WHERE thread_first='0' GROUP BY thread_fid");
            $all_count = array();
            while($row = mysql::fetch_array($query)){
                $all_count[$row['thread_fid']] = $row['counts'];
            }
            cache::write('cat_list_count','cat_list_count.inc.php',$all_count);
        }
        #为其余两个风格做数据补充
        if($tpl === 'gen' || $tpl === 'show'){
            $re = ($page - 1) * 30;  
            $query = mysql::query("SELECT thread_id,thread_thum, thread_title,thread_message,thread_attch, thread_state, thread_date,thread_view,thread_history, U.user_name FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id =T.thread_uid WHERE thread_fid='{$default_parem[3]}' AND thread_first='0' ORDER BY thread_id DESC LIMIT $re, 30");
            while($row = mysql::fetch_array($query)){
                $row['thread_state_top'] = 0;
                $loop_list[] = $row;
            }
            
        # 置顶信息 第二页不显示
        if($re <= 0 && $tpl === 'show'){
            $query = mysql::query("SELECT thread_id,thread_thum, thread_title, thread_state, thread_date,thread_view,thread_history, U.user_name FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id =T.thread_uid WHERE thread_fid='{$default_parem[3]}' AND thread_state IN ('$state','$stateb') ORDER BY thread_id ASC LIMIT 5"); 
            $top_list = array();
            while($row = mysql::fetch_array($query)){
                #定时清除置顶帖为热贴.
                if(strtotime("+{$cfg_catstop} day",$row['thread_date']) <= GET_TIME){
                    mysql::query("UPDATE DB_thread SET thread_state = '$statec' WHERE thread_id = '{$row['thread_id']}'");
                    continue;
                }
                
                $row['thread_state_top'] = 1;
                $topid = 1;
                array_unshift($loop_list,$row); //写入的上数组中.
            }
        }

        $loop_lists = $loop_list;
        $loop_list = array();
        foreach($loop_lists as $key=>$row){
            if(empty($loop_list[$row['thread_id']]) === false)
                continue;
                # 对有附件的主题进行首页显示, 默认先显示插入到主题的第一张,否则显示
                unset($row['thread_message']);
                
                $row['user_name'] = fun_cutstr($row['user_name'],20,'');
                $row['thread_date'] = fun_date($row['thread_date']);
                $row['thread_title2'] = fun_enhtml($row['thread_title']);
                $row['thread_title'] = fun_cutstr($row['thread_title'],90,'');
                $row['thread_state'] = $ico_array[$row['thread_state']];
                $row['thread_rss'] = fun_parse_url("./index.php?main=rss&read={$row['thread_id']}.html");
                $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
                if($row['thread_view'] > 999)
                    $row['thread_view'] = 999;
                # 主题高亮.
                $row['css'] = '';
                $threads = array();
                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;";
                  }
                }
                $row['path'] = './Data/attachments/attach.jpg';
                if(empty($row['thread_thum']) === false && is_file($row['thread_thum']) === true){
                    $row['path'] = $row['thread_thum'];
                }
                
                $row['th_pay'] = ($threads['th_pay'] += 0); 
                $row['los_pay'] = ($threads['los_pay'] += 0);
                $row['th_url'] = fun_parse_url("./index.php?ajax=jump&{$row['thread_id']}.html");
                unset($threads);
                // los_pay
                if(empty($row['th_pay']) == false){
                    empty($row['los_pay']) === true && $row['los_pay'] = sprintf("%01.2f",$row['th_pay'] * 2);
                }
                
                $loop_list[$row['thread_id']] = $row;
        } 
            
            # 分页
            $cats = urlencode($cat);
            $page_list = fun_multi($all_count[$default_parem[3]],30,$page,fun_parse_url("./index.php?main=cat&{$default_parem[3]}={#1}.html"));
            
            # 取得最新主题
            $new_list = cache::read('cat_right_new','cat_right_new.inc.php');
            if(empty($new_list) === true){
                $query = mysql::query("SELECT thread_id,thread_state, thread_fid, thread_title, thread_view FROM DB_thread WHERE thread_first = '0' ORDER BY thread_id DESC LIMIT 10");
                $new_list = array();
                while($row = mysql::fetch_array($query)){
                    $row['thread_date'] = fun_date($row['thread_date']);
                    $row['thread_title'] = fun_cutstr($row['thread_title'], 28 ,'');
                    $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
                    $new_list[] = $row;
                }
                cache::write('cat_right_new','cat_right_new.inc.php',$new_list);
            }
            $html['title'] = $cat;
            $html['keywords'] = $cat.' '.$html['metac'];
            $html['description'] = $html['generator'] = $cat;
            empty($cat_array[$default_parem[3]]['tags']) === false && $html['description'] = $cat_array[$default_parem[3]]['tags'];
            $rss_url = fun_parse_url("./index.php?main=rss&cats={$default_parem[3]}.html");
            $url_rss = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{$html['title']}\" href=\"{$rss_url}\" />";
            
            common_function_template('main_cat_'.$tpl);
            exit();
        }
        #############################################
        ################风格过滤完成#################
        
        $re = ($page - 1) * 30;  
        $query = mysql::query("SELECT thread_id, thread_title, thread_state, thread_date,thread_view,thread_history, U.user_name FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id =T.thread_uid WHERE thread_fid='{$default_parem[3]}' AND thread_first='0' ORDER BY thread_id DESC LIMIT $re, 30");
        while($row = mysql::fetch_array($query)){
            $row['thread_state_top'] = 0;
            $loop_list[] = $row;
        }
        
        # 置顶信息 第二页不显示
        if($re <= 0){
            $query = mysql::query("SELECT thread_id, thread_title, thread_state, thread_date,thread_view,thread_history, U.user_name FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id =T.thread_uid WHERE thread_fid='{$default_parem[3]}' AND thread_state IN ('$state','$stateb') ORDER BY thread_id ASC LIMIT 5");
            
            $top_list = array();
            while($row = mysql::fetch_array($query)){
                #定时清除置顶帖为热贴.
                if(strtotime("+{$cfg_catstop} day",$row['thread_date']) <= GET_TIME){
                    mysql::query("UPDATE DB_thread SET thread_state = '$statec' WHERE thread_id = '{$row['thread_id']}'");
                    continue;
                }
                $row['thread_state_top'] = 1;
                $topid = 1;
                array_unshift($loop_list,$row); //写入的上数组中.
            }
        }
        
        $loop_lists = $loop_list;
        $loop_list = array();
        foreach($loop_lists as $key=>$row){
            if(empty($loop_list[$row['thread_id']]) === false)
                continue;
            
            $row['user_name'] = fun_cutstr($row['user_name'],20,'');
            $row['thread_date'] = fun_date($row['thread_date']);
            $row['thread_title2'] = fun_enhtml($row['thread_title']);
            $row['thread_state'] = $ico_array[$row['thread_state']];
            $row['thread_rss'] = fun_parse_url("./index.php?main=rss&read={$row['thread_id']}.html");
            $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
            if($row['thread_view'] > 999)
                $row['thread_view'] = 999;
            # 主题高亮.
            $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;";
              }
            }
 
            $loop_list[$row['thread_id']] = $row;
        }
        

        # 分页
        $cats = urlencode($cat);
        $page_list = fun_multi($all_count[$default_parem[3]],30,$page,fun_parse_url("./index.php?main=cat&{$default_parem[3]}={#1}.html"));
        
        # 取得最新主题
        $new_list = cache::read('cat_right_new','cat_right_new.inc.php');
        if(empty($new_list) === true){
            $query = mysql::query("SELECT thread_id,thread_state, thread_fid, thread_title, thread_view FROM DB_thread WHERE thread_first = '0' ORDER BY thread_id DESC LIMIT 10");
            $new_list = array();
            while($row = mysql::fetch_array($query)){
                if($row['thread_view'] <= 9){
                   $row['thread_view'] = str_pad($row['thread_view'],2,0,STR_PAD_LEFT); 
                }else{
                    if($row['thread_view'] >= 99)
                        $row['thread_view'] = 99;
                }
                $row['thread_title'] = fun_cutstr($row['thread_title'],28,'');
                $row['thread_date'] = fun_date($row['thread_date']);
                $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
                $new_list[] = $row;
            }
            cache::write('cat_right_new','cat_right_new.inc.php',$new_list);
        }
        $html['title'] = $cat;
        $html['keywords'] = $cat.' '.$html['metac'];
        $html['description'] = $html['generator'] = $cat;
        empty($cat_array[$default_parem[3]]['tags']) === false && $html['description'] = $cat_array[$default_parem[3]]['tags'];
        $rss_url = fun_parse_url("./index.php?main=rss&cats={$default_parem[3]}.html");
        $url_rss = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{$html['title']}\" href=\"{$rss_url}\" />";
        common_function_template('main_cat_'.$tpl);
        break;
    case 'read':
        // TODO: 主题内容显示功能.
        $read = $default_parem[3] + 0;
        $page = max(1,$default_parem[4]+0);
        $deleid = $thread = array();
        $thread = mysql::get_one("SELECT U.user_admin,U.user_name,thread_uid, thread_id, thread_fid,thread_attch, thread_first,thread_message, thread_title, thread_update, thread_date, thread_ip, thread_admin,thread_state, thread_history,thread_view,thread_replay_count FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id=T.thread_uid WHERE thread_id='$read' LIMIT 1");
        
        $catid = $thread['thread_fid'] + 0;
        $thread['thread_history'] = empty($thread['thread_history']) === false? unserialize($thread['thread_history']):0;
        
        # 一些基础判断. 特别是主题相关的.
        if(empty($thread) === true || empty($thread['thread_first']) === false || $thread['user_admin'] == 2){
            fun_message('主题被屏蔽或者删除');
        }
        
        // 单主题回复限期及禁止回复.
        $no_replay = 0;
        if($thread['thread_history']['th_replay'] === '0' || (empty($thread['thread_history']['th_replay']) === false && GET_TIME > $thread['thread_history']['th_replay'])){
            $no_replay = 1;
        }
        
        # 基础判断.
        if($thread['thread_history']['th_url'])
            $th_url = fun_parse_url("./index.php?ajax=jump&{$read}.html");
        if($thread['thread_history']['th_admread'] === '1' && USER_ADMIN === 0)
            fun_message('主题仅限管理员查看, 请登录管理员账号.');
            
        # 时间段禁止回复.隐藏回复窗.
        $replay_statu = 0;
        $day_h = date('H');
        if(empty($cfg_redate) === false && in_array($day_h,$cfg_redate) === true){
            $replay_statu = 1;
        }

        # 多少天后禁止回复 隐藏回复窗. 与上结合.
        if($replay_statu === 0 && $cfg_replay_time && ($thread['thread_update'] + $cfg_replay_time * 86400) <= GET_TIME){
            $replay_statu = 1;
        }
        
        # 禁止下载权限判断
        $replay_downtime = 0;
        if(empty($cfg_attch_downtime) === false && in_array($day_h,$cfg_attch_downtime) === true){
            $replay_downtime = 1;
        }
        
        # 会员,回复,游客查看识别.
        # 非常严格的限制过程.
        $cfg_attch_look = isset($thread['thread_history']['th_user']) === true?$thread['thread_history']['th_user']+0:$cfg_attch_look;
        # 重点处理1,2, 0放任功能.
        if($cfg_attch_look === 1 && USER_UID){
            $cfg_attch_look = 0;
        }else if($cfg_attch_look === 2){
            if(($thread['thread_uid']+0) === USER_UID){
                $cfg_attch_look = 0;
            }else if(($thread['thread_replay_count']+0) > 0 && $thread['thread_attch'] > 0){
                $seuid = USER_UID;
                $isone = mysql::get_one("SELECT thread_uid FROM DB_thread WHERE thread_first='$read' AND thread_uid='$seuid' LIMIT 1");
                if($isone){
                    $cfg_attch_look = 0;
                }
            }
        }
        # ======================= 判断结束end =======================================
        
        # 变量释放过程.
        $th_keyword = $thread['thread_history']['th_keyword'];
        $th_sync = $thread['thread_history']['th_sync'];
        $th_pay = $thread['thread_history']['th_pay'];
        $los_pay = $thread['thread_history']['los_pay'];
        unset($thread['thread_history']);
        
        $useradmin = 0; // 防止有人调试功能.
        if($thread['thread_date'] && (GET_TIME - $thread['thread_date']) <= 7200){
            $useradmin = USER_ADMIN;
            if(empty($default_parem[4]) === false){
                $syncid = (fun_authcode($default_parem[4],'DECODE')) + 0;
                if($syncid === $read){
                    $useradmin = 1;
                }else{
                    fun_log("同步解密出错: [$syncid]-[{$default_parem[4]}]".URL_SITE."\n\n");
                }
            }else{
                 if($thread['thread_admin'] === '2' && (USER_ADMIN === 0 || $thread['user_name'] !== USER_NAME)){
                    fun_message('主题暂时无法查阅,请稍候再访问.');
                 }
            }
        }
        
        #处理远程图片同步
        if($thread['thread_view'] === '0' && $useradmin &&  $th_sync === '1' && strpos($thread['thread_message'], '[/img]') !== false){
            include_once(DIR_FUNCTION.'function_images.php');
            $thread['thread_message'] = preg_replace('/\[img=\d{1,4}[x|\,]\d{1,4}\]/isU','[img]',$thread['thread_message']);
            preg_match_all('/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/isU',$thread['thread_message'],$reg);
            empty($reg[1]) === true && $reg[1] = array();
            // 处理远程图片列表.
            $get_link = $replay = $attch_sync = array();
            $i = 1;
            foreach($reg[1] AS $key => $val){
                $md5 = md5(trim($reg[0][$key]));
                if(empty($img_arr[$md5]) === true){
                    $get_link[$md5] = $val;
                    $img_arr[$md5] = array(
                        'lostcode' => $reg[0][$key],
                        'url' => $val,
                    );
                    $i ++;
                }
            }
            
            $memory_limit = get_cfg_var('memory_limit') + 0;
            
            if($memory_limit < 4){
                fun_log('memory_limit < 4 内存太低会影响图片同步, 请尽快修复');
            }
            
            set_time_limit(0);
            $getdata = fun_geturl($get_link);

            # 纠正取完数据后的顺序问题
            $newdata = $getdata;
            $getdata = array();
            $allsize = 0;
            foreach($img_arr AS $key => $val){
                if(empty($newdata[$key]) === false){
                    $getdata[$key] = $newdata[$key];
                    $allsize += strlen($newdata[$key]);
                }
            }
            unset($newdata);
            
            fun_log('图片同步开始: 取值项'.count($get_link).'; 结果项:'.count($getdata).'; 总容量:'.fun_sizecount($allsize)."; \n");
            $thread_thum = $thread_index_img = $firt = $file_dir = $img_i = $allsize = $thread_thum_a = 0;
            $width_x = 10;
            foreach($getdata AS $key => $val){
                unset($getdata[$key]);
                if($firt === 0){
                    # 第一步创建目录.
                    $file_dir = './Data/attachments/' . date('Ym') . '/';
        			if(is_dir($file_dir) === false){
        				 mkdir($file_dir, 0777);
                         fun_put_contents($file_dir.'index.html','phpnew blog');
        			}
                    $firt = 1;
                }
                
                #对于1KB图片进行过滤.
                if(empty($val) === true || strlen($val) < 1000){
                        $val = fun_fsockopen($get_link[$key]);
                }
                
                if(strlen($val) < 1000){
                    $val = 0;
                    $replay[$img_arr[$key]['lostcode']] = '';
                    continue;
                }
                
                $img_i ++;
                // 处理文件结构.
                    $extension = 'jpg'; 
                if(stripos($img_arr[$key]['url'],'.gif') !== false){
                    $extension = 'gif';
                }else if(stripos($img_arr[$key]['url'],'.png') !== false){
                    $extension = 'gif';
                }
                
                $times = GET_TIME;
                $file['type'] = fun_mimetype($extension);
                $file_name = md5($key. GET_MICROTIME.rand(1,9999)).'.'.strtolower($extension);
                
                $pathfile = $file_dir.$file_name;
                file_put_contents($pathfile, $val,LOCK_EX);
                
                $aistype  = 1;
                if(is_file($pathfile) === true){ 
                    $size = filesize($pathfile);
                    list($imgwidth, $imgheight, $imgtype, $imgattr) = getimagesize($pathfile);
                    unset($imgheight,$imgtype,$imgattr); 
                    $allsize += $size;
                    
                    # 先选取第一张图片为展示.
                    if($thread_thum_a === 0){
                        $thread_thum_a = $pathfile;
                    }
                    
                    # 计算取值.只要有合适的, 就选取, 656
                    $tewidth = $imgwidth - 656;
                    if( $tewidth < $width_x && $tewidth >= 0){
                        $thread_thum = $pathfile;
                    }
                    $width_x = max(0, $tewidth); // 大出来多少尺寸.
                    
                    
                    mysql::query("INSERT INTO `DB_attachments`(`tid`,`fid`, `aname`, `atype`, `asize`, `amname`, `atime`, `adown`, `temp`, `aistype`) VALUES ('$read','{$thread[thread_fid]}', '{$file_name}', '{$file['type']}', {$size}, '{$file_name}', '$times', '0', '0','$aistype')");
                    $insert_id = mysql::insert_id();
                    $attch_sync[] = $insert_id;
                    $thread['thread_attch'] = 1;
                    $replay[$img_arr[$key]['lostcode']] = "[attch]{$insert_id}[/attch]";
                }else{
                    $replay[$img_arr[$key]['lostcode']] = '';
                }
                
                # 销毁变量.
                unset($val,$pathfile);
            }
            # foreach end
            
            if(empty($replay) === false){
                
                # 处理展示图片
                if($thread_thum === 0)
                    $thread_thum = $thread_thum_a;
                if($thread_thum){
                    $thread_index_img = $thread_thum;
                    $thread_thum = fun_imageresize($thread_thum, 230, 200);
                }
                #更新附件标识
                $thread['thread_message'] = strtr($thread['thread_message'],$replay);
                $thread['thread_message'] = addslashes($thread['thread_message']);
                mysql::query("UPDATE DB_thread SET thread_message = '{$thread['thread_message']}',thread_thum='$thread_thum',thread_attch='1', thread_index_img ='$thread_index_img' WHERE thread_id='$read'");
                if(empty($attch_sync) === false){
                   $attch_sync = implode(',',$attch_sync); 
                   mysql::query("UPDATE `DB_attachments` SET `temp`='1' WHERE `aid` IN ($attch_sync)");
                }
                cache::dele('default_list.php');
            }
            
            # 记录图片采集日志:
            fun_log("图片同步结束: 处理项:".$img_i.'; 替换项:'.count($replay).'; 总容量:'.fun_sizecount($allsize)."; 主题项:$insert_id;\n");
            mysql::query("UPDATE DB_thread SET thread_view = (thread_view + 1),thread_admin='0' WHERE thread_id='$read' LIMIT 1");
            # end ##################################################################################
        }else{
            if($thread['thread_admin'] !== '0'){
                mysql::query("UPDATE DB_thread SET thread_view = (thread_view + 1), thread_admin='0' WHERE thread_id='$read' LIMIT 1");
            }
        }
        
        # 同步中心变量.
        if($syncid){
            exit('sync_ok');
        }
        # 主题变量
        $thread_mess = fun_cutstr($thread['thread_message'],200);
        $thread['thread_title'] = fun_enhtml($thread['thread_title']);
        $thread['thread_strfid'] = $fid = $thread['thread_fid']+0;
        $thread['fidlink'] = fun_parse_url("./index.php?main=cat&{$fid}.html");
        $thread['thread_date_read'] = fun_date('H:i:s',$thread['thread_date']);
        $thread['thread_date'] = fun_date($thread['thread_date']);
        $thread['thread_attch'] = temp_get_attach($thread['thread_attch']);
        $thread['thread_size_attch'] = count($thread['thread_attch']);
        $thread['thread_fid'] = $cat_array[$thread['thread_fid']]['c_name'];
        $thread['link'] = fun_parse_url("./index.php?main=read&{$thread['thread_id']}.html");
        $thread['thread_state'] = $ico_array[$thread['thread_state']];
        $thread['thread_replay_count'] += 0;
        temp_parse_message();
        
        if($thread['thread_replay_count'] > 0){
            # 回复列表处理.
            $page = max(1,$default_parem[4]+0);
            $re = ($page - 1) * 20; 
            $replay_array = array();
            $query = mysql::query("SELECT U.user_id, U.user_logo,U.user_name,U.user_exp,thread_id, thread_fid, thread_first,thread_message, thread_title, thread_update, thread_date, thread_ip, thread_admin FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id=T.thread_uid WHERE T.thread_first='$read' ORDER BY thread_id ASC LIMIT $re,20");
            while($row = mysql::fetch_array($query)){
                $row['deles'] = 0;
                if( (GET_TIME-86400) >= $row['thread_date']){
                    $row['deles'] = 1;
                }
                $row['user_logo'] = fun_getlogo($row['user_id'],$row['user_logo']);
                $row['thread_date'] = fun_date( $row['thread_date']);
                $row['thread_message'] = nl2br($row['thread_message']);
                $row['thread_message'] =  preg_replace('/\[code=(.+)\](.*)\[\/code\]/iseU','temp_code_highlight(\'$2\',\'$1\')',$row['thread_message']);
                $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
                $replay_array[] = $row;
            }
    
            # 实现分页
            $count = mysql::get_one("SELECT count(thread_id) AS counts FROM DB_thread WHERE thread_first='$read'");
            $page_list = fun_multi($count['counts'],20,$page,fun_parse_url("./index.php?main=read&$read={#1}.html")); 
        }
        
        # 访问动作记录
        $cookie_thread_id = fun_getcookie('thread_id');
        if(empty($cookie_thread_id) === true || $cookie_thread_id != $read){
            mysql::query("UPDATE DB_thread SET thread_view = (thread_view + 1) WHERE thread_id='$read' LIMIT 1");
            fun_setcookie('thread_id',$read);
        }
        
        # 取得精华, 推荐, 热贴各十条
        $get_rand = rand(1,4);
        $get_thread = cache::read('get_thread','get_thread.inc.php');
        if(empty($get_thread) === true){
            $get_thread = array();
            $query = mysql::query("SELECT `thread_id`, `thread_title`, `thread_state` FROM `DB_thread` WHERE thread_first='0' AND thread_state BETWEEN 0 AND 4 ORDER BY thread_id DESC LIMIT 100");
            while($row = mysql::fetch_array($query)){
                if(in_array($row['thread_state'],array('2','3','4')) === false)
                    $row['thread_state'] = 0;
                    $row['thread_title'] = fun_enhtml($row['thread_title']);
                    $row['thread_title2'] = $row['thread_title'];
                    $row['thread_title'] = fun_cutstr($row['thread_title'],60,'');
                    $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
                    $get_thread[$row['thread_state']][] = $row;
            }
    
            # 每段都补充为10条.
            if($get_thread){
                $tem_list = $get_thread[0];
                unset($get_thread[0]);
                $no = 0;
                $temp_thread = array();
                for($i = 0; $i<10; $i++){
                    if(!$get_thread[0][$i] && $tem_list[$no]){
                        $temp_thread[0][$i] = $tem_list[$no];
                        $no++;
                    }else if($get_thread[0][$i]){
                        $temp_thread[0][$i] = $get_thread[0][$i];
                    }
                    if(!$get_thread[2][$i] && $tem_list[$no]){
                        $temp_thread[2][$i] = $tem_list[$no];
                        $no++;
                    }if($get_thread[2][$i]){
                        $temp_thread[2][$i] = $get_thread[2][$i];
                    }
                    if(!$get_thread[3][$i] && $tem_list[$no]){
                        $temp_thread[3][$i] = $tem_list[$no];
                        $no++;
                    }if($get_thread[3][$i]){
                        $temp_thread[3][$i] = $get_thread[3][$i];
                    }
                    if(!$get_thread[4][$i] && $tem_list[$no]){
                        $temp_thread[4][$i] = $tem_list[$no];
                        $no++;
                    }if($get_thread[4][$i]){
                        $temp_thread[4][$i] = $get_thread[4][$i];
                    }
                }
                $get_thread = $temp_thread;
                unset($temp_thread);
                cache::write('get_thread','get_thread.inc.php',$get_thread);
            }
        }
        
        # 基本变量及流程即将结束.
        $html['title'] = $thread['thread_title'] .' - '.$thread['thread_fid'];
        $html['keywords'] = $html['description'] = $thread_mess;
        empty($th_keyword) === false && $html['keywords'] = fun_enhtml($th_keyword);
        $rss_url = fun_parse_url("./index.php?main=rss&read={$read}.html");
        $url_rss = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{$html['title']}\" href=\"{$rss_url}\" />";
        common_function_template('main_read');
        break;
    case 'replay':
            // TODO: 接收回复信息功能.
            if(strlen($default_post['message']) < 12){
                exit(json::encode(array('status'=>0,'m'=>'请输入大于12字节内容信息')));
            }
            if(empty($default_post['tid']) === true){
                exit(json::encode(array('status'=>0,'m'=>'系统无法识别的操作')));
            }
            if(empty($user_uid) === true || app_user(true) === false){
                exit(json::encode(array('status'=>0,'m'=>'请登录你的会员账号','url'=>'./index.php?user=login.html')));
            }
            $default_post['tid'] += 0;
            #时间段禁止回复.
            $d = date('H');
            if(empty($cfg_redate) === false && in_array($d,$cfg_redate) === true){
                $tem[0] = str_pad($cfg_redate[0],2,'0',STR_PAD_LEFT);
                $tem[1] = str_pad(end($cfg_redate),2,'0',STR_PAD_LEFT);
                exit(json::encode(array('status'=>0,'m'=>"系统禁止此 {$tem[0]} 至 {$tem[1]} 时间内回复信息")));
            }
            
            $thread = mysql::get_one("SELECT thread_update,thread_first FROM DB_thread WHERE thread_id='{$default_post['tid']}'");
            
            if(empty($thread) === true || empty($thread['thread_first']) === false || $thread['user_admin'] == 2){
                exit(json::encode(array('status'=>0,'m'=>'主题被屏蔽或者删除, 禁止回复!')));
            }
            
            # 多少天后禁止回复
            if($cfg_replay_time && ($thread['thread_update'] + $cfg_replay_time * 86400) <= GET_TIME){
                exit(json::encode(array('status'=>0,'m'=>"主题已经发表超过{$cfg_replay_time}天, 禁止回复!")));
            }
            
            $thread_fid = $default_post['cat'] + 0;
            $thread_title = 0;
            function unbase_code_highlight($mess,$code){$mess = base64_encode($mess);return "[code=$code]{$mess}[/code]";}
            $default_post['message'] = preg_replace('/\[code=(.+)\](.*)\[\/code\]/iseU','unbase_code_highlight(\'$2\',\'$1\')',$default_post['message']);
            $thread_message = strip_tags($default_post['message']);
            $thread_update = $thread_date = GET_TIME;
            $thread_ip = fun_get_ip();
            
            $sql = "INSERT INTO DB_thread(thread_uid,thread_fid, thread_first, thread_title, thread_message, thread_update, thread_date, thread_ip,thread_admin) VALUES ($user_uid,'$thread_fid', '{$default_post['tid']}', '0', '$thread_message', '$thread_update', '$thread_date', '$thread_ip','1')";
            mysql::query($sql);
            $inid = mysql::insert_id();
            #   更新主题的修改时间.
            mysql::query("UPDATE DB_thread SET thread_update = '$thread_update',thread_replay_count = (thread_replay_count+1) WHERE thread_id = '{$default_post['tid']}'");
            
            $user_temp_exp = $user_exp + $main_exp;
            mysql::query("UPDATE DB_user SET user_exp = '$user_temp_exp' WHERE user_id = '$user_uid'"); // $main_exp增加积分
            
            cache::dele('index_new_replay.php'); 
            
            # 返回当前回复的信息
            $userlogo = fun_getlogo($user_uid,$user_logo);
            $thread_date = fun_date($thread_date);
            $thread_message = nl2br($thread_message);
            $thread_message =  preg_replace('/\[code=(.+)\](.*)\[\/code\]/iseU','temp_code_highlight(\'$2\',\'$1\')',$thread_message);
            $returnstr ='<ul class="replay" style="display:none" id="th_'.$inid.'">
            <li class="user_re">
                <img src="'.$userlogo.'" class="user_img" />
                <span class="user_na">'.USER_NAME.'</span>
                <span>积分: '.$user_temp_exp.'</span>
            </li>
            <li class="replay_show">
            <span class="replay_meun">　'.$thread_date.' / <a href="javascript:void(0)" title="'.$inid.'" onclick="replay_dele(this);" class="replay_dele">DEL</a></span>
                <span class="replay_mess">
                '.$thread_message.'<br />
                </span>
            </li>
        </ul>';
        exit(json::encode(array('status'=>1,'m'=>$returnstr,'id'=>'#th_'.$inid)));
        break;
    case 'filing':
        $page = max(1, $default_parem[4]+0);
        $datekey = $default_parem[3];
        $datekeystr = empty($datekey) === false? ' &raquo; <a href="'.GET_URL.'">'.$datekey.'</a>':'';
        # 处理条件
        $where = '';
        if(empty($datekey) === false){
            $c = substr_count($datekey,'-');
            if($c === 1){
                $stime = strtotime($datekey);
                $etime = strtotime('+1 month',$stime);
                $fire_month = date('Y-m',$stime);
            }else{
                $stime = strtotime($datekey);
                $etime = strtotime('+1 day',$stime);
                $fire_month = date('Y-m',$stime);
            }
            $where = "AND thread_date BETWEEN '$stime' AND '$etime'";
        }else{
            $datekey = 0;
        }
        $month_array = cache::read('filing_left_month','filing_left_month.inc.php',604800);
        if(empty($month_array) === true){
            $query = mysql::query("SELECT thread_date FROM DB_thread WHERE thread_first='0' ORDER BY `thread_id` DESC LIMIT 500000");
            $month_array = array();
            $allcount = 0;
            while($row = mysql::fetch_array($query)){
                if(!$row['thread_date'])
                    continue;
                if(count($month_array) >= 36){
                    break;
                }
                # 左侧月份条件
                $row['date'] = fun_date('Y-m-d',$row['thread_date']);
                $month = fun_date('Y-m',$row['thread_date']);
            
                $month_array[$month]['count'] +=1;
                $month_array[$month]['sub'][$row['date']] += 1;
                $allcount += 1;
            }
            foreach($month_array AS $key => $val){
                if($val['count'] > 99999)
                    $val['count'] = '9999+';
                $month_array[$key] = $val;
            }
            
            $month_array['allcount'] = $allcount;
            cache::write('filing_left_month','filing_left_month.inc.php',$month_array);
        }
        # 更快方式取得分页
        if(!$default_parem[3]){
            $count['counts'] = $month_array['allcount'];
        }else if($c === 1){
            $count['counts'] = $month_array[$fire_month]['count'];
        }else{
            $count['counts'] = $month_array[$fire_month]['sub'][$default_parem[3]];
        }
        unset($month_array['allcount']);
        
        // 防止后期的左侧暴高.
        $leftcss = 'overflow: hidden;';
        if(count($month_array) >= 38)
          $leftcss = 'height: 800px; overflow: scroll';
        $re = ($page - 1) * 60;
        
        if($page !== 1){
            $limit = "LIMIT $re,60";
        }else{
            $limit = "LIMIT 60";
        }
       $query = mysql::query("SELECT thread_id,thread_fid,thread_first,thread_date,thread_title,thread_state,thread_attch FROM DB_thread WHERE thread_first = '0' {$where} ORDER BY thread_id DESC $limit");
       $list_array  = array();
       while($row = mysql::fetch_array($query)){
            $row['thread_fid'] = sprintf('[<a href="%1$s">%2$s</a>]', fun_parse_url("./index.php?main=cat&{$row['thread_fid']}.html"),$cat_array[$row['thread_fid']]['c_name']);
            $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
            $d = fun_date('Y-m-d',$row['thread_date']);
            $row['thread_title'] = fun_cutstr($row['thread_title'],90);
            $row['thread_title2'] = fun_enhtml($row['thread_title']);

            if($row['thread_state'])
            $row['thread_state'] = $ico_array[$row['thread_state']];
            $list_array[$d][] = $row;
       }
       
       
       # 分页缓存
       $page_list = fun_multi($count['counts'],60,$page,"./index.php?main=filing&$datekey={#1}.html");
       $html['link'] = fun_parse_url("./index.php?main=filing.html");
       $html['title'] = '主题归档';
       common_function_template('main_filing');
       break;
    case 'rss':
        // TODO: RSS显示功能.
        $where = '';
        $type = $default_parem[3];
        $default_parem[4] += 0;
        if($type === 'cats'){
            $where = "AND thread_fid = '$default_parem[4]' ";
        }
        
        if($type === 'read'){
            $where = "AND thread_id = '$default_parem[4]' ";
        }
        $query = mysql::query("SELECT thread_fid,thread_id,thread_message,thread_date,thread_title,thread_index_img FROM DB_thread WHERE thread_first='0' {$where} ORDER BY thread_id DESC LIMIT 88");
        $date = fun_date('Y-m-d H:i:s');
        $html['title'] = fun_enhtml($html['title']);
        $str = '<?xml version="1.0" encoding="utf-8"?>
        <rss version="2.0">
         <channel>
          <title>'.$html['title'].'</title>
          <link>'.URL_HOST.'</link>
          <description>'.$html['title'].'</description>
          <pubDate>'.$date.'</pubDate>
          <language>zh-CN</language>';
        while($row = mysql::fetch_array($query)){
            if($type !== 'read')
                $row['thread_message'] = fun_cutstr($row['thread_message'],250);
            $row['thread_message'] = nl2br(fun_ubb2html($row['thread_message']));
            $row['thread_date'] = date(DATE_RSS,$row['thread_date']); 
            $row['thread_title'] = fun_enhtml($row['thread_title']);
            $row['link'] = fun_parse_url("./index.php?main=read&{$row['thread_id']}.html");
            $row['link'] = fun_enhtml(URL_HOST.strtr($row['link'],array('./'=>'')));
            if(is_file($row['thread_index_img']) === true){
                $row['thread_index_img'] = fun_enhtml(URL_HOST.strtr($row['thread_index_img'],array('./'=>'')));
                $row['thread_message'] = '<img src="'.$row['thread_index_img'].'" /><br />'.$row['thread_message'];
            }
            $catname = fun_enhtml($cat_array[$row['thread_fid']]['c_name']);
            $str .= "<item>
           <title>{$row['thread_title']}</title>
           <link>{$row[link]}</link>
        	 <category>{$catname}</category>
           <description><![CDATA[{$row['thread_message']}]]></description>
           <pubDate>{$row['thread_date']}</pubDate>
           <guid>{$row['link']}</guid>
          </item>";
        }
        $str .= '</channel>
        </rss>';
        header('Content-type: text/xml; charset=utf-8');
        print($str);
        break;
    default:
        // TODO: 默认跳转至首页.
        fun_header();
        break;
    case 'htaccess':
        // TODO: 检测伪静态是否成功.
        exit('htaccess OK');
        break;
}
##################### END ##########################


// TODO: 函数开始, 所有当页函数均在下列.

// 取得最新回复
function temp_get_replay(){
    $query = mysql::query("SELECT user_name,thread_id, thread_fid, thread_first, thread_title, thread_message, thread_update, thread_date, thread_ip,thread_admin FROM DB_thread AS T LEFT JOIN DB_user AS U ON U.user_id=T.thread_uid WHERE thread_admin = '1' ORDER BY thread_id DESC LIMIT 10");
    $return_array = array();
    while($row = mysql::fetch_array($query)){
        $row['thread_link'] = fun_parse_url("./index.php?main=read&{$row['thread_first']}.html");
        $row['thread_message'] = fun_cutstr(nl2br($row['thread_message']),60);
        $row['thread_date'] = date('Y-m-d H:i:s',$row['thread_date']);
       $return_array[] = $row;
    }
    return $return_array;
}

// 处理主题内容 
function temp_parse_message() {
	global $thread,$deleid, $cfg_attch_look;
    include_once(DIR_CLASS.'Ubb_class.php');
    $ubbcls = new ubb();
    $thread['thread_message'] = $ubbcls->ubb2html($thread['thread_message']);
	$thread['thread_message'] = preg_replace("/\[attch\]([0-9]+)\[\/attch\](<br \/>)*?/iseU", 'temp_attch($1)', $thread['thread_message']);
    
    $i = 0;
	foreach ($thread['thread_attch'] AS $key => $val){
	   if(empty($deleid[$key]) === false){
	       unset($thread['thread_attch'][$key]);
	   }else{
	       if($i === 1 && $cfg_attch_look !== 0 && $val['aistype'] === 1){
	           $thread['thread_message'] .= '';
	       }else{
	           if($cfg_attch_look !== 0 && $val['aistype'] === 1 && strpos($thread['thread_message'],'attach_img') !== false){}else{
	               $thread['thread_message'] .= '<br>' . $val['showdata'];
	           }
               $i = 1;
	       }
	   }
	}
     # 对代码段进行高亮显示.
    $thread['thread_message'] = preg_replace("/[\t]*\[code=(.+)\](.*)\[\/code\](<br \/>)*?/iseU",'temp_code_highlight(\'$2\',\'$1\')',$thread['thread_message']);
}

function temp_code_highlight($mess,$code){
    static $i = 0;
    $mess = base64_decode($mess);
    if($code == 'default'){
        $mess = strtr($mess,array("<br />"=>'','&nbsp;'=>' '));
        $mess = trim($mess);
        $mess = htmlspecialchars_decode($mess);
        $p = 1;
        if($mess && strpos($mess,'<?') === false){
            $mess = "<?php ".$mess;
            $p = 0;
        }
        
        $mess = highlight_string($mess,true);
        if($p === 0)
            $mess = strtr($mess,array('&lt;?php&nbsp;'=>''));
        return $mess;
    }elseif($code == 'video'){
        $i ++;
        #尽最大努力完成对youku视频的兼容.
        if(stripos($mess,'youku.com') !== false || stripos($mess,'.') === false || strpos($mess,'.swf') !== false){
            if(strpos($mess,'youku') === false && strpos($mess,'.') !== false){
                $vids = fun_enhtml($mess);
                $ti = 1;
            }else{
                if(stripos($mess,'.') === false){
                    $mess = trim($mess,'=');
                    $vid = base64_decode($mess);
                    if (preg_match('/[a-z]/isU',$vid)){}else{
                         $vid = fun_enhtml($mess);
                    }
                }else{
                    $mess = strtr($mess,array('sid/'=>'id_','/v'=>'.html'));
                    preg_match('/\/id_(.*)\.html/isU',$mess,$reg); 
                    $vid = $reg[1];
                }
                $vids = fun_enhtml($vid);
            }
            
          if($i !== 1){
             return '<div class="play_list" onclick="playrun(this);" title="'.$vids.'"><img src="./Static/Images/filetype/swf.gif" /> 点击播放视频['.$i.']</div>';
          }
    
            $w = '570';
            $h = '400';
          if($ti === 1){
            return '<div class="play_list" style="width: '.$w.'px" onclick="playrun(this);" title="'.$vids.'"><img src="./Static/Images/filetype/swf.gif" /> 点击播放视频['.$i.']</div><div class="video_div" style="width: '.$w.'px"><embed src="'.$vids.'" allowFullScreen="true" quality="high" width="'.$w.'" height="'.$h.'" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed></div>';
          }else{
          return '<div class="play_list" onclick="playrun(this);" title="'.$vids.'"><img src="./Static/Images/filetype/swf.gif" /> 点击播放视频['.$i.']</div><div class="video_div"><embed src="http://static.youku.com/v1.0.0174/v/swf/loader.swf?VideoIDS='.$vids.'&amp;embedid=&amp;isAutoPlay=true&amp;isShowRelatedVideo=false&amp;embedid=-&amp;showAd=0" quality="high" width="'.$w.'" height="'.$h.'" align="middle" allowScriptAccess="always" allowFullScreen="true" mode="transparent" type="application/x-shockwave-flash" wmode="opaque"></embed></div>';
          }
       }else{
        return '<div id="video_mp3"><embed type="application/x-shockwave-flash" style=" width: 400px; height: 30px;" src="./Static/Source/music_player.swf?url='.urlencode($mess).'&amp;Rwid=360&amp;Autoplay=0&amp;rand='.GET_RAND.'" /></div>';
       }
    }else if($code == 'html'){
        #禁止回复被注入危险.
        return fun_enhtml($mess);
    }
}

// 返回附件, 被处理正则替换调用.
function temp_attch($imgid) {
	global $thread,$deleid,$cfg_attch_look;
    static $i = 0;
	if (empty($thread['thread_attch'][$imgid]) === false) {
		$return_str = $thread['thread_attch'][$imgid]['showdata'];
        $deleid[$imgid] = 1;
	}
    if($i === 1 && $cfg_attch_look !== 0 && $thread['thread_attch'][$imgid]['aistype'] === 1){
        return '';
    }else{
        $i = 1;
        return $return_str;
    }
	
}

// 返回可用附件.
function temp_get_attach($state) {
    global $read;
	if (empty($state) === true) {
	    define('QQ_IMG','');
		return array();
	}
	$return_array = array();
    $i = 0;
	$query = mysql::query("SELECT aid, aname, asize, amname, atime, adown,temp,atag,aistype FROM DB_attachments WHERE tid='$read' ORDER BY aid ASC");
	while ($row = mysql::fetch_array($query) ) {
		$row['path'] = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
        $row['atag'] = nl2br($row['atag']);
        $row['aistype'] += 0;
		// 附件显示调用函数
		$row = temp_parse_attach($row);
		$return_array[$row['aid']] = $row;
        if($i <= 10 && $row['aistype'] === 1)
            $qq_img .= URL_HOST.ltrim($row['path'],'./').'|';
        $i ++;
	}
    
    define('QQ_IMG',rtrim($qq_img,'|'));
    unset($qq_img);
	return $return_array;
}

// 统一组成附件显示模式.
function temp_parse_attach($array) {
    global $img_maxread,$read,$cfg_attch_look;
    static $imgs = 0;
      if( empty($array['atag']) === false){
        $array['atag'] = '<br /><span class="otherspan">'.$array['atag'].'</span>';
      }else{
        $array['atag'] = '';
      }

	if((is_file($array['path']) === false)){
	    $noattch = '附件已经丢失';
		$array['showdata'] = '<div class="notpic">　'.$array['aname'].'　'.$noattch.'</div>';
        return $array;
    };

	$path = pathinfo($array['path']);
	$path['extension'] = fun_enhtml(strtolower($path['extension']));
    # 两种模式的附件显示.
	if (in_array($path['extension'], array('jpg','gif','png')) === true) {
       $imgs += 1;
       if($img_maxread < $imgs){
          $array['showdata'] = '<div class="img_hide" onclick="next_img(this);" title="'.$vid.'"><br /><img src="./Static/Images/filetype/img.png" /> 点击查看图片['.$imgs.']</div>
        '.sprintf('<div style="display: none;" class="attach_img"><img title="'.$array['path'].'" src="./Static/Images/loading.gif" alt="%2$s" title="%2$s" />%4$s</div>', $array['path'], $array['aname'],0,$array['atag']);
       }else{
		  $array['showdata'] = sprintf('<div class="attach_img"><img src="%1$s" alt="%2$s" title="%2$s" />%4$s</div>', $array['path'], $array['aname'],0,$array['atag']);
       }
       
	}elseif (in_array($path['extension'], array('mp3','wma','wav')) === true) {
	    $array['showdata'] = '<div id="video_mp3"><embed type="application/x-shockwave-flash" style=" width: 400px; height: 30px;" src="./Static/Source/music_player.swf?url='.urlencode($array['path']).'&amp;Rwid=320&amp;Autoplay=0&amp;rand='.GET_RAND.'">'.$array['atag'].'</div>';
	}elseif (in_array($path['extension'],array('flv','wmv','mkv','swf','rmvb','avi','rm','mp4'))) {
       static $flvs = 0;
       if($flvs === 0){
            $array['showdata'] = '<script type="text/javascript" src="./Source/Default_data/jwplayer/jwplayer.js"></script>';
       }
        $array['path'] = URL_HOST.trim($array['path'],'./');
        $array['showdata'] .= "<div class=\"jwplayer\" id=\"jwplayer_$flvs\" title=\"{$array['path']}\"></div>";
        $flvs = 1;
    }else {
	    if(in_array($path['extension'],array('doc','xls','docx','xlsx','ppt')))
            $path['extension'] = 'msoffice';
        if(in_array($path['extension'],array('zip','7z')))
            $path['extension'] = 'rar';
        if(in_array($path['extension'],array('srt','sub','ssa','ass')))
            $path['extension'] = 'font';

        $img_path = "./Static/Images/filetype/{$path['extension']}.gif";
        if(is_file($img_path) === false)
            $img_path = "./Static/Images/filetype/unknown.gif";    
        $array['asize'] = fun_sizecount($array['asize']);
        $array['adown'] = str_pad($array['adown'],3,'0', STR_PAD_LEFT);
        $array['adown'] > 9999 && $array['adown'] = 9999;
        
        # 附件下载权限受限.
        global $replay_downtime,$_config;
        $ankey =  $_config['default']['ankey'];
        if($replay_downtime === 1 || $cfg_attch_look > 1){
            if($replay_downtime === 1){
                $array['atag'] .= '<span class="otherspan" style="color:#FF6363">此时段区间附件安全保护, 请稍后再下载!</span>';
            }else{
                $array['atag'] .= '<span class="otherspan" style="color:#FF6363">此附件需要回复后下载, 请参与回复后下载!</span>';
            }
           $ankey = GET_RAND;
        }
        $downlink = "./index.php?ajax=down&{$array['aid']}={$read}&".md5($ankey.$read.$array['aid']).".html";
        
		$array['showdata'] = sprintf('<div class="attach_other"><span class="sourcedata"><img src="'.$img_path.'" /> <a href="'.$downlink.'" title="附件名称:%s'."\n".'下载次数:' . $array['adown'] . '" style="font-weight:bold">%1$s</a> (%3$s) %2$s </span><span class="right_attach" title="下载次数">'.$array['adown'].'</span></div>'."\n",$array['aname'],$array['atag'],$array['asize']);
	}
	return $array;
}