<?php

/*
 * Copyright (C) xgcms.com
 */

!defined('FRAMEWORK_PATH') && exit('FRAMEWORK_PATH not defined.');

include POST_PATH.'core/control/common_control.class.php';

class post_control extends common_control {
	
	function __construct(&$conf) {
		parent::__construct($conf);
		$this->_checked = array('bbs'=>' class="checked"');
		// 加载积分策略
		$this->conf += $this->kv->xget('conf_ext');
	}
	
	// create ajax
	public function on_topic() {
		$this->_title[] = '发表帖子';
		$this->_nav[] = '发表帖子';
		
		//$this->check_login();
		$this->check_forbidden_group();
		
		$fid = intval(core::gpc('fid'));
		
		$forum = $this->mcache->read('forum', $fid);
		
		$uid = $this->_user['uid'];

		if($uid>0){
		    $user = $this->member->read($uid);
			$username = $this->_user['username'];
	    }else{
			$user = $this->_user;
			$username=$_SERVER['ip'];
		}
		// hook post_topic_user_after.php
		$group = $this->group->read($user['groupid']);
		$this->check_forum_exists($forum);
		$this->check_forum_status($forum);
		$this->check_access($forum, 'thread');
		
		$this->check_user_delete($user);
		
		
		
		if(!$this->form_submit()) {
			
			$attachlist = $this->get_attachlist_by_tmp($uid);
			$this->init_editor_attach($attachlist, '0');
		
		    //主题分类
			$typearr=array();
			if($forum['typeid']){
				$typearr=$this->type->get_typearr($forum['typeid']);
			}
			
			$this->view->assign('fid', $fid);
			
			//$typeselect = form::get_select('typeid', $forum['typelist'], 0, '');
			$this->view->assign('typearr', $typearr);
		
			// hook post_thread_before.php
			$this->view->display('post_topic_ajax.html');
		} else {
			if($forum['user_post']>1){
				$forum_follow=$this->forum_users->check_status($fid,$uid);
				if(!$forum_follow || $forum_follow['status']!=1){
					$this->message('非本吧成员不能发主题帖',0);
				}
			}
           if($group['verifynum']){
				   if(empty($_SESSION)){
				       session_start();	
				   }
				   $verifynum=strtolower(trim(core::gpc('verifyNum','P')));
				   if($verifynum!=$_SESSION['verify']) $this->message('验证码错误！',0);
			}
            $quickpost=intval(core::gpc('quickpost','P'));
			$subject = htmlspecialchars(core::gpc('subject', 'P'));
			$seo_keywords = htmlspecialchars(strip_tags(core::gpc('seo_keywords', 'P')));
			$message = core::gpc('message', 'P');
            
            $tags=core::gpc('tags','P');
			$typeid=intval(core::gpc('typeid','P'));
            
			// 快速发帖。
			if($quickpost) {
				$this->html_in($message);
				$message = misc::html_space($message);
			}
			$user['groupid']>1 && $message = $this->post->html_safe($message);
			
			$message=$this->message_rep($message,$group['allowlink'],$fid);
			
			// hook post_thread_after.php
			
			$thread = $post = $error = array();
		
			// -----------> 添加到 thread
			$thread = array(
				'fid'=>$fid,
				'typeid'=>$typeid,
				'authorid'=>$uid,
				'author'=>$username,
				'subject'=>$subject,
				'dateline'=>$_SERVER['time'],
				//'lastpost'=>0,
				'lastauthorid'=>$uid,
				'lastauthor'=>$username,
				'lasttime'=>'0',//$_SERVER['time'],
				'views'=>0,
				'posts'=>0,
				'replies'=>0,
				'top'=>0,
				'digest'=>0,
				'imagenum'=>0,	// 需要最后更新
				'attachnum'=>0,	// 需要最后更新
				//'modnum'=>0,	// 评分次数
				'lockout'=>0,
				'firstpid'=>0,	// 需要最后更新，也就是最小的pid，冗余存储，提高速度
				//'catenames'=>'',	// 
				//'cateids'=>0,	//
				//'typeid'=>$typeid,	//
				//'typename'=>$typename,	//
				//'coverimg'=>'',
				'brief'=>'',
				'status'=>0,
				'seo_keywords'=>$seo_keywords,
                'tags'=>'',
				'pids'=>'',		// 第一页的缓存的pid
			);
			$error['subject'] = $this->topic->check_subject($thread['subject']);
			$error['message'] = $this->post->check_message($message);
			empty($error['subject']) && $error['subject'] = $this->check_badword($subject);
			empty($error['message']) && $error['message'] = $this->check_badword($message);
			
			if(!array_filter($error)) {
				$error = array();
				
				// hook post_thread_create_before.php
				
				$tid = $thread['tid'] = $this->topic->create($thread);
				if(!$thread['tid']) {
					$this->message('发帖过程中保存数据错误，请联系管理员。');
				}
				// hook post_thread_create_after.php
				
				/*//$this->thread_views->create(array('tid'=>$tid, 'views'=>0));
				// 如果没有设置权限才加入。
				if(empty($this->conf['forumaccesson'][$fid]) || $this->conf['search_type'] == 'sphinx') {
					$this->thread_new->create(array('fid'=>$fid, 'tid'=>$tid, 'dateline'=>$_SERVER['time'], 'lastpost'=>$_SERVER['time']));
				}*/
				//@消息
				$this->at($message,"?topic-index-fid-$fid-tid-$tid.htm",1,$subject);
				
				// -----------> 添加到 post
				
				$page = 1;
				$floor=1;
				$post = array (
					'fid'=>$fid,
					'tid'=>$thread['tid'],
					'authorid'=>$uid,
					'dateline'=>$_SERVER['time'],
					'postip'=>ip2long($_SERVER['ip']),
					'attachnum'=>0,
					'imagenum'=>0,
					'rates'=>0,
					'page'=>$page,
					'author'=>$username,
					'floor'=>$floor,
					'subject'=>'',
					'message'=>$message,
				);
				
				// hook post_thread_post_create_before.php
				$pid = $post['pid'] = $this->post->create($post);
				// hook post_thread_post_create_after.php
				
				// 更新 $attach 上传文件的pid
				$attachnum = $imagenum = $coverimg=0;
				$aidarr = $this->attachment->get_aid_from_tmp($uid);

				foreach($aidarr as $fid_aid) {
					$arr = explode('_', $fid_aid);
					$fid = intval($arr[0]);
					$aid = intval($arr[1]);
					$attach = $this->attachment->read($fid, $aid);
					if(empty($attach)) continue;
					if($attach['uid'] != $uid) continue;
					$attach['fid'] = $post['fid'];
					$attach['pid'] = $post['pid'];
					$attach['tid'] = $post['tid'];
					$coverimg=0;
					if($attach['isimage'] == 1) {
						$imagenum++;
						if(empty($coverimg)) $coverimg=$attach['filename'];
					} else {
						preg_match("/\[attach=$aid\|gold=([0-9]+)\](.+?)\[\/attach\]/is",$message,$att);
						if(!empty($att)){
							$attach['golds']=$att[1];
							unset($att); 
							$post['message']=preg_replace("/\[attach=$aid\|gold=([0-9]+)\](.+?)\[\/attach\]/is",'',$post['message']);
						}
						$attachnum++;
					}
					$this->attachment->db_cache_update("attachment-fid-$fid-aid-$aid", $attach);
				}
				$this->attachment->clear_aid_from_tmp($uid);
                
				
				// 加入到 thread_type
				//$this->thread_type_data->xcreate($fid, $tid, $typeid1, $typeid2, $typeid3, $typeid4);
				if($tags){
					$tags=utf8::safe_substr($tags,0,80);
					$tagsarr=explode(" ",$tags);
					$newtags=array();
					foreach($tagsarr as $t){
						$t=misc::safe_str($t);
						if(!empty($t)){
							$t=utf8::safe_substr($t,0,20);
							$tag_id=$this->tags->_create($t,'topics');
							$newtags[]=$t;
							$tag_id && $this->tags_data->_create(array('tid'=>$tid,'fid'=>$fid,'tag_id'=>$tag_id,'dateline'=>$_SERVER['time']));
						}
					}
					$seo_keywords+=implode(',',$newtags);
					$tags=implode(' ',$newtags);
				}
            
				$brief = utf8::substr(strip_tags($message), 0, 80);
				// 更新 $thread firstpid
				$thread['firstpid'] = $post['pid'];
				$thread['imagenum'] = $imagenum;
				$thread['attachnum'] = $attachnum;
				$thread['brief'] = $brief;
				
				$thread['coverimg']=$coverimg;
                
                $thread['seo_keywords']=$seo_keywords;
                $thread['tags']=$tags;

				$this->topic->update($thread);
				
				// 更新 $post
				$post['imagenum'] = $imagenum;
				$post['attachnum'] = $attachnum;
				$this->post->update($post);
				
				// 更新 $user 用户发帖数，积分
				//$user = $this->user->read($uid);
				$user['topics']++;
				$user['posts']++;
				$user['credits'] += $this->conf['credits_policy_thread'];
				$user['golds'] += $this->conf['golds_policy_thread'];
				$groupid = $user['groupid'];
				$user['groupid'] = $this->group->get_groupid_by_credits($user['groupid'], $user['credits']);
				
				// 更新 cookie 如果用户组发生改变，更新用户的 cookie
				if($groupid != $user['groupid']) {
					$this->member->set_login_cookie($user);
				}
				
				// 加入 $mypost
				if(!$forum['accesson']) {
					$this->mypost->create(array('uid'=>$uid, 'fid'=>$fid, 'tid'=>$tid, 'pid'=>$pid));
					$user['myposts']++;
				}
				//加入本吧发帖
				!isset($forum_follow) && $forum_follow=$this->forum_users->check_status($fid,$uid);
				if($forum_follow){
				   $forum_follow['topics']++;
				   $forum_follow['lastpost']=$_SERVER['time'];
				   $this->forum_users->update($forum_follow);	
				}
				
				
				// 更新 user
				$this->member->update($user);
				
				// 更新 $forum 版块的总帖数
				$forum = $this->forum->read($fid);
				$forum['topics']++;
				$forum['posts']++;
				$forum['todayposts']++;
				$forum['lastpost']=$_SERVER['time'];
				//$forum['lasttid'] = $tid;
				
				if($coverimg){
					$this->topic_pic->create(array('fid'=>$fid,'tid'=>$thread['tid'],'coverimg'=>$coverimg));
					$forum['topic_pic']++;
				}
				
				$this->forum->xupdate($forum);
				$this->runtime->xset('posts', '+1');
				$this->runtime->xset('threads', '+1');
				$this->runtime->xset('todayposts', '+1');
				// $this->runtime->xsave();
				
				$this->topic->format($thread);
				$error['thread'] = $thread;
				//更新分类统计
				if($typeid){
				   $this->type_count->inc($fid,$typeid);	
				}
				// hook post_topic_succeed.php

			}
			$this->message($error);
		}
	}
	
	public function on_post() {
		$fid = intval(core::gpc('fid'));
		$tid = intval(core::gpc('tid'));
		$quickpost = intval(core::gpc('quickpost','P'));
		
		//$this->check_login();
		$this->check_forbidden_group();
		
		$uid = $this->_user['uid'];
		
		if($uid>0){
		    $user = $this->member->read($uid);
			$username = $this->_user['username'];
	    }else{
			$user = $this->_user;
			$username=$_SERVER['ip'];
		}
		$this->check_user_delete($user);
		// hook post_post_user_after.php
		$group = $this->group->read($user['groupid']);
		
		// 帖子存在检查
		$thread = $this->topic->read($fid, $tid);
		$this->check_topic_exists($thread);
		
		// 帖子回复数不能超过 10000
		if($thread['posts'] > 10000) {
			$this->message('该帖子回复数已经达到10000，不能再回复了，再起话题吧！',0);
		}
		// 帖子回复数不能超过 10000
		if($thread['lockout'] == 1) {
			$this->message('帖子被锁定，禁止回复！',0);
		}
		
		// 板块权限检查
		$forum = $this->mcache->read('forum', $fid);
		$this->check_forum_exists($forum);
		$this->check_forum_status($forum);
		$this->check_access($forum, 'post');
		if($forum['user_post']>1){
			$forum_follow=$this->forum_users->check_status($fid,$uid);
			if($forum['user_post']==3 && (!$forum_follow || $forum_follow['status']==1)){
				$this->message('仅限本吧成员发帖',0);
			}
		}
		if(!$this->form_submit()) {
			
			// 附件相关
			$attachlist = $this->get_attachlist_by_tmp($uid);
			$this->init_editor_attach($attachlist, '00');
			
			$this->view->assign('fid', $fid);
			$this->view->assign('tid', $tid);
			$this->view->assign('thread', $thread);
			$this->view->assign('forum', $forum);
			// hook post_post_before.php
			$this->view->display('post_post_ajax.html');
		} else {
			$post = $error = array();
			if($group['verifynum']){
				if(empty($_SESSION)){
				    session_start();	
				}
				$verifynum=strtolower(trim(core::gpc('verifyNum','P')));
				if($verifynum!=$_SESSION['verify']) $this->message('验证码错误！',0);
			}
			$subject = htmlspecialchars(core::gpc('subject', 'P')); // 废弃
			$message = core::gpc('message', 'P');
			$user['groupid']>1 && $message = $this->post->html_safe($message);
			
			$message=$this->message_rep($message,$group['allowlink'],$fid);
			
			// 快速发帖。
			if($quickpost) {
				$this->html_in($message);
				$message = misc::html_space($message);
			}
			
			// -----------> 添加到 post
			$attachnum = $imagenum = 0;
			$page = 1;
			$maxfloor=$this->post->get_maxfloor($tid);
			$floor=$maxfloor+1;
			
			$page = ceil(($thread['posts'] + 1) / $this->conf['pagesize']);
			
			$post = array (
				'tid'=>$thread['tid'],
				'fid'=>$fid,
				'authorid'=>$uid,
				'dateline'=>$_SERVER['time'],
				'postip'=>ip2long($_SERVER['ip']),
				'attachnum'=>0,
				'imagenum'=>0,
				'replies'=>0,
				'rates'=>0,
				'page'=>$page,
				'floor'=>$floor,
				'author'=>$username,
				'subject'=>'',
				'message'=>$message,
			);
			
			$error['message'] = $this->post->check_message($post['message']);
			empty($error['message']) && $error['message'] = $this->check_badword($post['message']);
			
			// hook post_post_after.php
			if(!array_filter($error)) {
				$error = array();
				$error['page'] = $page;
				//@消息
			    $this->conf['at_on']==1 && $this->at($post['message'],"?topic-index-fid-$fid-tid-$tid-page-$page.htm",$floor,$thread['subject']);
				//回帖提醒
				if($this->conf['pm_reply']==1 && $thread['authorid'] && $thread['authorid']!=$uid){
				    $this->pm_reply("?topic-index-fid-$fid-tid-$tid-page-$page.htm",$thread,$floor,$username);
				}
				
				// hook post_topic_post_create_before.php
				$pid = $post['pid'] = $this->post->create($post);
				// hook post_post_post_create_after.php
				
				// 更新 $attach 上传文件的pid
				$aidarr = $this->attachment->get_aid_from_tmp($uid);
                //$coverimg='';
				foreach($aidarr as $fid_aid) {
					$arr = explode('_', $fid_aid);
					$fid = intval($arr[0]);
					$aid = intval($arr[1]);
					$attach = $this->attachment->read($fid, $aid);
					if(empty($attach)) continue;
					if($attach['uid'] != $uid) continue;
					$attach['fid'] = $post['fid'];
					$attach['pid'] = $post['pid'];
					$attach['tid'] = $post['tid'];
					if($attach['isimage'] == 1) {
						$imagenum++;
						//if(empty($coverimg)) $coverimg=$attach['filename'];
					} else {
						preg_match("/\[attach=$aid\|gold=([0-9]+)\](.+?)\[\/attach\]/is",$message,$att);
						if(!empty($att)){
							$attach['golds']=$att[1];
							unset($att); 
							
							$post['message']=preg_replace("/\[attach=$aid\|gold=([0-9]+)\](.+?)\[\/attach\]/is",'',$post['message']);
						}
						$attachnum++;
					}
					$this->attachment->db_cache_update("attachment-fid-$fid-aid-$aid", $attach);
				}
				$this->attachment->clear_aid_from_tmp($uid);
				
				
				// 更新 $post
				$post['attachnum'] = $attachnum;
				$post['imagenum'] = $imagenum;
				$this->post->update($post);
				
				// 更新 $user 用户发帖数，积分
				$user = $this->member->read($uid);
				$user['posts']++;
				$user['credits'] += $this->conf['credits_policy_post'];
				$user['golds'] += $this->conf['golds_policy_post'];
				$groupid = $user['groupid'];
				$user['groupid'] = $this->group->get_groupid_by_credits($user['groupid'], $user['credits']);
				
				// 更新 cookie 如果用户组发生改变，更新用户的 cookie
				if($groupid != $user['groupid']) {
					$this->member->set_login_cookie($user);
				}
				
				// 加入 $mypost
				if(!$this->mypost->have_tid($uid, $fid, $tid)) {
					$this->mypost->create(array('uid'=>$uid, 'fid'=>$fid, 'tid'=>$tid, 'pid'=>$pid));
					$user['myposts']++;
				}
				//加入本吧发帖
				!isset($forum_follow) && $forum_follow=$this->forum_users->check_status($fid,$uid);
				if($forum_follow){
				   $forum_follow['topics']++;
				   $forum_follow['lastpost']=$_SERVER['time'];
				   $this->forum_users->update($forum_follow);	
				}
				
				
				// 更新 $user 
				$this->member->update($user);
					

				// 更新 $forum 版块的总帖数
				$forum = $this->forum->read($fid);
				$forum['posts']++;
				$forum['todayposts']++;
				$forum['lastpost']=$_SERVER['time'];
				//$forum['lasttid'] = $thread['tid'];
				
				
				$this->forum->xupdate($forum);
				
				// 今日总的发帖数
				$this->runtime->xset('posts', '+1');
				$this->runtime->xset('todayposts', '+1');
				

				// 更新 $thread
				$thread['posts']++;
				$thread['lastauthorid'] = $uid;
				$thread['lasttime'] = $_SERVER['time'];
				$thread['lastauthor'] = $username;
				
				//$thread['floortime'] = $this->get_floortime($fid, $thread['floortime'], $group['upfloors']);
/*				if($thread['posts'] <= $this->conf['pagesize']) {
					$thread['pids'] .= ($thread['pids'] ? ','.$pid : $pid);
				}*/
				$this->topic->update($thread);
				

				// hook post_post_succeed.php
				//$this->location("?topic-index-fid-$fid-tid-$tid-page-$page.html");
				$this->topic->format($thread,$page);
				$error['url']=$thread['url'].'?scrollbottom=1';
				
			}
			$this->message($error);
		}
	}
	// 修改 ajax
	public function on_update() {
		$this->_title[] = '修改帖子';
		$this->_nav[] = '修改帖子';
		
		$this->check_login();
		$this->check_forbidden_group();
		
		$fid = intval(core::gpc('fid'));
		$pid = intval(core::gpc('pid'));
		
		$uid = $this->_user['uid'];
		$username = $this->_user['username'];
		$user = $this->member->read($uid);
		$this->check_user_delete($user);
		
		// 版块权限检查
		$forum = $this->mcache->read('forum', $fid);
		$this->check_forum_exists($forum);
		$this->check_access($forum, 'post');
		
		$post = $this->post->read($fid, $pid);
		$this->check_post_exists($post);
		$tid = intval($post['tid']);
		
		$thread = $this->topic->read($fid, $tid);
		$this->check_topic_exists($thread);
		
		$ismod = $this->is_mod($forum, $this->_user);
		// 编辑权限检查：管理员，版主，可以编辑
		if($post['authorid'] != $this->_user['uid']) {
			$this->check_access($forum, 'update');
		}
		
		// 过期不能编辑
		// post_update_expiry
		if(!$ismod && $this->conf['post_update_expiry'] && $_SERVER['time'] - $post['dateline'] > $this->conf['post_update_expiry']) {
			$time = ceil($this->conf['post_update_expiry'] / 60);
			$this->message('您不能再继续修改该帖，已经超出了最大修改时间: (<b>'.$time.'分钟</b>)。', 0);
		}
		
		// 是否为首帖
		$isfirst = $thread['firstpid'] == $pid;
		
		$input = $error = array();
		if(!$this->form_submit()) {
			$post['message_html'] = htmlspecialchars($post['message']);;
			
			// 附件相关
			$attachlist = $this->attachment->get_list_by_fid_pid($fid, $pid, 0);
			$this->init_editor_attach($attachlist,$pid);
			
			if($isfirst) {
				//$this->init_type_select($forum, $thread['typeid1'], $thread['typeid2'], $thread['typeid3'], $thread['typeid4']);
				
				$typearr=array();
				if($forum['typeid']){
				   $typearr=$this->type->get_typearr($forum['typeid']);	
				}
				$this->view->assign('typearr',$typearr);
			}
			
			$this->view->assign('isfirst', $isfirst);
			$this->view->assign('fid', $fid);
			$this->view->assign('tid', $tid);
			$this->view->assign('pid', $pid);
			$this->view->assign('post', $post);
			$this->view->assign('thread', $thread);
			$this->view->assign('forum', $forum);
			$this->view->assign('input', $input);
			$this->view->assign('error', $error);
			// hook post_update_before.php
			$this->view->display('post_update_ajax.html');
			//$this->view->display('__post_update.htm');
		} else {
			
			$subject = htmlspecialchars(core::gpc('subject', 'P'));
			$message = $this->post->html_safe(core::gpc('message', 'P'));
			$tags=core::gpc('tags','P');
			
			// 更新数据
			if($isfirst) {
				
				// 更新 threadtype

				$thread['subject'] = $subject;
				$error['subject'] = $this->topic->check_subject($thread['subject']);
				$typeid=intval(core::gpc('typeid','P'));
			}
			$post['message'] = $message;
			$error['message'] = $this->post->check_message($post['message']);
			
			// hook post_update_after.php
			
			// 如果检测没有错误，则更新
			if(!array_filter($error)) {
				$error = array();
				
				// 更新 $attach 上传文件的pid
				$attachnum = $imagenum = 0;
				$aidarr = $this->attachment->get_aid_from_tmp($uid);
				foreach($aidarr as $fid_aid) {
					$arr = explode('_', $fid_aid);
					$fid = intval($arr[0]);
					$aid = intval($arr[1]);
					
					$attach = $this->attachment->read($fid, $aid);
					if(empty($attach)) continue;
					if($attach['uid'] != $uid) continue;
					$attach['fid'] = $post['fid'];
					$attach['pid'] = $post['pid'];
					$attach['tid'] = $post['tid'];
					if($attach['isimage'] == 1) {
						$imagenum++;
					} else {
						$attachnum++;
					}
					// 修改主键
					$this->attachment->db_cache_update("attachment-fid-$fid-aid-$aid", $attach);
				}
				$this->attachment->clear_aid_from_tmp($uid);
				
				// 删除没有被引用的图片
				$attachlist = $this->attachment->get_list_by_fid_pid($fid, $pid, 1);
				$rebuild_cover = 0;
				foreach($attachlist as $attach) {
					$url = $this->conf['upload_url'].$attach['filename'];
					if($attach['filename'] && strpos($post['message'], $attach['filename']) === FALSE) {
						// 删除没有被引用的附件，有点粗暴，可以理解为 word 的编辑方式，删除的图片需要重新上传。
						$this->attachment->unlink($attach);
						$this->attachment->delete($attach['fid'], $attach['aid']);
						$imagenum--;
						//var_dump('deleted: '.$attach['filename'].', imagenum:'.$imagenum);
					} else {
						//var_dump($attach['filename']);
					}
				}
				
				//var_dump($post['imagenum'].'-'.$imagenum);
				$post['imagenum'] += $imagenum;
				$post['attachnum'] += $attachnum;

				// 如果为主题帖，则更新附件个数
				if($isfirst) {
					$thread['imagenum'] += $imagenum;
					$thread['attachnum'] += $attachnum;
					if($tags){
						$tags=utf8::safe_substr($tags,0,80);
						$tagsarr=explode(" ",$tags);
						$newtags=array();
						$this->tags_data->delete_by_tid($tid);
						foreach($tagsarr as $t){
							$t=misc::safe_str($t);
							if(!empty($t)){
								$t=utf8::safe_substr($t,0,20);
								$tag_id=$this->tags->_create($t,'topics');
								$newtags[]=$t;
								$tag_id && $this->tags_data->_create(array('tid'=>$tid,'fid'=>$fid,'tag_id'=>$tag_id,'dateline'=>$_SERVER['time']));
							}
						}
						$seo_keywords=implode(',',$newtags);
						$tags=implode(' ',$newtags);
					}
            
                    $thread['tags']=$tags;
                    $thread['seo_keywords']+=$seo_keywords;
					//更新分类统计
					if($typeid){
					   if($typeid!=$thread['typeid']){
						   $this->type_count->inc($fid,$typeid);
						   $this->type_count->dec($fid,$thread['typeid']);
					   }
					}elseif($thread['typeid']){
						$this->type_count->dec($fid,$thread['typeid']);
					}
					$thread['typeid']=$typeid;
				}
				// hook post_update_thread_update_before.php
				$this->topic->update($thread);
				$this->post->update($post);
				// hook post_update_thread_update_after.php
				
				//$this->forum->xupdate($forum);
				$this->topic->format($thread);
				// hook post_update_succeed.php
				$error['url']=$thread['url'];
				$this->message($error);
			}
			$this->message($error);
		}
	}


	// 默认顶贴升几楼？ get_floortime($fid, $thread['floortime'], $group['upfloors']);
	private function get_floortime($fid, $floortime, $upfloors) {
		if(empty($upfloors)) {
			return $_SERVER['time'];
		}
		$tids = $this->thread->index_fetch_id(array('fid'=>$fid, 'floortime'=>array('>'=>$floortime)), array('floortime'=>1), 0, $upfloors);
		$key = array_pop($tids);
		if(empty($key)) {
			return $_SERVER['time'];
		} else {
			$thread = $this->thread->db_cache_get($key);
			return $thread['floortime'] + 1;
		}
	}
	
	private function get_attachlist_by_tmp($uid) {
		$file = $this->conf['tmp_path'].$uid.'_aids.tmp';
		$aids = is_file($file) ? trim(file_get_contents($file)) : '';
		$aidarr = $aids ? explode(' ', $aids) : array();
		$attachlist = array();
		foreach($aidarr as $aid) {
			$attach = $this->attachment->read($aid);
			$this->attachment->format($attach);
			$attachlist[$aid] = $attach;
		}
		return $attachlist;
	}
		
	private function init_editor_attach($attachlist, $pid) {
		$attachnum = count($attachlist);
		$this->view->assign('attachlist', $attachlist);
		$this->view->assign('attachnum', $attachnum);
		$upload_max_filesize = $this->attachment->get_upload_max_filesize();
		$this->view->assign('upload_max_filesize', $upload_max_filesize);
		$filetyps = core::json_encode($this->attachment->filetypes);
		$this->view->assign('filetyps', $filetyps);
		$this->view->assign_value('pid', $pid);// 给编辑器附件列表使用
	}

   private function message_rep($str,$a=false,$fid=0){
	    $search = array (
		            "/<a[^>]+>(.+?)<\/a>/is",//去除超链接
					//"/\[attach=([0-9]+)\|gold=([0-9]+)\](.+?)\[\/attach\]/is",
					);
	    $replace = array (
		            "\\1",
					//'<a href="?attachment-download-aid-\\1.htm" target="_blank">\\3</a><span style="color:#666">(金币：<span id="attach_gold_\\1">\\2</span>  大小：<span id="attach_size_\\1"></span> 下载：<span id="attach_download_\\1"></span> 时间：<span id="attach_time_\\1"></span>)</span>',
					//'<a href="?attachment-dialog-fid-'.$fid.'-aid-\\1-ajax-1.htm" class="ajaxdialog" ajaxdialog="{showtitle: false, cache: true, position: 6, modal: false}" onclick="return false;" target="_blank" rel="nofollow">\\3</a><span style="color:#666">(金币：<span id="attach_gold_\\1">\\2</span>  大小：<span id="attach_size_\\1"></span> 下载：<span id="attach_download_\\1"></span> 时间：<span id="attach_time_\\1"></span>)</span>',
					);	
	    if($a){unset($search[0],$replace[0]);}						  
        $str=@preg_replace ($search, $replace, $str);
        return $str;
	
  }
  
  //编辑器图片在线管理
  public function on_myimage(){
	    $uid = $this->_user['uid'];
		$action = htmlspecialchars( $_POST[ "action" ] );
    if ( $action == "get" ) {
	  // 附件相关
		$attachlist = $this->get_attachlist_by_tmp($uid);
		$str = "";
        foreach ( $attachlist as $file ) {
            $str .= $file['filename'] . "ue_separate_ue";
        }
        echo $str;
	}
		//$this->init_editor_attach($attachlist, '00');
	  
  }
  
  private function html_in(&$str,$a=false)
{
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
					 "'<iframe[^>]*?>.*?</iframe>'si", // 去掉iframe
					 "/<a[^>]+>(.+?)<\/a>/is",//去除超链接
					);
	$replace = array ("",
					  "",
					  "\\1",
					);	
	if($a){unset($search[3],$replace[3]);}						  
   $str=@preg_replace ($search, $replace, $str);
   $str=htmlspecialchars($str);
   	if(!get_magic_quotes_gpc()) 
	{
  	  $str = addslashes($str);
	}
   //return $str;
}
// tpdo: 删除帖子，删除主题, todayposts 未更新
public function on_delete() {
		$this->_title[] = '删除帖子';
		$this->_nav[] = '删除帖子';
		
		// 检查是否为 post 提交
		/*if(!core::gpc('formhash', 'P')) {
			$this->message('非法请求！');
		}*/
		
		$this->check_login();
		$this->check_forbidden_group();
		
		$pid = intval(core::gpc('pid'));
		$fid = intval(core::gpc('fid'));
		
		$uid = $this->_user['uid'];
		$username = $this->_user['username'];
		$user = $this->member->read($uid);
		$this->check_user_delete($user);
		
		// 版块权限检查
		$forum = $this->mcache->read('forum', $fid);
		$this->check_forum_exists($forum);
		$this->check_access($forum, 'thread');
		
		$post = $this->post->read($fid, $pid);
		$this->check_post_exists($post);
		$tid = $post['tid'];
		
		$thread = $this->topic->read($fid, $tid);
		$this->check_topic_exists($thread);
		
		// 编辑权限检查：管理员，版主，可以编辑
		if($post['authorid'] != $this->_user['uid']) {
			$this->check_access($forum, 'delete');
		}
		
		$isfirst = $thread['firstpid'] == $pid;
		$forum=$this->forum->read($fid);
		
	   $this->modlog->create(array(
					'uid'=>$this->_user['uid'],
					'username'=>$this->_user['username'],
					'fid'=>$fid,
					'tid'=>0,
					'pid'=>0,
					'subject'=>$thread['subject'],
					'credits'=>0,
					'golds'=>0,
					'dateline'=>$_SERVER['time'],
					'action'=>'delete',
					'comment'=>'',
				));

		if($isfirst) {
			
			// hook post_delete_post_before.php
			$this->topic->xdelete($fid, $tid, TRUE);	// 删除 $postlist, 更新 $forum $userlist
			// hook post_delete_post_after.php
			
			$forum['posts'] -= $thread['posts'];
			$forum['topics']--;
			$this->forum->xupdate($forum);
			
			
				
			$this->message('删除成功',1,"?forum-index-fid-$fid.htm");
			//$this->location("?forum-index-fid-$fid.htm");
			
		} else {
			
			// hook post_delete_thread_before.php
			$this->post->xdelete($fid, $pid, TRUE);
			// hook post_delete_thread_after.php
			
			$forum['posts']--;
			$this->forum->xupdate($forum);
			
			// 重建页数
			$this->post->rebuild_page($fid, $tid, $pid, $post['page']);
			$this->message('删除成功');
			//$this->location("?topic-index-fid-$fid-tid-$tid-page-$post[page].htm");
		}
	}
	//@提醒
	private function at(&$message,$url,$floor,$subject){
		//$url="?topic-index-fid-$fid-tid-$tid-page-$page.htm";
		$preg = '/\@(.*)[\s+\&\<]/U';
		preg_match_all($preg, $message, $ats);
		if(!empty($ats[1])){
			$num=3;
			$ats[1]=array_unique($ats[1]);
			if($num>count($ats[1])) $num=count($ats[1]);
			
			$i=1;
			foreach($ats[1] as $v)
			{
				if(empty($v)) continue;
				$atusername=strip_tags($v);
				misc::safe_str($atusername);
				$rs=$this->member->get_user_by_username($atusername);
				if(!empty($rs)&&$rs['uid']!=$this->_user['uid'])
				{
				   $pat=array('/(@'.$v.')/');
				   $rep=array('<a href="?you-index-uid-'.$rs['uid'].'.htm" target="_blank" class="cblue">\\1</a>');
				   $message=preg_replace($pat,$rep,$message,1);
					
					// 发送系统消息：
				  $pmsubject = '在帖子《'.utf8::substr($subject,0,30).'》中有人提到你';;
				  $pmmessage = '有人在帖子《<a href="'.$url.'#floor_'.$floor.'" target="_blank">'.$subject.'</a>》中@了你，赶快去看看吧。<a href="'.$url.'#floor_'.$floor.'"  target="_blank">'.$url.'</a> 楼层：'.$floor.'楼';
				  $this->pm->system_send($rs['uid'], $rs['username'], $pmmessage);
				  $i++;
				  if($i>=$num) break;
				}else{
				   continue;
				}
				
			}
		    
		}
		//return $message;
	}
	//回帖提醒
	private function pm_reply($url,$topic,$floor,$username){
		$pmsubject = '您的帖子《'.utf8::substr($topic['subject'],0,30).'》有新回复';;
		$pmmessage = $username.'回复了您的帖子《<a href="'.$url.'#floor_'.$floor.'" target="_blank">'.$topic['subject'].'</a>》，赶快去看看吧。<a href="'.$url.'#floor_'.$floor.'"  target="_blank">'.$url.'</a>';
		$this->pm->system_send($topic['authorid'], $topic['author'], $pmmessage);
	}
	//hook post_control_after.php
}
//html代码输入


?>