<?php
namespace Action;
class Api extends HYBBS{
    public function __construct(){
        parent::__construct();
    }
    
    //获取楼主评论
    
    //排行榜
    public function phb(){
$type=X('get.type');
  if ($type == 'gold'){
            $list = S('user')->select('*',[
                'gold[!]'=>0,
                'ORDER'=>['gold'=>'DESC'],
                'LIMIT'=> [0, 20]
            ]);
        foreach($list as &$v) {	
        
        unset ($v['pass']);

        $v['avatar']=WWW.$this->avatar($v['uid'])['a'];
        }
	exit(json_encode(array(
		    '列表' => $list,
		    )));
        }elseif ($type == 'thread'){
            $list = S('user')->select('*',[
                'threads[!]'=>0,
                'ORDER'=>['threads'=>'DESC'],
                'LIMIT'=> [0, 10]
            ]);
        foreach($list as &$v) {	
        unset ($v['pass']);
        $v['avatar']=WWW.$this->avatar($v['uid'])['a'];
        }
	exit(json_encode(array(
		    '列表' => $list,
		    )));
    }
  }

 
    //招募老用户发送邮箱
    
    public function zmlyh(){
    $x=1; 
    $User = M("User");
    while($x<=3000) {
         
    $array=$User->read($x);
    echo $array['email']."<br>";    
    
    
    $x++;
    } 
    
    }
    //领取芥末2
    public function lqbc(){
    if(!IS_LOGIN){
    $this->json(['error'=>false,'info'=>'请登录后操作!']);
    }

   $User = M("User");
   //获取用户金币
   $goId="1314";
    $filename = "./lqjm2/".NOW_UID.".txt";
    if(file_exists($filename)){
    
    echo '你已经领取过补偿奖励啦';
    } else {
    $myfile = fopen($filename, "w") or die("Unable to open file!");
    $txt = "B";
    fwrite($myfile, $txt);
    
    fclose($myfile);
    $User->update_int(NOW_UID,'gold','+',$goId);
    echo '领取成功，已到账啦';
    M("Chat")->sys_send(NOW_UID,"尊敬的用户你好，您的补偿奖励1314已到账，请注意查收 i");
    }
    }

        //邮箱获取用户名
    public function zhyhm(){
    $email = X('get.email');
    $User = M("User");
    //通过用户名获取用户数据
    $json=$User->email_read($email);
    $fh=$json['user'];
    $this->json(['error'=>true,'info'=>$fh]);
    }

    //自助领取补偿奖励

    //清理数据缓存，提升运行效率
    public function cache_data(){
     if(is_file(TMP_PATH.'log.php'))
     unlink(TMP_PATH.'log.php');
       
    }
    //禁言用户登录与禁止发言【查询状态】
    public function ajax_user_switch(){
        if(!IS_LOGIN){
    $this->json(['error'=>false,'info'=>'请登录后操作!']);
    }
    if(NOW_GID!="1"){
	
    return $this->json(array('error'=>false,'info'=>'您没有权限'));
	}
  
            $type = X('post.type');
            $uid = X('post.uid');

            $User = M('User');

            if($type == 'login'){
                $state = $User->get_row($uid,'ban_login') == 0 ? 1 : 0; //交换状态
                
                $User->update(['ban_login'=>$state],['uid'=>$uid]);
                $this->json(['error'=>true,'info'=>'success','state'=>$state]);
            }else if($type == 'post'){
                $state = $User->get_row($uid,'ban_post') == 0 ? 1 : 0;
                $User->update(['ban_post'=>$state],['uid'=>$uid]);
                $this->json(['error'=>true,'info'=>'success','state'=>$state]);
            }else if($type == 'cxzt'){
            
            $this->json(['ban_login'=> $User->get_row($uid,'ban_login') ,'ban_post'=> $User->get_row($uid,'ban_post')]);
            
            }
        
        $this->json(['error'=>false,'info'=>'参数丢失']);
    }
    //显示打赏用户列表
    
    public function ds(){
    $gold= X('get.gold');
    $tid = X('get.tid');
	 //$avatar = get_avatar($uid);
    $file_path = "fold/".$tid."/";
$contents= "{".NOW_USER."}[".WWW.$this->avatar(NOW_UID)['a']."](".$gold.")";

    if(!file_exists($file_path)){

     mkdir($file_path);

     $myfile=fopen($file_path."gold.txt", 'w');

$myfile = fopen($file_path."gold.txt", "r") or die("Unable to open file!");
fclose($myfile);

$str =file_get_contents($file_path."gold.txt");
$myf = fopen($file_path."gold.txt", "w") or die("Unable to open file!");

$txt2= $str.$contents."\n";

echo $txt2;
fwrite($myf, $txt2);
fclose($myf);

}else{

$myfile = fopen($file_path."gold.txt", "r") or die("Unable to open file!");
fclose($myfile);

$str =file_get_contents($file_path."gold.txt");
$myf = fopen($file_path."gold.txt", "w") or die("Unable to open file!");

$txt2= $str.$contents."\n";

echo $txt2;
fwrite($myf, $txt2);
fclose($myf);
}
   
    }
	//兑换用户组
	public function dhyh(){
	if(!IS_LOGIN){
    $this->json(['error'=>false,'info'=>'请登录后操作!']);
    }
   $User = M("User");
   //获取用户金币
   $goId="99999";
   $uid=NOW_UID;
   $wdjm=$User->get_gold($uid);

     if($uid!= NOW_UID){
     return $this->json(array('error'=>false,'info'=>'请登录自己的账号哦'));
     }
       if(NOW_GID=="5"||NOW_GID=="1"){
	//兑换用户组代码
    return $this->json(array('error'=>false,'info'=>'你已经兑换过了，或者你所在用户组不支持兑换'));
	}
 
            	
  if($wdjm<$goId){
   return $this->json(array('error'=>false,'info'=>'你的芥末不足'));
  }  
            
    $fhsj=$User->set_gid($uid,"5");
	
   if($fhsj){
	$User->update_int(NOW_UID,'gold','-',$goId);
	M("Chat")->sys_send($uid,"您兑换的会员已经到账[扣除芥末:".$goId."］");
	return $this->json(array('error'=>true,'info'=>'兑换成功啦'));
	}else{
    return $this->json(array('error'=>false,'info'=>'兑换失败，请稍候再试'));
   }
   }
    
    // 首页
    public function index(){
        $pageid	= intval(X('get.pageid')) 	or $pageid=1;
		$type 	= X('get.type') 			or $type='New';
		
		if($type != 'New' && $type != 'Btime')
			$type='';
		$this->v("type",strtolower($type));
		$Thread = M("Thread");
		$desc = ['tid' => 'DESC'];
		if($type == 'Btime')
			$desc = ['btime'=>'DESC'];

		$thread_list = $this->CacheObj->get("index_index_".$type.'_'.$pageid);

		//获取主题列表
		if(empty($thread_list) || DEBUG){
			$thread_list = $Thread->get_thread_list($pageid,$this->conf['homelist'],$desc);
			$Thread->format($thread_list);
			foreach ($thread_list as $key => $value) {
				if($value['top'] == 2)
					unset($thread_list[$key]);
			}
			$this->CacheObj->set("index_index_".$type.'_'.$pageid,$thread_list);
		}
        foreach($thread_list as &$v){
            if(!empty($v['img'])){
                $v['image'] = array_filter($v['image']);
            }
        }
		//获取置顶缓存
		$top_data=$this->CacheObj->get("top_data_2");
		if(empty($top_data) || DEBUG){
			//全局置顶
	        $top_data = $Thread->get_top_thread();
	        //格式数据显示
	        $Thread->format($top_data);
	        //写入缓存
			$this->CacheObj->set("top_data_2",$top_data);
		}

		$count = $this->_count['thread'];
		$count = (!$count)?1:$count;
        $page_count = ($count % $this->conf['homelist'] != 0)?(intval($count/$this->conf['homelist'])+1) : intval($count/$this->conf['homelist']);
        $data = [
            'thread_list'   => $thread_list,
            'top_data'      => $top_data,
            'count'         => $count,
            'pageid'        => $pageid,
            'page_count'    => $page_count
        ];
		return $this->json($data);
    }
    // 论坛分类
    public function forum(){
        $forunlist = [];
        $fgid = X('get.fgid');
        $lanmu = S('forum_group')->select('*');
        if(!empty($lanmu)){
            $Fourm = S('forum');
            $forunlist = $Fourm->select('*');
            foreach($forunlist as &$v){
                if(is_file(INDEX_PATH."upload/forum{$v['id']}.png")){
                    $v['icon'] = WWW."upload/forum{$v['id']}.png";
                }else{
                    $v['icon'] = WWW."upload/de.png";
                }
                if(!empty($v['bg_img'])){
                    $v['bg_img'] = WWW.$v['bg_img'];
                }
            }
        }
        return $this->json([
            'count'=>['jinri'=>$this->_count['day_thread'],'quanbu'=>$this->_count['thread'],'users'=>$this->_count['user']],
            'lanmu'=>$lanmu,
            'forumlist'=>$forunlist
        ]);
    }
    // 帖子详情
    public function article(){
        $pageid=intval(X('get.pageid') ? X('get.pageid') : 1) or $pageid=1;
        $tid = intval(X('get.tid'));

        //{hook a_thread_empty_2}
        $Thread = M("Thread");
        $User   = M("User");

        //获取文章数据
        $thread_data = $this->CacheObj->get('thread_data_'.$tid);
        if(empty($thread_data) || DEBUG){
            //{hook a_thread_empty_cache_1}
            $thread_data = $Thread->read($tid);
            if(empty($thread_data))
                return $this->app_json("不存在该主题");
            //获取文章作者用户名以及头像
            $thread_data['user']=$User->uid_to_user($thread_data['uid']);
            
            $thread_data['avatar']['a']=WWW.$this->avatar($thread_data['uid'])['a'];
            $thread_data['avatar']['b']=WWW.$this->avatar($thread_data['uid'])['b'];
            $thread_data['avatar']['c']=WWW.$this->avatar($thread_data['uid'])['c'];
            $this->CacheObj->set('thread_data_'.$tid,$thread_data);
            //{hook a_thread_empty_cache_2}
        }

        //权限判断 
        if(!L("Forum")->is_comp($thread_data['fid'],NOW_GID,'vthread',$this->_forum[$thread_data['fid']]['json']))
            return $this->app_json("你没有权限访问这个帖子");

        //{hook a_thread_empty_3}
        

        //添加网站描述
        $this->conf['description'] = filter_html($thread_data['summary']);
        if($thread_data['hide'] || $thread_data['gold']){
            $this->conf['description'] = '内容需要回复 或 付费 才可浏览.';
        }

        //{hook a_thread_empty_4}
        $Post = S("Post");
        

        //处理隐藏帖子
        $thread_data['show'] = true;
        if($thread_data['hide']){
            if(!IS_LOGIN)
                $thread_data['show'] = false;
            else{
                //判断用户是否回复过
                if($Thread->is_user_post(NOW_UID,$tid))
                    $thread_data['show'] = true;
                else
                    $thread_data['show'] = false;
            }
        }
        $thread_data['ban_zu'] = is_forumg($this->_forum,NOW_UID,$thread_data['fid']) ;
        //{hook a_thread_empty_44}
        $thread_data['gold_show'] = true;
        if($thread_data['gold']){
            if(!IS_LOGIN)
                $thread_data['gold_show'] = false;
            else{
                if(S("Threadgold")->has(['AND'=>['uid'=>NOW_UID,'tid'=>$tid]]) || NOW_UID == $thread_data['uid'])
                    $thread_data['gold_show'] = true;
                else
                    $thread_data['gold_show'] = false;
            }
        }
        //{hook a_thread_empty_55}
        //版主 与 管理员 直接显示隐藏主题 不需要付费
        if(is_forumg($this->_forum,NOW_UID,$thread_data['fid']) || NOW_GID == C("ADMIN_GROUP")){
            $thread_data['gold_show'] = true;
            $thread_data['show'] = true;
        }
        //当前用户组 拥有 不花金币特权 直接显示
        $UsergroupLib = L("Usergroup");
        if($UsergroupLib->read(NOW_GID,'nogold',$this->_usergroup)){
            $thread_data['gold_show'] = true;
        }
        //{hook a_thread_empty_5}
        
        //获取文章评论列表
        
        $order=$order_a='ASC';
        if(X("get.order")=='desc')
            $order = $order_a = 'DESC';
        
        $PostList = $this->CacheObj->get("post_list_{$tid}_{$order_a}_{$pageid}");

        if((empty($PostList) || DEBUG) && $thread_data['posts'] != 0){
            //{hook a_thread_empty_cache_5}
            $post_list_limit = $this->conf['postlist'];
            
            if($pageid == 1){
                $post_list_size = (($pageid-1) * ($this->conf['postlist']+1));
                $post_list_limit++;
                
            }else{
                $post_list_size = (($pageid-1) * $this->conf['postlist'])+1;
            }
            if(X("get.order")=='lou'){
$parameter=['tid'=>$tid,'uid'=>$thread_data['uid']];
}else{
$parameter=['tid'=>$tid];
}
            $PostList = $Post->select('*',[
            'AND'=>$parameter,
                "ORDER" => ['pid'=>$order],
                "LIMIT" => [ $post_list_size , $post_list_limit],
            ]);
            //评论列表实例化
            $i = 0;
            if(!empty($PostList) && is_array($PostList)){
                $User->auto_add_user($PostList);
                foreach ($PostList as $key => &$v) {
                    $v['atime_str']=humandate($v['atime']);
                    $v['key'] = (($pageid-1)*10) + (++$i);
                    $v['avatar']['a']=WWW.$this->avatar($v['uid'])['a'];
                    $v['avatar']['b']=WWW.$this->avatar($v['uid'])['b'];
                    $v['avatar']['c']=WWW.$this->avatar($v['uid'])['c'];
                    $this->CacheObj->set('post_data_'.$v['pid'],$v);
                    if($v['isthread']==1)
                        unset($PostList[$key]);

                    
                }
            }else{
                $PostList = array();
            }
            
            $this->CacheObj->set("post_list_{$tid}_{$order_a}_{$pageid}",$PostList);
            //{hook a_thread_empty_cache_6}
        }
        /*1.5修复PID*/
        if(!$thread_data['pid']){
            $pid = $thread_data['pid'] = $Post->find('pid',['AND'=>['tid'=>$tid,'isthread'=>1]]);
            $Thread->update(['pid'=>$pid],['tid'=>$tid]);
        }
        
        if(!$PostList)
            $PostList = array();

        //获取文章内容
        $PostData = M('Data')->get_post_data($thread_data['pid']);
        if(empty($PostData))
            return $this->app_json("文章内容没有找到");
            

        //{hook a_thread_empty_6}

        //附件处理
        $File = M("File");
        $Fileinfo = S("Fileinfo");
        $Filelist = $Fileinfo->select("*",['tid'=>$tid]);
        unset($v);
        //用户是否回复过帖子
        $is_post = false;
        if(IS_LOGIN){
            $is_post = $Thread->is_user_post(NOW_UID,$tid);

            //管理员 直接显示 或者版主 
            if(NOW_GID == C("ADMIN_GROUP") || is_forumg($this->_forum,NOW_UID,$thread_data['fid']))
                $is_post = true;
        }
        //{hook a_thread_empty_66}


        
        foreach ($Filelist as $key => &$v) {

            //获取附件信息
            $File_Data = $File->read($v['fileid']);
            if(empty($File_Data)){
                unset($Filelist[$key]);
                continue;
            }
            $v['show'] = true;
            if($v['hide']){//隐藏附件
                if(!$is_post) //如果用户没有回复过
                    $v['show'] = false;

            } 
            $v['size'] = $File_Data['filesize'];
            $v['name'] = $File_Data['filename'];

        }
        //{hook a_thread_empty_77}
        //附件处理结束

        //增加主题点击数
        //if(NOW_UID != $thread_data['uid'])
            $Thread->update_int($tid,'views');

        $count = $thread_data['posts'];
        $count = (!$count)?1:$count;
        $page_count = ($count % $this->conf['postlist'] != 0)?(intval($count/$this->conf['postlist'])+1) : intval($count/$this->conf['postlist']);
        //{hook a_thread_empty_v}

        return $this->app_json('sucess',true,[
            'filelist'      => $Filelist,
            'post_data'     => $PostData,
            'pageid'        => $pageid,
            'page_count'    => $page_count,
            'thread_data'   => $thread_data,
            'PostList'      => $PostList,
        ]);
    }
    

    // 发布帖子
    public function thread_add(){
        if(!IS_LOGIN){
			return $this->app_json('请登录后再操作');
        }
        //{hook a_post_index_1}
		if($this->_user['ban_post']){
			return $this->app_json('您的账号已被禁言!');
		}
        if(IS_GET){ //显示发表主题模板
			//{hook a_post_index_2}
          
			//{hook a_post_index_3}
            
    		$this->display('post_index');
        }elseif(IS_POST){ //POST发表主题
			//{hook a_post_index_4}
			$UsergroupLib = L("Usergroup");

            if(!$UsergroupLib->read(NOW_GID,'thread',$this->_usergroup))
                return $this->app_json('你当前所在用户组无法发表主题!');


			//获取提交数据
            $forum = X("post.forum",'-1');
            $title = trim(X("post.title"));
            $title = htmlspecialchars($title);
            $tgold = intval(X("post.tgold"));
            $thide = intval(X("post.thide"));
            


            //{hook a_post_index_44}
            if(!$UsergroupLib->read(NOW_GID,'thide',$this->_usergroup)){
                if($thide)
                    return $this->app_json('你所在用户组无法隐藏帖子!');
            	$thide = 0;
            }
            if(!$UsergroupLib->read(NOW_GID,'tgold',$this->_usergroup)){
                if($tgold)
                    return $this->app_json('你所在用户组无法设置金币付费帖子!');
            	$tgold = 0;
            }
            //{hook a_post_index_55}

            //去除泰文音标
			$title = preg_replace( '/\p{Thai}/u' , '' , $title );
			$this->title=$title;

            $content = X('post.content');
            if (get_magic_quotes_gpc())
  				$content = stripslashes($content);
            
			if(NOW_GID != C("ADMIN_GROUP")){
				$Kses =L("Kses");
        		$content = $Kses->Parse($content);
			}
            $content=preg_replace( '/\p{Thai}/u' , '' , $content );

            //{hook a_post_index_5}
			$tmp = str_replace('&nbsp;','',$content);
			$tmp = trim(strip_tags($tmp,'<img><iframe><embed><video><audio>'));
            if(empty($tmp))
                return $this->app_json('内容不能为空!');

			//{hook a_post_index_6}
            if(mb_strlen($title) < $this->conf['titlemin'])
                return $this->app_json('标题长度不能小于'.$this->conf['titlemin'].'个字符');
            if(mb_strlen($title) > $this->conf['titlesize'])
                return $this->app_json('标题长度不能大于'.$this->conf['titlesize'].'个字符');
			if($forum < 0 ){
                return $this->app_json('请选择一个分类');
			}
			//{hook a_post_index_7}
			//用户组在分类下的权限判断
			if(!isset($this->_forum[$forum])){
                if(empty($this->_forum[$forum]['id']))
                    return $this->app_json('不存在该分类');
			}
			//{hook a_post_index_8}
            if(!L("Forum")->is_comp($forum,NOW_GID,'thread',$this->_forum[$forum]['json']))
                return $this->app_json('你没有权限在该板块发表帖子');

          	
          	//去除图片自定义高度
			$content = preg_replace('/(<img.*?)((height)=[\'"]+[0-9]+[\'"]+)/is','$1', $content);
			//{hook a_post_index_9}
            //获取所有图片地址
			$pattern="/\<img.*?src\=\"(.*?)\"[^>]*>/i";
			preg_match_all($pattern,$content,$match);
			$img = '';
			$sz=0;
			$img_all=[];
			if(isset($match[1][0])){
				foreach ($match[1] as $v) {
					if(substr_count($v,'data:image/') || substr_count($v,';base64') || strpos($v,'/emoji/') !== FALSE || empty($v)){
						continue;
					}
					$img_all[]=$v;
					if($sz++<$this->conf['post_image_size']){
						$img.=$v;
						$img.=",";
					}
				}
			}
			
			
			
		
			
			//发送消息 摘要
			$this->content = mb_substr(trim(filter_html($content)), 0,$this->conf['summary_size']);

			//{hook a_post_index_10}
			
			
			//主题数据
            $Thread = S("Thread");
            $Thread->insert(array(
                'fid'=>$forum,
                'uid'=>NOW_UID,
                'title'=>$title,
                'summary'=>mb_substr(trim(filter_html($content)), 0,$this->conf['summary_size']),
				'atime'	=>NOW_TIME,
				'etime'	=>NOW_TIME,
				'btime'	=>NOW_TIME,
				'img'	=>'',
				'img_count'	=>$sz,
				'hide'	=>$thide?1:0,
				'gold'	=>$tgold,
            ));
            $tid=0;
            $this->tid = $tid = $Thread->id();
            //{hook a_post_index_100}
            
            //@用户
			$this->ante_type = 'thread';
			if($UsergroupLib->read(NOW_GID,'mess',$this->_usergroup))
				$content = $this->ante($content); //@ 用户函数



			//处理临时文件
			$UserTmpUploadPath 	= 	GetUserTmpUploadPath(NOW_UID);
			$tmp_file_expression= "/src=\"(.*?)\"/i";
			preg_match_all($tmp_file_expression,$content,$matchsrc);
			$SrcFileList=[];
			if(isset($matchsrc[1][0])){
				$SrcFileList=$matchsrc[1];
			}
			//{hook a_post_index_101}
			$MoveFileList = [];
			if(!empty($SrcFileList)){
				$StorageThreadDir 		=	GetStorageThreadDir($tid);
				foreach ($SrcFileList as $v) {
					$TmpFilePath = realpath(INDEX_PATH . str_replace(WWW,'',$v));
					$TmpFilePath = str_replace("\\",'/',$TmpFilePath);
					if(strpos($TmpFilePath,$UserTmpUploadPath) !== false){//确定为临时文件
						$NewFilePath = str_replace($UserTmpUploadPath,$StorageThreadDir,$TmpFilePath);
						
						//移动临时文件到正式目录
						if(move_file($TmpFilePath, $NewFilePath)){ //移动成功
							$MoveFileList[] = $NewFilePath;
						}

					}

				}
				
				//替换临时文件路径为正式文件路径
				$content = str_replace($UserTmpUploadPath,$StorageThreadDir,$content);
				$img 	 = str_replace($UserTmpUploadPath,$StorageThreadDir,$img);
			}
			
			//{hook a_post_index_102}
            

            //主题帖子数据
            $Post = S("Post");
            $Post->insert(array(
				'tid'	=> $tid,
				'fid'	=>$forum,
				'uid'	=> NOW_UID,
				'isthread'=> 1,
				'content' => $content,
				'atime'	  => NOW_TIME
            ));
            $pid = $Post->id();

            if(!empty($MoveFileList)){
            	$File=M('File');
            	foreach ($MoveFileList as $v) {
					$FileInfo = pathinfo($v);
					$FileName = $FileInfo['filename'];
					$File->update([
						'tid'	=> $tid,
						'pid'	=> $pid,
					],[
						'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
					]);
	            }
            }
            

            //{hook a_post_index_11}

            $files=0;
            //是否有权限上传附件
            if($UsergroupLib->read(NOW_GID,'uploadfile',$this->_usergroup)){

	            //处理附件
	            $fileid 	= X("post.fileid");
	            $filegold 	= X("post.filegold");
	            $filemess 	= X("post.filemess");
	            $filehide 	= X("post.filehide");
	            //{hook a_post_index_12}

	            if(!empty($fileid)){
	            	//{hook a_post_index_13}
	            	$fileid_arr 	= explode("||",$fileid);
	            	$filegold_arr 	= explode("||",$filegold);
	            	$filemess_arr 	= explode("||",$filemess);
	            	$filehide_arr 	= explode("||",$filehide);

	            	if(count($fileid_arr)){
	            		//{hook a_post_index_14}

	            		$File = M("File");
	            		$Fileinfo = S("Fileinfo");
	            		$MoveFileList = [];
	            		foreach ($fileid_arr as $key => $v) {
	            			//{hook a_post_index_15}
	            			$v=intval($v);
	            			if(empty($v))
	            			{
	            				
	            				continue;
	            			}
	            			//判断附件ID 是否属于 发帖者
	            			if($File->is_comp($v,NOW_UID)){
	            				$files++;
	            				$Fileinfo->insert(array(
	            					'fileid'	=>	$v,
	            					'tid'		=>	$tid,
	            					'uid'		=>	NOW_UID,
	            					'gold'		=>	isset($filegold_arr[$key]) ? intval($filegold_arr[$key]) : 0,
	            					'hide'		=>	isset($filehide_arr[$key]) ? intval($filehide_arr[$key]) : 0,
	            					'mess'		=>	isset($filemess_arr[$key]) ? filter_html($filemess_arr[$key]) : '',
	            				));
	            				//{hook a_post_index_151}
	            				$FileMd5Name 	= $File->get_row($v,'md5name');
	            				$FileTmpPath 	= INDEX_PATH . $UserTmpUploadPath . $FileMd5Name;
								$StorageThreadFileDir = GetStorageThreadFileDir($tid);
	            				
	            				if(move_file($FileTmpPath, INDEX_PATH . $StorageThreadFileDir . $FileMd5Name)){
	            					$MoveFileList[] = INDEX_PATH . $StorageThreadFileDir . $FileMd5Name;
	            					$FileInfo = pathinfo($FileMd5Name);
									$FileName = $FileInfo['filename'];
		            				$File->update([
										'tid'	=> $tid,
										'pid'	=> $pid,
									],[
										'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
									]);
	            				}
	            				//{hook a_post_index_152}
	            			}
	            			//{hook a_post_index_153}
	            		}
	            		//{hook a_post_index_16}
	            	}
	            }//处理附件结束

            }
            $Thread->update(['pid'=>$pid,'img'=>$img,'files'=>$files],['tid'=>$tid]);
            



			$User = M("User");
			//用户增加 主题数
			$User->update_int(NOW_UID,'threads','+');

			//用户增加 金钱
			$User->update_int(NOW_UID,'gold','+',$this->conf['gold_thread']);
			//用户增加 积分
			$User->update_int(NOW_UID,'credits','+',$this->conf['credits_thread']);
			//{hook a_post_index_18}
			if($this->conf['gold_thread'] != 0 || $this->conf['credits_thread'] != 0){
				S("Log")->insert(array(
					'uid'=>NOW_UID,
					'gold'=>$this->conf['gold_thread'],
					'credits'=>$this->conf['credits_thread'],
					'content'=>'发表文章 文章ID['.$tid.']',
					'atime'=>NOW_TIME
				));
			}

			//分类板块 帖子数量++
			M("Forum")->update_int($forum);
			//{hook a_post_index_19}
			//更新分类缓存
			$this->_forum[$forum]['threads']++;
			$this->CacheObj->forum = $this->_forum;
			//更新统计缓存
			$this->_count['thread']++;
			$this->_count['day_thread']++;
			$this->CacheObj->bbs_count = $this->_count;

			$this->_user['threads']++;

			//删除第一页缓存
			$this->CacheObj->rm("index_index_New_1");
			$this->CacheObj->rm("index_index_Btime_1");

			$this->CacheObj->rm("index_index_{$forum}_1_Btime");
			$this->CacheObj->rm("index_index_{$forum}_1_New");
			
			//{hook a_post_index_20}

			//用户组升级检测
			M('Usergroup')->check_up(NOW_UID);

			//删除用户当前临时文件夹
			deldir($UserTmpUploadPath,false,true);

            //{hook a_post_index_v}
            return $this->app_json('发表成功',true,['tid'=>$tid]);

        }

    }
    // 编辑帖子
    public function thread_edit(){
        if(!IS_LOGIN){
			return $this->app_json('请登录后再操作');
        }
        //{hook a_post_edit_1}
		if(IS_POST){
			//{hook a_post_edit_2}
			$pid = intval(X("post.id"));
			$content = X('post.content');
			if (get_magic_quotes_gpc())
  				$content = stripslashes($content);
			
			if(NOW_GID != C("ADMIN_GROUP")){
				$Kses 	 = L("Kses");
        		$content = $Kses->Parse($content);
			}

			//$content = preg_replace('/(<img.*?)((width)=[\'"]+[0-9]+[\'"]+)/is','$1', $content);
			$content = preg_replace('/(<img.*?)((height)=[\'"]+[0-9]+[\'"]+)/is','$1', $content);
			$content = preg_replace( '/\p{Thai}/u' , '' , $content );
			$tmp = str_replace('&nbsp;','',$content);
			$tmp = trim(strip_tags($tmp,'<img><iframe><embed><video><audio>'));
            if(empty($tmp))
                return $this->app_json('内容不能为空');
			//{hook a_post_edit_3}
			$Post = M("Post");
			$post_data = $Post->read($pid);
            if(empty($post_data))
                return $this->app_json('评论不存在');
        	//{hook a_post_edit_33}
			//评论数据不存在 或者 评论不属于当前登陆者 或者 登陆者不是管理员
			if(
				
				$post_data['uid'] != NOW_UID && //编辑者不属于帖子作者
				NOW_GID != C("ADMIN_GROUP") &&  //不属于管理员
				!is_forumg($this->_forum,NOW_UID,$post_data['fid']) //不是版主
            )
                return $this->app_json('太坏了,你居然想修改别人帖子');

			$isthread 	= $post_data['isthread'];
			$tid 		= $post_data['tid'];
			//{hook a_post_edit_34}
			//修改主题 评论是主题内容
			if($isthread){
				//{hook a_post_edit_35}
				$fid = intval(X("post.fid"));
				$title = trim(X("post.title"));
				$title = htmlspecialchars($title);
				$title = preg_replace( '/\p{Thai}/u' , '' , $title );
                if(mb_strlen($title) < $this->conf['titlemin'])
                    return $this->app_json('标题长度不能小于'.$this->conf['titlemin'].'个字符');
                if(mb_strlen($title) > $this->conf['titlesize'])
                    return $this->app_json('标题长度不能大于'.$this->conf['titlesize'].'个字符');
				
				if($fid < 0 ){
                    return $this->app_json('请选择一个分类,板块');
				}
				//{hook a_post_edit_36}
	            if(!isset($this->_forum[$fid])){
                    if(empty($this->_forum[$fid]['id']))
                        return $this->app_json('不存在该分类');
				}
                if(!L("Forum")->is_comp($fid,NOW_GID,'thread',$this->_forum[$fid]['json']))
                    return $this->app_json('你没有权限在该板块发表帖子');

				$tgold = intval(X("post.tgold"));
            	$thide = intval(X("post.thide"));
            	$UsergroupLib = L("Usergroup");
            	$User = M('User');
            	if(!$UsergroupLib->read(NOW_GID,'thide',$this->_usergroup)){
	            	$thide = 0;
	            }
	            if(!$UsergroupLib->read(NOW_GID,'tgold',$this->_usergroup)){
	            	$tgold = 0;
	            }
	            //{hook a_post_edit_37}

	            //获取所有图片地址
				$pattern="/\<img.*?src\=\"(.*?)\"[^>]*>/i";
				preg_match_all($pattern,$content,$match);
				$img = '';
				$sz=0;
				$img_all=[];
				if(isset($match[1][0])){
					foreach ($match[1] as $v) {
						if(substr_count($v,'data:image/')  || substr_count($v,';base64') || strpos($v,'/emoji/') !== FALSE || empty($v))
							continue;
						$img_all[]=$v;
						if($sz++<$this->conf['post_image_size']){
							$img.=$v;
							$img.=",";
						}
					}
				}

				
				
				//{hook a_post_edit_371}
				//处理临时文件
				$UserTmpUploadPath 	= GetUserTmpUploadPath(NOW_UID);
				$tmp_file_expression= "/src=\"(.*?)\"/i";
				preg_match_all($tmp_file_expression,$content,$matchsrc);
				$SrcFileList=[];
				if(isset($matchsrc[1][0])){
					$SrcFileList=$matchsrc[1];
				}
				//{hook a_post_edit_372}
				$MoveFileList = [];
				if(!empty($SrcFileList)){
					$StorageThreadDir 		=	GetStorageThreadDir($tid);
					foreach ($SrcFileList as $v) {
						$TmpFilePath = realpath(INDEX_PATH . str_replace(WWW,'',$v));
						$TmpFilePath = str_replace("\\",'/',$TmpFilePath);
						if(strpos($TmpFilePath,$UserTmpUploadPath) !== false){//确定为临时文件
							$NewFilePath = str_replace($UserTmpUploadPath,$StorageThreadDir,$TmpFilePath);
							//移动临时文件到正式目录
							if(move_file($TmpFilePath, $NewFilePath)){
								$MoveFileList[] = $NewFilePath;
							}

						}
					}
					//替换临时文件路径为正式文件路径
					$content = str_replace($UserTmpUploadPath,$StorageThreadDir,$content);
					$img 	 = str_replace($UserTmpUploadPath,$StorageThreadDir,$img);
				}
				//{hook a_post_edit_373}
				//更新文件使用帖子
				$File=M('File');
				if(!empty($MoveFileList)){
	            	foreach ($MoveFileList as $v) {
						$FileInfo = pathinfo($v);
						$FileName = $FileInfo['filename'];
						$File->update([
							'tid'	=> $tid,
							'pid'	=> $pid,
						],[
							'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
						]);
		            }
	            }
	            //{hook a_post_edit_374}
				//处理不使用的旧文件
				$StorageThreadDir = GetStorageThreadDir($tid,false);
				if(is_dir($StorageThreadDir)){
					$dh = opendir(INDEX_PATH . $StorageThreadDir);

					while ($filename = readdir($dh)) {
						$fullpath = INDEX_PATH . $StorageThreadDir . $filename;
						if ($filename != "." && $filename != ".." && !is_dir($fullpath)) {
							$IsDel = true;
							foreach ($SrcFileList as $v) {
								if(strpos($v,$filename) !== false){ //正在使用
									$IsDel = false;
									break;
								}
							}
							if($IsDel){ //删除不使用的文件
								delete_file($fullpath);
								$FileInfo = pathinfo($fullpath);
								$FileName = $FileInfo['filename'];
								$File->delete(['md5'=>$FileName]);
							}
						}
					}
				}

				//{hook a_post_edit_370}

            	//编辑主题数据
				$Thread = S("Thread");
				$Thread->update(array(
					'fid'		=>	$fid,
					'title'		=>	$title,
					'hide'		=>	$thide?1:0,
					'summary'	=>	mb_substr(trim(filter_html($content)), 0,$this->conf['summary_size']),
					'gold'		=>	$tgold,
					'img'		=>	$img,
					'img_count'	=>	$sz,
					'etime'		=>	NOW_TIME,
					'euid'		=>	NOW_UID
					),[
					'tid'		=>	$tid
				]);
				$this->CacheObj->rm('thread_data_'.$tid);
            	$this->CacheObj->rm('post_data_'.$post_data['pid']);
				//{hook a_post_edit_38}

				//判断是否有上传附件权限
				if($UsergroupLib->read(NOW_GID,'uploadfile',$this->_usergroup)){
					//{hook a_post_edit_39}
					//编辑附件
		            $fileid 	= X("post.fileid");
		            $filegold 	= X("post.filegold");
		            $filemess 	= X("post.filemess");
		            $filehide 	= X("post.filehide");
		            
		            $Fileinfo = S("Fileinfo");
		            $Filegold = S('Filegold');
		            //删除附件文件路径列表
		            $DelFileList=[];
		            //{hook a_post_edit_391}
		            if(!empty($fileid)){
		            	//{hook a_post_edit_40}

		            	$fileid_arr 	= explode("||",$fileid);
		            	$filegold_arr 	= explode("||",$filegold);
		            	$filemess_arr 	= explode("||",$filemess);
		            	$filehide_arr 	= explode("||",$filehide);

		            	if(count($fileid_arr)){
		            		//{hook a_post_edit_41}

		            		$FileinfoList = $Fileinfo->select('*',['tid'=>$tid]);
		            		if(empty($FileinfoList)) $FileinfoList=[];
		            		
		            		$tmp_arr=[];
		            		foreach($FileinfoList as $key => $v){
		            			$tmp_arr[$v['fileid']]=[
		            				'tid'	=>	$v['tid'],
		            				'uid'	=>	$v['uid'],
		            				'gold'	=>	$v['gold'],
		            				'hide'	=>	$v['hide'],
		            				'downs'	=>	$v['downs'],
		            				'mess'	=>	$v['mess'],
		            				//是否被删除
		            				'is_del'	=> true
		            			];
		            		}
		            		//{hook a_post_edit_411}

	            			foreach ($fileid_arr as $key => $fileid_v) {
		            			$fileid_v=intval($fileid_v);
		            			if(empty($fileid_v)) continue;
		            			//判断文件是否属于文章作者 跳过管理员 版主
		            			if($File->is_comp($fileid_v,$post_data['uid']) || NOW_GID == C('ADMIN_GROUP') || is_forumg($this->_forum,NOW_UID,$post_data['fid'])){
		            				//{hook a_post_edit_412}
		            				$tmp_arr[$fileid_v]=[
		            					'tid'	=>	$tid,
		            					'uid'	=>	$post_data['uid'],
		            					'gold'	=>	isset($filegold_arr[$key]) ? intval($filegold_arr[$key]) : 0,
		            					'hide'	=>	isset($filehide_arr[$key]) ? intval($filehide_arr[$key]) : 0,
		            					'downs'	=>	isset($tmp_arr[$fileid_v]) ? $tmp_arr[$fileid_v]['downs'] : 0,
		            					'mess'	=>	isset($filemess_arr[$key]) ?  filter_html($filemess_arr[$key]) : '',
		            					//是否被删除
		            					'is_del'	=>	false
		            				];
		            				
		            			}

		            		}
		            		$i = 0;
		            		//{hook a_post_edit_413}
		            		$MoveFileList = [];
		            		foreach($tmp_arr as $key => $v){
		            			//{hook a_post_edit_4131}
		            			if($v['is_del']){//删除附件
		            				//{hook a_post_edit_414}
		            				$Fileinfo->delete(['fileid'=>$key]);
		            				$Filegold->delete(['fileid'=>$key]);
		            				$FileData = $File->read($key,['uid','md5name','filesize']);
		            				if(!empty($FileData)){
		            					//删除数据记录
		            					$File->delete(['id'=>$key]);

		            					//更新用户上传字节
		            					$User->update([
		            						'file_size[-]'=>$FileData['filesize']
		            					],[
		            						'uid'=>$FileData['uid']
		            					]);
		            					//{hook a_post_edit_4141}
		            					//文件路劲
		            					$FilePath = INDEX_PATH . 'upload/userfile/' . $FileData['uid'] . '/' . $FileData['md5name'];
		            					if(is_file($FilePath)){
		            						unlink($FilePath);
		            					}
		            					$DelFileList[]='upload/userfile/' . $FileData['uid'] . '/' . $FileData['md5name'];
		            					//删除附件 兼容新版本
		            					$FilePath = INDEX_PATH . GetStorageThreadFileDir($tid,false) . $FileData['md5name'];
		            					if(is_file($FilePath)){
		            						unlink($FilePath);
		            					}
		            					$DelFileList[]=GetStorageThreadFileDir($tid,false) . $FileData['md5name'];
		            					//{hook a_post_edit_4142}

		            				}
		            			}else{ //更新或插入新附件
		            				//{hook a_post_edit_415}
		            				$i++;
		            				if($Fileinfo->has(['fileid'=>$key])){ //存在旧附件
		            					$Fileinfo->update([
		            						'tid'		=>	$v['tid'],
		            						'gold'		=>	$v['gold'],
		            						'hide'		=>	$v['hide'],
		            						'downs'		=>	$v['downs'],
		            						'mess'		=>	$v['mess']
		            					],[
		            						'fileid'	=>	$key
		            					]);
		            				}else{ //插入新附件
		            					$Fileinfo->insert([
		            						'fileid'	=>	$key,
		            						'tid'		=>	$v['tid'],
		            						'uid'		=>	$v['uid'],
		            						'gold'		=>	$v['gold'],
		            						'hide'		=>	$v['hide'],
		            						'downs'		=>	$v['downs'],
		            						'mess'		=>	$v['mess']
		            					]);
		            					//{hook a_post_edit_416}
		            					$FileMd5Name 	= $File->get_row($key,'md5name');
			            				$FileTmpPath 	= INDEX_PATH . $UserTmpUploadPath . $FileMd5Name;
			            				
			            				//{hook a_post_edit_417}
			            				$StorageThreadFileDir = GetStorageThreadFileDir($tid);
			            				if(move_file($FileTmpPath, INDEX_PATH . $StorageThreadFileDir . $FileMd5Name)){
			            					$MoveFileList[] = INDEX_PATH . $StorageThreadFileDir . $FileMd5Name;
				            				$FileInfo = pathinfo($FileMd5Name);
											$FileName = $FileInfo['filename'];
				            				$File->update([
												'tid'	=> $tid,
												'pid'	=> $pid,
											],[
												'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
											]);
										}
										//{hook a_post_edit_418}
		            				}
		            			}
		            			//{hook a_post_edit_419}
		            		}
		            		
		            		//{hook a_post_edit_43}
		            		$Thread->update(['files'=>$i],['tid'=>$tid]); //更新主题附件数量
		            	}
		            }else{ //清空附件
		            	//{hook a_post_edit_431}
		            	$FileinfoList = $Fileinfo->select('*',['tid'=>$tid]);
		            	if(empty($FileinfoList)) $FileinfoList=[];

		            	foreach($FileinfoList as $v){
		            		//{hook a_post_edit_432}
		            		$Fileinfo->delete(['fileid'=>$v['fileid']]);
		            		$Filegold->delete(['fileid'=>$v['fileid']]);
            				$FileData = $File->read($v['fileid'],['uid','md5name','filesize']);
            				if(!empty($FileData)){
            					//删除数据记录
            					$File->delete(['id'=>$v['fileid']]);

            					//更新用户上传字节
            					$User->update([
            						'file_size[-]'=>$FileData['filesize']
            					],[
            						'uid'=>$FileData['uid']
            					]);
            					//{hook a_post_edit_433}
            					//文件路劲
            					$FilePath = INDEX_PATH . 'upload/userfile/' . $FileData['uid'] . '/' . $FileData['md5name'];
            					if(is_file($FilePath)){
            						unlink($FilePath);
            					}
            					$DelFileList[]='upload/userfile/' . $FileData['uid'] . '/' . $FileData['md5name'];
            					//删除附件 兼容新版本
            					$FilePath = INDEX_PATH . GetStorageThreadFileDir($tid,false) . $FileData['md5name'];
            					if(is_file($FilePath)){
            						unlink($FilePath);
            					}
            					$DelFileList[]=GetStorageThreadFileDir($tid,false) . $FileData['md5name'];
            					//{hook a_post_edit_434}

            				}
		            	}

	            		//{hook a_post_edit_435}
	            		$Thread->update(['files'=>0],['tid'=>$tid]); //更新主题附件数量

	            	}//结束附件相关
	            	//{hook a_post_edit_381}
				}//结束判断附件权限
				//{hook a_post_edit_382}
			}//修改主题结束
			else{ //编辑帖子不是主题
				//{hook a_post_edit_436}
				$thread_data_posts = S("Thread")->find('posts',['tid'=>$post_data['tid']]);

				$pattern="/\<img.*?src\=\"(.*?)\"[^>]*>/i";
				preg_match_all($pattern,$content,$match);
				$img_all=[];
				if(isset($match[1][0])){
					foreach ($match[1] as $v) {
						if(substr_count($v,'data:image/') || substr_count($v,';base64') || strpos($v,'/emoji/') !== FALSE || empty($v)){
							continue;
						}
						$img_all[]=$v;
					}
				}
				//{hook a_post_edit_437}

				//处理临时文件
				$UserTmpUploadPath 	= 	GetUserTmpUploadPath(NOW_UID);
				$tmp_file_expression= "/src=\"(.*?)\"/i";
				preg_match_all($tmp_file_expression,$content,$matchsrc);
				$SrcFileList=[];
				if(isset($matchsrc[1][0])){
					$SrcFileList=$matchsrc[1];
				}
				//{hook a_post_edit_438}
				$MoveFileList = [];
				if(!empty($SrcFileList)){
					$StoragePostDir 		=	GetStoragePostDir($tid,$pid);
					foreach ($SrcFileList as $v) {
						$TmpFilePath = realpath(INDEX_PATH . str_replace(WWW,'',$v));
						$TmpFilePath = str_replace("\\",'/',$TmpFilePath);
						if(strpos($TmpFilePath,$UserTmpUploadPath) !== false){//确定为临时文件
							$NewFilePath = str_replace($UserTmpUploadPath,$StoragePostDir,$TmpFilePath);
							//移动临时文件到正式目录
							if(move_file($TmpFilePath, $NewFilePath)){
								$MoveFileList[] = $NewFilePath;
							}
						}
					}
					//替换临时文件路径为正式文件路径
					$content = str_replace($UserTmpUploadPath,$StoragePostDir,$content);
				}

				//{hook a_post_edit_439}
				$File=M('File');
				if(!empty($MoveFileList)){
	            	foreach ($MoveFileList as $v) {
						$FileInfo = pathinfo($v);
						$FileName = $FileInfo['filename'];
						$File->update([
							'tid'	=> $tid,
							'pid'	=> $pid,
						],[
							'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
						]);
		            }
	            }

	            //{hook a_post_edit_461}

				//处理不使用的旧文件
				$StoragePostDir = GetStoragePostDir($tid,$pid,false);
				if(is_dir($StoragePostDir)){
					$dh = opendir(INDEX_PATH . $StoragePostDir);
					while ($filename = readdir($dh)) {
						$fullpath = INDEX_PATH . $StoragePostDir . $filename;
						if ($filename != "." && $filename != ".." && !is_dir($fullpath)) {
							//{hook a_post_edit_462}
							$IsDel = true;
							foreach ($SrcFileList as $v) {
								if(strpos($v,$filename) !== false){ //正在使用
									$IsDel = false;
									break;
								}
							}
							//{hook a_post_edit_463}
							if($IsDel){
								delete_file($fullpath);
								$FileInfo = pathinfo($fullpath);
								$FileName = $FileInfo['filename'];
								$File->delete(['md5'=>$FileName]);
							}
						}
					}
				}
				//{hook a_post_edit_464}


				$count = intval(($thread_data_posts /  $this->conf['postlist']) + 1)+1;
		        for ($i=0; $i < $count; $i++) {
		            $this->CacheObj->rm("post_list_{$post_data['tid']}_DESC_{$i}");
		            $this->CacheObj->rm("post_list_{$post_data['tid']}_ASC_{$i}");
		        }
		        $this->CacheObj->rm('post_data_'.$post_data['pid']);
			}
			//{hook a_post_edit_4}
			//修改评论内容
			$Post->update([
				'content'	=>	$content,
				'etime'		=>	NOW_TIME,
				'euid'		=>	NOW_UID,
			],[
				'pid'		=>	$pid
			]);

            return $this->app_json('修改成功',true);
		} //End Post
    }
    // 编辑帖子拉取数据
    public function thread_editpull(){
        if(!IS_LOGIN){
			return $this->app_json('请登录后再操作');
        }
        //编辑器帖子
		$pid = intval(X("id"));
		$Post = M("Post");

		$data = $Post->read($pid);

		//{hook a_post_edit_66}
		if(empty($data))
			return $this->app_json('评论不存在');
		//不是帖子作者 并且 不是管理员 并且不是版主
		if(
			NOW_UID != $data['uid'] && 
			NOW_GID != C("ADMIN_GROUP") && 
			!is_forumg($this->_forum,NOW_UID,$data['fid'])
		)
			return $this->app_json('太坏了,你居然想修改别人帖子 E= 2');
		//{hook a_post_edit_6}
		//获取帖子数据
		
        $file_list = [];
		//属于主题帖子
		if($data['isthread']){
			//{hook a_post_edit_77}
			$thread_data = M("Thread")->read($data['tid']);
			$this->v('thread_data',$thread_data);


			$Fileinfo = S("Fileinfo");
	
			$file_list = $Fileinfo->select("*",array(
				'tid'=>$data['tid'],
				'ORDER' => ['fileid' => 'DESC'],
			));
			//{hook a_post_edit_88}
			if(!empty($file_list)){
				$File = M("File");
				foreach ($file_list as &$v) {
					$v['filename']=$File->get_name($v['fileid']);
				}

			}
			$this->v("file_list",$file_list);
		}
		
		//{hook a_post_edit_7}
        return $this->app_json('success',true,['pid'=>$pid,'data'=>$data,'filename'=>$file_list]);

    }
    //发表评论
	public function Post(){
        if(!IS_LOGIN){
			return $this->app_json('请登录后再操作');
        }
		//{hook a_post_post_1}
		if(!IS_POST)
			return;
		if($this->_user['ban_post']){
            return $this->app_json('您的账号已被禁言');
		}

		$UsergroupLib = L("Usergroup");
		//用户组权限判断
        if(!$UsergroupLib->read(NOW_GID,'post',$this->_usergroup))
            return $this->app_json('你当前所在用户组无法发表评论');

		//{hook a_post_post_2}
		$tid= intval(X("post.id"));
        if(empty($tid))
            return $this->app_json('文章ID不能为空');
        if(!isset($_POST['content']))
            return $this->app_json('内容不能为空');
		//{hook a_post_post_3}
		$content = X('post.content');
		if (get_magic_quotes_gpc())
  			$content = stripslashes($content);
		
		if(NOW_GID != C("ADMIN_GROUP")){
			$Kses =L("Kses");
        	$content = $Kses->Parse($content);
		}
		$content = preg_replace('/(<img.*?)((height)=[\'"]+[0-9]+[\'"]+)/is','$1', $content);
		$pattern="/\<img.*?src\=\"(.*?)\"[^>]*>/i";
		preg_match_all($pattern,$content,$match);
		$img_all=[];
		if(isset($match[1][0])){
			foreach ($match[1] as $v) {
				if(substr_count($v,'data:image/') || substr_count($v,';base64') || strpos($v,'/emoji/') !== FALSE || empty($v)){
					continue;
				}
				$img_all[]=$v;
			}
		}

		//去除泰文音标
		$content = preg_replace( '/\p{Thai}/u' , '' , $content );
		$tmp = str_replace('&nbsp;','',$content);
		$tmp = trim(strip_tags($tmp,'<img><iframe><embed><video><audio>'));
        if(empty($tmp) || $tmp == '&nbsp;')
            return $this->app_json('内容不能为空');
		//{hook a_post_post_4}
		//获取文章数据
		$Thread = M('Thread');
		$thread_data = $Thread->read($tid);
		//锁帖判断
        if($thread_data['state'] && NOW_UID != $thread_data['uid'] && NOW_GID != C("ADMIN_GROUP") && !is_forumg($this->_forum,NOW_UID,$thread_data['fid']))
            return $this->app_json('帖子已经被锁定');
        if(!L("Forum")->is_comp($thread_data['fid'],NOW_GID,'post',$this->_forum[$thread_data['fid']]['json']))
            return $this->app_json('你没有权限发表');

		//{hook a_post_post_5}
		$this->tid = $tid;
		$this->posts = $thread_data['posts'];
		$this->title = $thread_data['title'];

		//发送消息摘要
		$this->content = mb_substr(trim(filter_html($content)), 0,$this->conf['summary_size']);

		//{hook a_post_post_6}
		
		//回复评论 非点评评论
		$rpid = intval(X('post.pid',0));

		//写入评论数据
		$Post = S("Post");

		//评论不存在 或 评论是主题内容 无法引用回复
		if(!$Post->has(['pid'=>$rpid]) || $thread_data['pid'] == $rpid)
			$rpid = 0;


		$Post->insert(array(
			'tid'	=> $tid,
			'fid'	=> $thread_data['fid'],
			'uid'	=> NOW_UID,
			'rpid'	=> $rpid,
			'content' => trim($content),
			'atime'	  => NOW_TIME,
			'etime'	  => NOW_TIME
		));
		$this->pid = $pid = $Post->id();
		//{hook a_post_post_61}

		//处理临时文件
		$UserTmpUploadPath 	= 	GetUserTmpUploadPath(NOW_UID);
		$tmp_file_expression= "/src=\"(.*?)\"/i";
		preg_match_all($tmp_file_expression,$content,$matchsrc);
		$SrcFileList=[];
		if(isset($matchsrc[1][0])){
			$SrcFileList=$matchsrc[1];
		}
		//{hook a_post_post_62}
		$MoveFileList = [];
		if(!empty($SrcFileList)){
			$StoragePostDir 		=	GetStoragePostDir($tid,$pid);
			foreach ($SrcFileList as $v) {
				$TmpFilePath = realpath(INDEX_PATH . str_replace(WWW,'',$v));
				$TmpFilePath = str_replace("\\",'/',$TmpFilePath);
				if(strpos($TmpFilePath,$UserTmpUploadPath) !== false){//确定为临时文件
					$NewFilePath = str_replace($UserTmpUploadPath,$StoragePostDir,$TmpFilePath);
					//移动临时文件到正式目录
					if(move_file($TmpFilePath, $NewFilePath)){
						$MoveFileList[] = $NewFilePath;
					}
					
				}
			}
			//替换临时文件路径为正式文件路径
			$content = str_replace($UserTmpUploadPath,$StoragePostDir,$content);
		}

		//{hook a_post_post_63}
		if(!empty($MoveFileList)){
        	$File=M('File');
        	foreach ($MoveFileList as $v) {
				$FileInfo = pathinfo($v);
				$FileName = $FileInfo['filename'];
				$File->update([
					'tid'	=> $tid,
					'pid'	=> $pid,
				],[
					'AND'=>['uid'=>NOW_UID,'md5'=>$FileName]
				]);
            }
        }
        //{hook a_post_post_64}
		//@用户
		$this->ante_type = 'post';
		if($UsergroupLib->read(NOW_GID,'mess',$this->_usergroup))
			$content = $this->ante($content);
		$Post->update(['content'=>$content],['pid'=>$pid]);


		//{hook a_post_post_66}
		//分类 评论数量+1
		M("Forum")->update_int($thread_data['fid'],'posts');
		$this->_forum[$thread_data['fid']]['posts']++;
		$this->CacheObj->forum = $this->_forum;
		$this->_count['post']++;
		$this->_count['day_post']++;
		$this->CacheObj->bbs_count = $this->_count;
		if($thread_data['top']==1) //如果是板块置顶帖子，清理该板块置顶帖子缓存
			$this->CacheObj->rm("forum_top_id_".$thread_data['fid']);
		elseif($thread_data['top']==2)
			$this->CacheObj->rm("top_data_2");
		//{hook a_post_post_7}
		//更新主题 回复帖子数
		$Thread->update([
			'posts'=>$Post->count(['tid'=>$tid])-1, //评论数+1
			'btime'=>NOW_TIME, // 最后评论过时间
			'buid'=>NOW_UID, //最后回复者用户ID
		],[
			'tid'=>$tid
		]);
		$User = M("User");
		//用户评论数+1
		$User->update_int(NOW_UID,'posts','+');
		//增加金币
		$User->update_int(NOW_UID,'gold','+',$this->conf['gold_post']);
		//增加积分
		$User->update_int(NOW_UID,'credits','+',$this->conf['credits_post']);
		$this->_user['posts']++;
		if($thread_data['uid'] != NOW_UID){
			M("Chat")->sys_send($thread_data['uid'],'<a href="'. HYBBS_URLA('my',NOW_USER).'" target="_blank">['.NOW_USER.']</a> 回复了你的主题 <a href="'. HYBBS_URLA('thread',$thread_data['tid']).'" target="_blank">['.$thread_data['title'].']</a>');
		}
		if($this->conf['gold_post'] != 0 || $this->conf['credits_post'] != 0){
			S("Log")->insert(array(
				'uid'=>NOW_UID,
				'gold'=>$this->conf['gold_post'],
				'credits'=>$this->conf['credits_post'],
				'content'=>'发表评论 文章ID['.$thread_data['tid'].']',
				'atime'=>NOW_TIME
			));
		}
		//{hook a_post_post_9}

		if($thread_data['top'] == 2)
			$this->CacheObj->rm("top_data_2");
		elseif($thread_data['top'] == 1)
			$this->CacheObj->rm("forum_top_id_".$thread_data['fid']);

		$this->CacheObj->rm("index_index_Btime_1");
		$this->CacheObj->rm("index_index_{$thread_data['fid']}_1_Btime");
		$this->CacheObj->rm('thread_data_'.$tid);
		//{hook a_post_post_10}
		$count = intval(($thread_data['posts'] /  $this->conf['postlist']) + 1)+1;
        for ($i=0; $i < $count; $i++) {
            $this->CacheObj->rm("post_list_{$tid}_DESC_{$i}");
            $this->CacheObj->rm("post_list_{$tid}_ASC_{$i}");
        }
        //{hook a_post_post_11}

		//用户组升级检测
		M('Usergroup')->check_up(NOW_UID);
		

        //{hook a_post_post_v}
        return $this->app_json('发表成功',true);

    }
    //发表子评论
	public function post_post(){
        if(!IS_LOGIN){
			return $this->app_json('请登录后再操作');
        }
		//{hook a_post_post_post_0}
		if(IS_POST){
			//{hook a_post_post_post_1}
			if($this->_user['ban_post']){
                return $this->app_json('您的账号已被禁言');
			}
			//{hook a_post_post_post_2}
			$pid = intval(X('post.pid'));
			$content = trim(X('post.content'));
			$content = str_replace(['<div><br></div>','<div>','</div>','<p>','</p>'],"\n",$content);
			$content = strip_tags($content); //去除HTML标签并
			$content = preg_replace( '/\p{Thai}/u' , '' , $content );
			$content = str_replace(["\n\n","\n"],"<br>",$content);
			$content = str_replace("<br><br>","<br>",$content);
			$content = trim($content);
			//{hook a_post_post_post_3}
			
			if(substr($content,-4) == '<br>')
				$content = substr($content,0,-4);
            if($content == '' || !mb_strlen($content))
                return $this->app_json('请输入提交内容');
			
			$Post = M('Post');
            if(!$Post->is_pid($pid))
                return $this->app_json('该帖子已被删除，无法评论！');
			//{hook a_post_post_post_4}

			$post_data = $Post->get_row($pid,['tid','uid','content']);
			$tid = $post_data['tid'];

			$this->title = mb_substr(trim(strip_tags($post_data['content'])), 0,50);

            if(!$tid)
                return $this->app_json('无法找到原主题数据，无法评论！');
			//{hook a_post_post_post_5}
			$this->pid = $pid;

			
			//@用户
			$this->ante_type = 'post_post';
			if(L("Usergroup")->read(NOW_GID,'mess',$this->_usergroup))
				$content = $this->ante($content);
			//{hook a_post_post_post_6}
			$Thread = M('Thread');
			$Post_post = S('Post_post');
			$Post_post->insert([
				'pid'=>$pid,
				'tid'=>$tid,
				'uid'=>NOW_UID,
				'content'=>$content,
				'atime'=>NOW_TIME,
			]);
			//{hook a_post_post_post_7}
			$Post->update(['posts[+]'=>1],['pid'=>$pid]);
			M('User')->update(['post_ps[+]'=>1],['uid'=>NOW_UID]);
			$data = [
				'avatar'=>[
					'a' => WWW.$this->avatar(NOW_UID)['a'],
					'b' => WWW.$this->avatar(NOW_UID)['b'],
					'c' => WWW.$this->avatar(NOW_UID)['c']
				],
				'user'=>NOW_USER,
				'uid'=>NOW_UID,
				'content'=>$content
			];
			//{hook a_post_post_post_8}
			if(NOW_UID != $post_data['uid']){
				M("Chat")->sys_send(
					$post_data['uid'],
					'<a href="'. HYBBS_URLA('my',NOW_USER) .'" target="_blank">['.NOW_USER.']</a> 评论了你的回复 <a href="'. HYBBS_URLA('thread','post',$pid).'" target="_blank">['.mb_substr(strip_tags($post_data['content']),0,25).']</a>'
				);
			}
            //{hook a_post_post_post_v}
            return $this->app_json('发表成功！',true,['data'=>$data]);
		}
    }
    //投票
	public function vote(){
		//{hook a_post_vote_1}
        if(!IS_LOGIN)
            return $this->app_json('你需要登录才可投票');
		$id=intval(X("post.id")); // 提交ID
		$type = X("post.type"); //类型
        if(!in_array($type,['thread1','thread2','post1','post2']))
            return $this->app_json('投票类型不符');
		$type1=substr($type,0,-1);
		//{hook a_post_vote_2}
		if($type1 == 'thread'){
			$Thread = S("Thread");
            if(!$Thread->has(['tid'=>$id]))
                return $this->app_json('不存在该主题');

			//{hook a_post_vote_3}
			$obj = S("Vote_thread");
			if(!$obj->has([
				'AND'=>[
					'uid'=>NOW_UID,
					'tid'=>$id
					]
				]
			)){
				if($type == 'thread1')
					$Thread->update(['goods[+]'=>1],['tid'=>$id]);
				else
					$Thread->update(['nos[+]'=>1],['tid'=>$id]);
				//{hook a_post_vote_4}
				$obj->insert(array(
					'uid'	=>	NOW_UID,
					'tid'	=>	$id,
					'atime'	=>	NOW_TIME,
				));
				$this->CacheObj->rm('thread_data_'.$id);
                //{hook a_post_vote_5}
                return $this->app_json('投票成功');
				

			}
            //{hook a_post_vote_6}
            return $this->app_json('你投过了');
			
		}elseif($type1 == 'post'){
			//{hook a_post_vote_7}
			$Post = S("Post");
            if(!$Post->has(['pid'=>$id]))
                return $this->app_json('不存在该评论');
			//{hook a_post_vote_8}
			$obj = S("Vote_post");
			if(!$obj->has([
				'AND'=>[
					'uid'=>NOW_UID,
					'pid'=>$id
					]
				]
			)){
				if($type == 'post1')
					$Post->update(['goods[+]'=>1],['pid'=>$id]);
				else
					$Post->update(['nos[+]'=>1],['pid'=>$id]);
				//{hook a_post_vote_9}
				$obj->insert([
					'uid'	=>	NOW_UID,
					'pid'	=>	$id,
					'atime'	=>	NOW_TIME,
				]);
                //{hook a_post_vote_10}
                return $this->app_json('投票成功',true);
                
			}
            //{hook a_post_vote_11}
            return $this->app_json('你投过了');
			
		}

	}
	//删除评论， 不是 删除主题！
	public function del(){
		//{hook a_post_del_1}
        if(!IS_LOGIN)
            return $this->app_json('请登录');

		//用户组权限判断
		$UsergroupLib = L("Usergroup");
        if(!$UsergroupLib->read(NOW_GID,'del',$this->_usergroup))
            return $this->app_json('你当前所在用户组无法删除评论');
		//{hook a_post_del_2}
		$pid = intval(X("post.id"));
        $Post = M("Post");

		//获取 评论数据
        $post_data = $Post->read($pid);
        if(empty($post_data))
            return $this->app_json('不存在此评论');
        //{hook a_post_del_3}
		$fid = $post_data['fid'];
		$tid = $post_data['tid'];

		//{hook a_post_del_4}
        //用户组不是 管理员 &&  用户不是文章作者
        if(
			(NOW_GID != C("ADMIN_GROUP")) &&
			(NOW_UID != $post_data['uid']) &&
			//array_search(NOW_UID,$arr) === false
			!is_forumg($this->_forum,NOW_UID,$fid)
        )
            return $this->app_json('你没有权限操作这个评论');

        //{hook a_post_del_5}
        //删除该ID评论
        $Post->del($pid);
        //主题评论数-1
		$Thread = M('Thread');
		$Thread->update_int($tid,'posts','-');
		//帖子作者-1
		M("User")->update_int($post_data['uid'],'posts','-');
		//更新缓存
		$this->_forum[$fid]['posts']--;
		$this->CacheObj->forum = $this->_forum;
		$this->_count['post']--;
		$this->CacheObj->bbs_count = $this->_count;
		//{hook a_post_del_6}
		//发送删除帖子消息
        if(NOW_UID != $post_data['uid']){
	        M("Chat")->sys_send(
	            $post_data['uid'],
	            '您的评论被删除 所在主题<a href="'.HYBBS_URLA('thread',$tid).'" target="_blank">['.$Thread->get_title($tid).']</a> 操作者:'.NOW_USER
	        );
        }
        //{hook a_post_del_7}
      	//删除附件
      	$StoragePostDir = GetStoragePostDir($tid,$pid);
      	deldir(INDEX_PATH . $StoragePostDir,false,true);
      	S('File')->delete(['pid'=>$pid]);
      	
        //{hook a_post_del_8}
        //删除缓存
        $count = intval(($Thread->get_row($tid,'posts') /  $this->conf['postlist']) + 1)+1;
        for ($i=0; $i < $count; $i++) {
            $this->CacheObj->rm("post_list_{$tid}_DESC_{$i}");
            $this->CacheObj->rm("post_list_{$tid}_ASC_{$i}");
        }
        $this->CacheObj->rm("post_data_".$post_data['pid']);

        //{hook a_post_del_5}
        return $this->app_json('删除成功',true);
    }
    // 用户
    public function user(){
        //{hook a_my_empty_1}
        $username = X('user');
        $method   = X('type');
        $pageid   = X('pageid') ? X('pageid') : 1;
        $username = urldecode ($username); //url解码
        if(empty($username))
            return $this->message("请输入一个用户名称");

        //$encode = mb_detect_encoding($username);
        //var_dump($username);

        //echo $encode;return;
        //if ($encode == "UTF-8"){
        //$username = iconv('GBK',"UTF-8",$username);
            //$username = iconv('GBK',"UTF-8",$username);
        //}
        
        //服务器引入 GBK编码 非zh系统
        $encode = mb_detect_encoding($username, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5')); 
        $username = mb_convert_encoding($username, 'UTF-8', $encode);

        //{hook a_my_empty_2}
        $User = M("User"); //实例用户模型
        $uid = $User->user_to_uid($username); //用户名转ID

        if(!$uid)
            return $this->app_json("不存在该用户");

        if(empty($method))
            $method = 'index';

        if($method == 'index'){ //用户首页
            //{hook a_my_empty_4}
            $thread_data = (array)M('Thread')->get_user_thread_list($uid,1,5);

            $post_data = S("Post")->select("*",array(
                'AND'=>array(
                    'uid'=>$uid,
                    'isthread'=>0
                ),
                "ORDER"=> ['pid'=>'DESC'],
                'LIMIT'=>5
            ));

            //{hook a_my_empty_5}
            foreach ($post_data as &$v) {
                $v['content'] = mb_substr(strip_tags($v['content']), 0,50);
            }
            $this->v("thread_data",$thread_data);
            $this->v("post_data",$post_data);

            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];
            $data['friend_state'] = false;
            if(IS_LOGIN){
                if(NOW_UID != $uid){
                    $Friend = M("Friend");
                    $data['friend_state'] = $Friend->get_state(NOW_UID,$uid);
                }
                

            }
            return $this->app_json('success',true,[
                'data'=>$data
            ]);
        }elseif($method == 'thread'){ //用户主题
            //{hook a_my_empty_6}
            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];

            $Thread = M("Thread");

            $thread_data = (array)$Thread->get_user_thread_list($uid,$pageid);

            foreach ($thread_data as &$v) {
                $v['atime'] =   $v['atime'];
                $v['avatar'] =$data['avatar'];
                $v['user']  = $data['user'];
                
            }
            //{hook a_my_empty_7}
            //print_r($thread_data);

            $count = $data['threads'];
            $count = (!$count)?1:$count;
            $page_count = ($count % 10 != 0)?(intval($count/10)+1) : intval($count/10);
            //{hook a_my_empty_8}

            return $this->app_json('success',true,[
                'pageid'    => $pageid,
                'page_count'=> $page_count,
                'thread_data'   => $thread_data,
                'data'          => $data
            ]);
        }elseif($method == 'post'){ //用户帖子
            //{hook a_my_empty_9}
            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];

            $Post = S("Post");

            $post_data = $Post->select('*',[
                
                'AND'=>[
                    'uid'=>$uid,
                    'isthread'=>0
                ],
                'LIMIT' =>[($pageid-1) * 10, 10],
                'ORDER' => ['pid'=>'DESC']
            ]);
            //{hook a_my_empty_100}
            $Thread = M("Thread");
            $tmp_thread_data= array();
            foreach ($post_data as &$v) {
                if(!isset($tmp_thread_data[$v['tid']]))
                    $tmp_thread_data[$v['tid']] = $Thread->get_row($v['tid'],['uid','title']);
                //$v['atime']=$v['atime'];
                $v['content'] = mb_substr(strip_tags($v['content']), 0,50);
                $v['title'] = $tmp_thread_data[$v['tid']]['title'];
                $v['uid'] = $tmp_thread_data[$v['tid']]['uid'];
            }
            $User->auto_add_user($post_data);
            
            //{hook a_my_empty_10}

            $count = $data['posts'];
            $count = (!$count)?1:$count;
            $page_count = ($count % 10 != 0)?(intval($count/10)+1) : intval($count/10);

            return $this->app_json('success',true,[
                'pageid'    => $pageid,
                'page_count'=> $page_count,
                'post_data' => $post_data,
                'data'      => $data
            ]);
        }elseif($method == 'op'){//用户配置
            //{hook a_my_empty_13}
            if(!IS_LOGIN)
                return $this->app_json("未登录，无法查看该页面");
            if(NOW_UID != $uid)
                return $this->app_json("没有权限访问他人配置页");
            $ation = X('ation');
            if($ation == 'pass'){
                $pass0 = X("post.pass0");
                $pass1 = X("post.pass1");
                $pass2 = X("post.pass2");
                //{hook a_user_edit_2}
                if($pass1 != $pass2)
                    return $this->app_json("两次密码不一致");
                $UserLib = L("User");
                if(!$UserLib->check_pass($pass1))
                    return $this->app_json('密码不符合规则');
                //{hook a_user_edit_3}
                if($UserLib->md5_md5($pass0,$this->_user['salt']) != $this->_user['pass'])
                    return $this->app_json('原密码不正确');
                $newpass = $UserLib->md5_md5($pass1,$this->_user['salt']);
                $this->_user['pass'] = $newpass;
                S("User")->update(array(
                    'pass'=>$this->_user['pass']
                ),[
                    'uid'=>NOW_UID
                ]);
                //{hook a_user_edit_4}
                cookie('HYBBS_HEX',$UserLib->set_cookie($this->_user));
                return $this->app_json("修改成功",true,[
                    'cookie' => 'HYBBS_HEX='.cookie('HYBBS_HEX')
                ]);
            }elseif($ation == 'ps'){
                $ps = htmlspecialchars(strip_tags(X("ps")));
                S("User")->update(array(
                    'ps'=>$ps
                ),[
                    'uid'=>NOW_UID
                ]);
                return $this->app_json('保存成功',true);
            }else{
                return $this->app_json('操作失败:操作类型错误');
            }

            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];

            //{hook a_my_empty_133}

            return $this->app_json('success',true,[
                'data'  => $data
            ]);
        }elseif($method == 'file'){ //文件列表
            //{hook a_my_empty_16}
            if(!IS_LOGIN)
                return $this->app_json("未登录，无法查看你的消息");
            if(NOW_UID != $uid)
                return $this->app_json("你不能查看他人文件!");
            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];
            $File=S("File");
            $Filedata = $File->select('*',['uid'=>$uid,'ORDER'=>['id'=>'DESC']]);

            // $filearr = array();
            // if(is_dir(INDEX_PATH. "upload/userfile/".$uid."/")){
            //     if($dh = opendir(INDEX_PATH. "upload/userfile/".$uid."/")) {
            //         while (($file = readdir($dh)) !== false){
                        
            //             if($file!="." && $file!=".."){
            //                 $filearr[]=$file;
                            
            //             }
            //         }
            //     }
            // }
            //{hook a_my_empty_17}
            //$this->v("filearr",$filearr);

            return $this->app_json('success',true,[
                'filelist' => $Filedata,
                'data'     => $data
            ]);
        }elseif($method == 'log'){
            if(!IS_LOGIN)
                return $this->app_json("未登录，无法查看该页面");
            if(NOW_UID != $uid)
                return $this->app_json("没有权限访问他人流水记录");


            $data = $User->read($uid);
            $data['avatar'] = $this->avatar($uid);
            $this->v('data',$data);
            $this->v("title","积分日志");

            $Log = S('Log');
            $log_data = $Log->select('*',[
                'uid'=>NOW_UID,
                'ORDER'=>['id'=>'DESC'],
                'LIMIT' =>[($pageid-1) * 10, 10],
            ]);

            $count = $Log->count(['uid'=>NOW_UID]);
            $page_count = ($count % 10 != 0)?(intval($count/10)+1) : intval($count/10);

            $this->v("count",$count);
            $this->v("pageid",$pageid);
            $this->v("page_count",$page_count);
            $this->v('log_data',$log_data);
            return $this->app_json('success',true,[
                'count'     => $count,
                'pageid'    => $pageid,
                'page_count'=> $page_count,
                'log_data'  => $log_data
            ]);
        }elseif($method == 'message'){
            if(!IS_LOGIN)
                return $this->app_json("未登录，无法查看该页面");
            if(NOW_UID != $uid)
                return $this->app_json("没有权限访问消息页面");

            $data = $User->read($uid);
            $data['avatar'] = [
                'a' => WWW.$this->avatar($uid)['a'],
                'b' => WWW.$this->avatar($uid)['b'],
                'c' => WWW.$this->avatar($uid)['c'],
            ];


            $message = X('get.message');
            $chat_uid = X('get.uid');
            if(empty($message))  $message = 'index';
            if(empty($chat_uid)) $chat_uid = 0;

            $Friend = S('Friend');
            $friend_data = $Friend->select('*',['OR'=>['uid1'=>NOW_UID,'uid2'=>NOW_UID],'ORDER'=>['update_time'=>'DESC']]);


            $chat_user_data =[];
            if($chat_uid == 0){
                $chat_user_data=[
                    'uid'=>0,
                    'user'=>'系统',
                    'avatar'=>[
                        'a'=>WWW.'View/hy_friend/bell.png',
                        'b'=>WWW.'View/hy_friend/bell.png',
                        'c'=>WWW.'View/hy_friend/bell.png'
                    ]
                ];
            }elseif($User->has(['uid'=>$chat_uid])){
                $chat_user_data = $User->read($chat_uid);
                $chat_user_data['avatar'] = $this->avatar($chat_uid);

            }
            $friend_list=[];
            if(!empty($friend_data)){

                switch ($message) {
                    case 'index':
                        foreach ($friend_data as $v) {
                            if($v['uid1']==NOW_UID)
                                $friend_list[]=$v;
                        }
                        foreach ($friend_data as $v) {
                            if($v['uid1'] != NOW_UID && $v['uid2'] == NOW_UID){
                                $b=false;
                                foreach ($friend_list as $vv) {
                                    if($vv['uid1'] == $v['uid2'] && $vv['uid2'] == $v['uid1']){
                                        $b=true;
                                        break;
                                    }
                                }
                                if(!$b){
                                    $v['uid2'] = $v['uid1'];
                                    $friend_list[]=$v;
                                }

                                $tmp = array();
                                unset($vv);
                                foreach ($friend_list as $vv) {
                                    $tmp[] = $vv['update_time'];
                                }
                                array_multisort($tmp,SORT_DESC,$friend_list);
                            }
                        }
                        break;
                    case 'follow':
                        // $friend_list = $Friend->select('*',['AND'=>['uid1'=>NOW_UID,'state'=>[1,2]],'ORDER'=>['atime'=>'DESC']]);

                        foreach ($friend_data as $v) {
                            if($v['uid1']==NOW_UID && ($v['state'] == 1 || $v['state'] == 2))
                                $friend_list[]=$v;
                        }
                        break;
                    case 'fans':
                        // $friend_list = $Friend->select('*',['AND'=>['uid2'=>NOW_UID,'state'=>[1,2]],'ORDER'=>['update_time'=>'DESC']]);
                        // foreach ($friend_list as $key => &$v) {
                        //     $v['uid2'] = $v['uid1'];
                        // }

                        foreach ($friend_data as $v) {
                            if($v['uid2']==NOW_UID && ($v['state'] == 1 || $v['state'] == 2)){
                                $v['uid2']=$v['uid1'];
                                $friend_list[]=$v;
                            }
                        }
                        break;
                    default:
                        break;
                }
                $User->auto_add_user($friend_list,'user','uid2');
            }

            $Online = S("Online");

            $administrator = [
                'uid2'=>0,
                'user'=>'系统',
                'ps'=>'系统消息',
                'avatar'=>[
                    'a'=>'View/hy_friend/bell.png',
                    'b'=>'View/hy_friend/bell.png',
                    'c'=>'View/hy_friend/bell.png',
                ],
                'ol'=>true,
                'c'=>0
            ];
            foreach ($friend_list as $key => &$v) {
                $v['ps'] = $User->get_row($v['uid2'],'ps');
//                if($v['uid2']==0)$v['ps']='系统消息';
                $v['avatar'] = [
                    'a' => WWW.$this->avatar($v['uid2'])['a'],
                    'b' => WWW.$this->avatar($v['uid2'])['b'],
                    'c' => WWW.$this->avatar($v['uid2'])['c'],
                ];
                $v['ol']=$Online->has(['AND'=>['uid'=>$v['uid2'],'atime[>]'=>NOW_TIME-BBSCONF('out_s')]]);

                if($v['uid2'] == 0){
                    $administrator['c']=$v['c'];
                    unset($friend_list[$key]);
                }
            }
            if($message == 'index')
                array_unshift($friend_list,$administrator);


            return $this->app_json('seccess',true,[
                'chat_user_data'=> $chat_user_data,
                'friend_list'   => $friend_list,
                '$data'         => $data
            ]);
        }
    }
    // 搜索分类
    public function searchforum(){
        if(!IS_LOGIN){
            return $this->app_json('登录过期请重新登录',0);
        }
        
        $name = htmlentities(trim(X('get.name')));
        $size = 10;
        $pageid = X('get.pageid')?X('get.pageid'):1;
        $data = S('forum')->select(['id','name','posts','threads'],[
            'name[~]'=>$name,
            'ORDER' => ['threads'=>'DESC'],
            'LIMIT' => [($pageid-1) * $size,$size]
        ]);
        foreach($data as &$v){
            if(is_file(INDEX_PATH."upload/forum{$v['id']}.png")){
                $v['icon'] = WWW."upload/forum{$v['id']}.png";
            }else{
                $v['icon'] = WWW."upload/de.png";
            }
        }
        return $this->app_json('success',1,['search'=>$data]);
        
    }
    // 列表数据
    public function forumlist(){
        $fid        = X('fid');
        $pageid	    = intval(X('pageid')) 	or $pageid=1;
        $type 	    = X('type') 			or $type='new';
        $forumlist  = [];
        $forum_class= [];
        $size       = intval(X('size')) 	or $size=10;
        // print_r($fids);exit;
        switch ($type) {
            case 'daihui':
                $canshu = ['fid'=>$fid,'posts'=>0,'ORDER' => ['tid'=>'DESC'],'LIMIT' => [($pageid-1) * $size,$size]];
                break;
            
            case 'remen':
                $canshu = ['fid'=>$fid,'posts[!]'=>0,'ORDER' => ['tid'=>'DESC'],'LIMIT' => [($pageid-1) * $size,$size]];
                break;
            
            case 'jing':
                $canshu = ['fid'=>$fid,'jing'=>1,'ORDER' => ['tid'=>'DESC'],'LIMIT' => [($pageid-1) * $size,$size]];
                break;
            
            default:
                $canshu = ['fid'=>$fid,'ORDER' => ['tid'=>'DESC'],'LIMIT' => [($pageid-1) * $size,$size]];
                break;
        }
        // 板块信息
        $forum_data = $this->CacheObj->get("app_forum_info_{$fid}_{$pageid}");
        if(empty($forum_data) || DEBUG){
            // 论坛详情
            $Forum = S('forum');
            $forum_data = $Forum->find('*',[
                'id'=>$fid,
            ]);
            if(!empty($forum_data)){
                if(is_file(INDEX_PATH."upload/forum{$forum_data['id']}.png")){
                    $forum_data['icon'] = WWW."upload/forum{$forum_data['id']}.png";
                }else{
                    $forum_data['icon'] = WWW."upload/de.png";
                }
                if(!empty($forum_data['bg_img'])){
                    $forum_data['bg_img'] = WWW.$forum_data['bg_img'];
                }else{
                    $forum_data['bg_img'] = "";
                }
            }
            $this->CacheObj->set("app_forum_info_{$fid}_{$pageid}",$forum_data);
        }
        // 板块子分类
        $forum_class = $this->CacheObj->get("app_forum_class_{$fid}_{$pageid}");
        if(empty($forum_class) || DEBUG){
            // 论坛详情
            $Forum = S('forum');
            $forum_class = $Forum->select(['name','id'],[
                'fid'=>$fid,
            ]);
            array_unshift($forum_class,[
                'name' => '全部',
                'id'   => $fid
            ]); 
            $this->CacheObj->set("app_forum_class_{$fid}_{$pageid}",$forum_class);
        }
        // 置顶帖子列表
		$forumtop = $this->CacheObj->get("app_forum_list_top{$fid}_{$type}_{$pageid}");
        if(empty($forumtop) || DEBUG){
            // 帖子列表
            $User       = M('User');
            $thread     = S('thread');
            $fids = S('forum')->select('id',['fid'=>$fid]);
            $forumtop  = $thread->select(['tid','fid','top','atime','title'],$canshu);
            foreach($forumtop as &$v){
                $v['atime']     = humandate($v['atime']);
            }
            $this->CacheObj->set("app_forum_list_top{$fid}_{$type}_{$pageid}",$forumtop);
        }

        // 帖子列表
		$forumlist = $this->CacheObj->get("app_forum_list_{$fid}_{$type}_{$pageid}");
        if(empty($forumlist) || DEBUG){
            // 帖子列表
            $User       = M('User');
            $thread     = S('thread');
            $fids = S('forum')->select('id',['fid'=>$fid]);
            array_unshift($fids,$fid);
            $canshu['fid'] = $fids;
            // var_dump($canshu);exit;
            $forumlist  = $thread->select('*',$canshu);
            foreach($forumlist as &$v){
                $v['img']       = !empty($v['img'])?array_filter(explode(",",$v['img'])):[];
                $v['user']      = $User->uid_to_user($v['uid']);
                $v['avatar']    = WWW . $this->avatar($v['uid'])['b'];
                $v['atime']     = humandate($v['atime']);
            }
            // var_dump($forumlist);exit;
            $this->CacheObj->set("app_forum_list_{$fid}_{$type}_{$pageid}",$forumlist);
        }
        // $count = $this->_count['thread'];
		// $count = (!$count)?1:$count;
        // $page_count = ($count % $this->conf['homelist'] != 0)?(intval($count/$this->conf['homelist'])+1) : intval($count/$this->conf['homelist']);
        
        return $this->json([
            'foruminfo'     => $forum_data,
            'forumclass'    => $forum_class,
            'forumtop'     => $forumtop,
            'forumlist'     => $forumlist
        ]);
    }
    // 用户登录
    public function login(){
        if(IS_POST){
            if(IS_LOGIN){
                return $this->app_json('已经登录过');
            }
            $user = X("post.user");
            $pass = X("post.pass");
            $UserLib = L("User");
            if(!$UserLib->check_pass($pass))
                return $this->app_json('密码不符合规则');
            $User = M("User");
            if(!$User->is_user($user))
                return $this->app_json("账号不存在-请使用昵称*网名");
           
            $data = $User->user_read($user);
            if(!empty($data)){
                //密码正确
                if($data['pass'] == $UserLib->md5_md5($pass,$data['salt'])){//登录成功
                    if($data['ban_login']){
                        return $this->app_json("账号已经被管理员锁定，禁止登陆!");
                    }
                    $Friend = S("Friend");
                    $sum = $Friend->sum("c",array('uid1'=>$data['uid']));
                    M("Chat_count")->update(array('c'=>$sum),array('uid'=>$data['uid']));

                    //更新用户所有缓存 一个星期更新缓存
                    if($data['ctime']+(86400*7) < NOW_TIME){

                        $count1 = $Friend->count(array('AND'=>array('uid1'=>$data['uid'],'OR'=>array('state'=>array(1,2)))));
                        $count2 = $Friend->count(array('AND'=>array('uid2'=>$data['uid'],'OR'=>array('state'=>array(1,2)))));

                        $User->update([
                            'ctime'=>NOW_TIME,
                            'threads'=>S("Thread")->count(['uid'=>$data['uid']]),
                            'posts'=>S("Post")->count(['uid'=>$data['uid']]),
                            'post_ps'=>S("Post_post")->count(['uid'=>$data['uid']]),
                            'follow'=>$count1,
                            'fans'=>$count2,
                        ],[
                            'uid'=>$data['uid']
                        ]);
                    }
                    //在线用户结束
                    cookie('HYBBS_HEX',$UserLib->set_cookie($data));
                    $this->init_user();
                    $this->_user['avatar']['a'] = WWW.$this->_user['avatar']['a'];
                    $this->_user['avatar']['b'] = WWW.$this->_user['avatar']['b'];
                    $this->_user['avatar']['c'] = WWW.$this->_user['avatar']['c'];
                    unset($this->_user['pass']);
                    unset($this->_user['salt']);
                    return $this->app_json("登录成功 !",true,['user'=>$this->_user,'cookie'=>"HYBBS_HEX=".cookie('HYBBS_HEX')]);
                }else{
                    return $this->app_json("密码错误!");
                }
            }else{
                return $this->app_json('账号数据不存在!');
            }
        }
    }
    
    
    
    /*
    // 用户注册
    public function adduser(){
        if(IS_POST){
            if(IS_LOGIN){
                return $this->app_json('已经登录过');
            }
            $user = X("post.user");
            $pass1 = X("post.pass1");
            $pass2 = X("post.pass2");
            $email = X("post.email");
            if($pass1 != $pass2)
                return $this->app_json("两次密码不一致");

            $UserLib = L("User");
            $msg = $UserLib->check_user($user);
            //检查用户名格式是否正确
            if(!empty($msg))
                return $this->app_json($msg);

            if(!$UserLib->check_pass($pass1))
                return $this->app_json('密码不符合规则');


            $msg = $UserLib->check_email($email);

            if(!empty($msg))
                return $this->app_json($msg);

            $User = M("User");
            if($User->is_user($user))
                return $this->app_json("账号已经存在!");

            if($User->is_email($email))
                return $this->app_json("邮箱已经存在!");


            $uid = $User->add_user($user,$pass1,$email);

            cookie('HYBBS_HEX',$UserLib->set_cookie($User->read($uid)));
            $this->_count['user']++;
            $this->_count['day_user']++;
            $this->CacheObj->bbs_count = $this->_count;

            return $this->app_json("账号注册成功",true);
        }
    }
    
    */
    
    // 密码找回
    public function repass(){
        if(IS_LOGIN){
            return $this->app_json('你已登录');
        }
        $email = X("post.email");
        $code = strtoupper(X("post.code"));
        $pass1=X("post.pass1");
        $pass2=X("post.pass2");
        //{hook a_user_recode2_2}
        if(empty($email)||empty($code)||empty($pass1)||empty($pass2))
            return $this->app_json('参数不完整,请填写好表单!');
        if($pass1 != $pass2)
            return $this->app_json('确认密码不一致');
        //{hook a_user_recode2_3}
        $UserLib = L("User");
        if(!$UserLib->check_pass($pass1))
            return $this->app_json('新密码不符合规则,必须大于等于5位');
        //{hook a_user_recode2_4}
        $User = M("User");

        if(!$User->is_email($email))
            return $this->app_json('邮箱不存在!');
        $data = $User->email_read($email);
        if(empty($data))
            return $this->app_json('邮箱不存在.');
        //{hook a_user_recode2_5}
        if(strlen($code) != 6)
            return $this->app_json('验证码是6位的.');
        //{hook a_user_recode2_6}
        $cookie = cache("HY_EMAIL");
        if(empty($cookie))
            return $this->app_json('验证码已经过期,请获取新验证码,紧急请联系管理员.');

        //{hook a_user_recode2_7}
        $Encrypt = L("Encrypt");
        $cr = $Encrypt->decrypt($cookie,$data['salt'].C("MD5_KEY"));
        if($cr != $code)
            return $this->app_json('验证码错误.');

        //{hook a_user_recode2_8}
        $User->update(array('pass'=>L("User")->md5_md5($pass1,$data['salt'])),array('uid'=>$data['uid']));
        cache('HY_EMAIL',null);
        return $this->app_json("修改成功",true);
    }
    // 找回密码验证码生成
    public function recode(){
        //{hook a_user_recode_1}
        $email = X("post.email");
        $emailhost = $this->conf['emailhost'];
        $emailport = $this->conf['emailport'];
        $emailuser = $this->conf['emailuser'];
        $emailpass = $this->conf['emailpass'];
        //{hook a_user_recode_2}

        if(empty($emailhost) || empty($emailport))
            return $this->app_json('网站没开启邮箱功能,请联系网站管理员');
        //{hook a_user_recode_3}
        $User = M("User");
        if(!$User->is_email($email))
            return $this->app_json('该邮箱不存在!');
        //{hook a_user_recode_4}
        $data = $User->email_read($email);
        if(empty($data))
            return $this->app_json('该邮箱不存在.');
        //{hook a_user_recode_5}
        if($data['etime'] > NOW_TIME)
            return $this->app_json(($data['etime'] - NOW_TIME)." 秒后才能发送验证码",true);

        //{hook a_user_recode_6}
        $code = rand_code(6);

        $Email = L("Email");

        $Encrypt = L("Encrypt");

        //{hook a_user_recode_7}
        $Email->init($emailhost,$emailport,true,$emailuser,$emailpass);

        if(!$Email->sendmail($email,$emailuser,$this->conf['emailtitle'],sprintf($this->conf['emailcontent'],$data['user'],$code),'HTML'))
            return $this->app_json('发送失败,具体原因:'.$Email->error_mess);
        cache('HY_EMAIL',$Encrypt->encrypt($code,$data['salt'].C("MD5_KEY")),array(
            'expire'=>300 //有效期5分钟
        ));
        $User->update(['etime'=>NOW_TIME+BBSCONF('send_email_s')],['uid'=>$data['uid']]);
        return $this->app_json('发送成功',true);
    }
    // 返回json
    protected function app_json($msg,$error=false,$data=[]){
        $arr = [
            'msg'   => $msg,
            'error' => $error,
            'data'  => $data
        ];
        return exit(json_encode($arr,JSON_UNESCAPED_UNICODE));
    }
    //@事件
	private function ante($content){
		//{hook a_post_ante_1}
		return preg_replace_callback('/@([^:|： @<&])+/',array($this, 'ante_callback'),$content);
	}
	private function ante_callback($tagStr){
		//{hook a_post_ante_callback_1}
		if(is_array($tagStr)) $tagStr = $tagStr[0];

		$tagStr = stripslashes($tagStr);
		$user = substr($tagStr,1);
		$User = M("User");
		$Chat = M("Chat");
		//{hook a_post_ante_callback_2}
		static $tmp_user=array(); //@发送一次
		if($user != NOW_USER){ //不能发送给自己
			if(!isset($tmp_user[$user])){ //本帖未@过该用户名
				if($User->is_user($user)/* && isset($tmp_user[$user])*/){ //判断用户是否存在
					//{hook a_post_ante_callback_3}
					$tmp_user[$user]=true;
					if($this->ante_type == 'thread')
						$Chat->sys_send($User->user_to_uid($user),'<a href="'. HYBBS_URLA('my',NOW_USER).'" target="_blank">['.NOW_USER.']</a> 在发表主题 <a href="'. HYBBS_URLA('thread',$this->tid).'" target="_blank">['.$this->title.']</a> 的时候@了你');
					elseif($this->ante_type == 'post')
						$Chat->sys_send($User->user_to_uid($user),'<a href="'. HYBBS_URLA('my',NOW_USER).'" target="_blank">['.NOW_USER.']</a> 在评论 <a href="'. HYBBS_URLA('thread','post',$this->pid).'" target="_blank">['.$this->title.']</a> 的时候@了你');
					elseif($this->ante_type == 'post_post')
						$Chat->sys_send($User->user_to_uid($user),'<a href="'. HYBBS_URLA('my',NOW_USER).'" target="_blank">['.NOW_USER.']</a> 回复评论 <a href="'. HYBBS_URLA('thread','post',$this->pid).'" target="_blank">['.$this->title.']</a> 的时候@了你');
					//{hook a_post_ante_callback_4}
				}
			}
			//{hook a_post_ante_callback_5}
			return '<span class="label label-primary">'.$tagStr.'</span>';
		}
		return $tagStr;
	}
}