<?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就可以省略,

# 重新定义板块url
// c_id
$cat_array_mobile = array();
foreach($cat_array AS $key => $val){
    $cat_array_mobile[$key] = array(fun_parse_url("./index.php?mobile=index&{$val['c_id']}={$page}.html"),$val['c_name'],$val['c_id']);
}
$indexlink = fun_parse_url('./index.php?mobile=index.html');
unset($cat_array);

$run_action = $default_parem[2];
switch($run_action){
    default:
        // TODO: 移动支持默认首页.
        $page = max(1, $default_parem[4]);
        $catid = $default_parem[3] + 0;
        $index_indexcount = 30;
        
        $where = '';
        if($catid){
            $where = " AND thread_fid = '$catid' ";
        }
        $re = '';
        if($page > 1){
            $re = ($page - 1) * $index_indexcount;
            $re = " $re,";
        }
        
        $query = mysql::query("SELECT thread_id, thread_title,thread_view,thread_history FROM DB_thread WHERE thread_first='0' {$where}ORDER BY thread_id DESC LIMIT{$re} $index_indexcount");
        $loop_list = $attch_id = array();
        while(($row = mysql::fetch_array($query)) !== false){
            $row['thread_top'] = 0;
            $loop_list[] = $row;
        }
        
        if($page === 1){
            $state = THREAD_EDIT;
            $query = mysql::query("SELECT thread_id, thread_title,thread_view,thread_history FROM DB_thread WHERE thread_state='$state' ORDER BY thread_id ASC LIMIT 5");
            while(($row = mysql::fetch_array($query)) !== false){
                $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'] = 999;
            
            $row['thread_link'] = fun_parse_url("./index.php?mobile=read&{$row['thread_id']}.html");
            
            # 主题高亮.
            $row['css'] = '';
            if(empty($row['thread_history']) === false){
              $threads = unserialize($row['thread_history']);
              if(empty($threads['th_color']) === false){
                $threads['th_color'] = fun_enhtml($threads['th_color']);
                $row['css'] = "color: {$threads['th_color']};";
              }
              if(empty($threads['th_weight']) === false){
                $row['css'] .= "font-weight: bolder;";
              }
            }
            $loop_list[$row['thread_id']] = $row;
        }
        
        # 分页处理
        $count = mysql::get_one("SELECT count(thread_id) AS counts FROM DB_thread WHERE thread_first='0' {$where}");
        
        $backpage = $page;
        if($page > 1)
            $backpage = $page - 1;
        $nextpage = $page + 1;
        $pagecount = ceil($count['counts'] / $index_indexcount);
        if($page >= $pagecount){
            $nextpage -= 1; 
        }
        $pagestr = '<a href="./index.php?mobile=index&'.$catid.'='.$backpage.'.html">上一页</a> - <a href="./index.php?mobile=index&'.$catid.'='.$nextpage.'.html">下一页</a>';
        common_function_template('mobile_index');
        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_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");

        if(empty($thread) === true || empty($thread['thread_first']) === false || $thread['user_admin'] == 2){
            fun_message('主题被屏蔽或者删除');
        }
        # 一些基础判断. 特别是主题相关的.
        $thread['thread_history'] = empty($thread['thread_history']) === false? unserialize($thread['thread_history']):0;
        if(empty($thread['thread_history']['th_user']) === false){
            if(!USER_UID)
                $attch['attch_look'] = 1;
        }else if($thread['thread_history']['th_user'] === '0'){
                $attch['attch_look'] = 0;
        }
        $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_admread'] === '1' && USER_ADMIN === 0)
            fun_message('主题仅限管理员查看, 请登录网站账号.');
        # end
        
        $useradmin = USER_ADMIN;
        if(empty($default_parem[4]) === false){
            $syncid = fun_authcode($default_parem[4],'DECODE') + 0;
            if($syncid === $read){
                $useradmin = 1;
            }
        }else{
             if($thread['thread_admin'] === '2' && (USER_ADMIN === 0 || $thread['user_name'] !== USER_NAME)){
                fun_message('主题暂时无法查阅,请稍候再访问.');
             }
        }
        
        # 主题变量
        $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)) !== false){
                $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);
        }
        
        #时间段禁止回复.提示在前台
        $replay_statu = 0;
        if(empty($cfg_redate) === false && in_array(date('H'),$cfg_redate) === true){
            $replay_statu = 1;
        }
        
        # 多少天后禁止回复 $cfg_replay_time
        if($replay_statu === 0 && $cfg_replay_time && ($thread['thread_update'] + $cfg_replay_time * 86400) <= GET_TIME){
            $replay_statu = 1;
        }

        $html['title'] = $thread['thread_title'] .' - '.$thread['thread_fid'];
        $html['keywords'] = $html['description'] = $thread_mess;
        empty($thread['thread_history']['th_keyword']) === false && $html['keywords'] = fun_enhtml($thread['thread_history']['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('mobile_read');
        break;
}

// 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)) !== false){
        $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,$attch,$deleid;
    include_once(DIR_CLASS.'Ubb_class.php');
    $ubbcls = new ubb();
    $thread['thread_message'] = $ubbcls->ubb2html($thread['thread_message']);
    if($attch['attch_look'] === 0){
    	$thread['thread_message'] = preg_replace("/\[attch\]([0-9]+)\[\/attch\](<br \/>)*?/iseU", 'temp_attch($1)', $thread['thread_message']);
    	foreach ($thread['thread_attch'] AS $key => $val){
    	   if(empty($deleid[$key]) === false){
    	       unset($thread['thread_attch'][$key]);
    	   }else{
    	       $thread['thread_message'] .= '<br>' . $val['showdata'];
    	   }
    	}
    }else{
        unset($thread['thread_attch']);
    }
     # 对代码段进行高亮显示.
    $thread['thread_message'] = preg_replace('/\[code=(.+)\](.*)\[\/code\](<br \/>)*?/iseU','temp_code_highlight(\'$2\',\'$1\')',$thread['thread_message']);
}

function temp_code_highlight($mess,$code){
    static $i = 0;
    global $row;
    $mess = base64_decode($mess);
    if($code == 'default'){
        $mess = strtr($mess,array("<br />"=>'','&nbsp;'=>' '));
        $mess = trim($mess);
        $mess = htmlspecialchars_decode($mess);
        if(strpos($mess,'<?') === false)
            $mess = "<?php ".$mess;
            
        $mess = highlight_string($mess,true);
        $mess = strtr($mess,array('&lt;?php&nbsp;</span>'=>'</span>'));
        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);
            }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';
          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;
	if (empty($thread['thread_attch'][$imgid]) === false) {
		$return_str = $thread['thread_attch'][$imgid]['showdata'];
        $deleid[$imgid] = 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)) !== false ) {
		$row['path'] = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
        $row['atag'] = nl2br($row['atag']);
        
		// 附件显示调用函数
		$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;
    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){
	    $array['path'] = strtr($array['path'],array('./Data/attachments/'=>'附件/'));
		$array['showdata'] = '<div class="notpic">　'.$array['path'].'　附件已经丢失</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.'"><img src="./Static/Images/filetype/img.png" /> 点击查看图片['.$imgs.']</div>
        '.sprintf('<img style="display: none;" class="attach_img" title="'.$array['path'].'" src="./Static/Images/loading.gif" alt="%2$s" title="%2$s" />%4$s<br />', $array['path'], $array['aname'],0,$array['atag']);
       }else{
		  $array['showdata'] = sprintf('<img class="attach_img" src="%1$s" alt="%2$s" title="%2$s" />%4$s<br />', $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>';
	}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';
        if(in_array($path['extension'],array('flv','wav','mkv','rm','rmvb','avi')))
            $path['extension'] = 'flv'; 
        
        $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['showdata'] = sprintf('<span class="attach_other"><img src="'.$img_path.'" /> <a href="./index.php?ajax=down&' . $array['aid'] . '.html" title="附件名称:%s'."\n".'下载次数:' . $array['adown'] . '" style="font-weight:bold">%1$s</a> (%3$s) %2$s</span>'."\n",$array['aname'],$array['atag'],$array['asize']);
	}
	return $array;
}