<?php

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

class topic extends base_model {
	
	function __construct(&$conf) {
		parent::__construct($conf);
		$this->table = 'topic';
		$this->primarykey = array('fid', 'tid');
		$this->maxcol = 'tid';
	}
    public function get_topiclist_by_fid($fid, $orderby, $start, $limit, $total = 0) {
		$cond = array('fid'=>$fid);
		//hook model_topic_get_topiclist_by_fid_start.php
		// 优化大数据翻页，倒排
		if($start > 1000 && $total > 2000 && $start > $total / 2) {
			$start = $total - $start;
			$orderby = $orderby == 0 ? array('lasttime'=>1) : array('tid'=>1);
			$threadlist = $this->index_fetch($cond, $orderby, max(0, $start - $limit), $limit);
			$threadlist = array_reverse($threadlist, TRUE);
			return $threadlist;
		} else {
			$orderby = $orderby == 0 ? array('lasttime'=>-1) : array('tid'=>-1);
			$threadlist = $this->index_fetch($cond, $orderby, $start, $limit);
			return $threadlist;
		}
	}
	// 基本删除
	public function _delete($fid, $tid) {
		$return = $this->delete($fid, $tid);
		// count 为强关联
		if($return) {
			$this->count('-1');
		}
		return $return;
	}
	
	// ------------------> 杂项
	public function check_subject(&$subject) {
		if(empty($subject)) {
			return '标题不能为空。';
		}
		if(utf8::strlen($subject) > 200) {
			return '标题不能超过 200 字，当前长度：'.strlen($subject);
		}
		return '';
	}
	// 用来显示给用户
	public function format(&$thread,$page=1,$forum=array()) {
		if(empty($thread)) return;

		empty($forum) && $forum=$this->mcache->read('forum',$thread['fid']);

		$thread['forumname'] =$forum['name'] ;//isset($miscarr['forum'][$thread['fid']]) ? $miscarr['forum'][$thread['fid']] : '';
		$thread['forumurl']=$forum['url'];
		$thread['dateline_fmt']=misc::humandate($thread['dateline'], $this->conf['timeoffset']);
		$thread['lasttime_fmt']=misc::humandate($thread['lasttime'], $this->conf['timeoffset']);
		$thread['posts_fmt'] = max(0, $thread['posts'] - 1);	// 用来前端显示
		$thread['tags_fmt']=explode(' ',$thread['tags']);
		
		
		if($page>1){
			$url_topic=substr($this->conf['url_topic'],stripos($this->conf['url_topic'],'|')+1);
		    $url_topic=$this->conf['app_url'].$url_topic;
			$thread['url']=$this->conf['urlrewrite']?str_replace(array('[fid]','[tid]','[page]'),array($thread['fid'],$thread['tid'],$page),$url_topic):$this->conf['app_url'].'?topic-index-fid-'.$thread['fid'].'-tid-'.$thread['tid'].'.htm';
		}else{
			$url_topic=substr($this->conf['url_topic'],0,stripos($this->conf['url_topic'],'|'));
		    $url_topic=$this->conf['app_url'].$url_topic;
			$thread['url']=$this->conf['urlrewrite']?str_replace(array('[fid]','[tid]'),array($thread['fid'],$thread['tid']),$url_topic):$this->conf['app_url'].'?topic-index-fid-'.$thread['fid'].'-tid-'.$thread['tid'].'.htm';
		}
		
		// 精华 火帖 新帖 老帖
		if($thread['digest'] > 0) {
			$thread['color'] = "thread-digest-$thread[digest]";
		} elseif($thread['posts'] > $this->conf['threadlist_hotviews']) {
			$thread['color'] = "thread-hot";
		// 24小时产生的帖子为新帖
		} elseif($_SERVER['time'] - $thread['dateline'] < 86400) {
			$thread['color'] = "thread-new";
		} else {
			$thread['color'] = "thread-old";
		}
		$thread['coverimg'] && stripos($thread['coverimg'],'http')===false && $thread['coverimg']=$this->conf['upload_url'].'attach/'.$thread['coverimg'];
		if($thread['top'] > 0) {
			$thread['top_fmt']=$thread['top']==3?'<font class="clr-org">[全站置顶]</font>':'<font class="clr-org">[置顶]</font>';
			$thread['icon'] = "icon-top-$thread[top]";
		} elseif($thread['digest'] > 0) {
			$thread['digest_fmt']='<font class="clr-green">[精华]</font>';
			$thread['icon'] = "icon-digest-$thread[digest]";
		} elseif($thread['color'] == 'thread-new') {
			$thread['icon'] = "icon-post-blue";
		} elseif($thread['color'] == 'thread-old') {
			$thread['icon'] = "icon-post-grey";
		} elseif($thread['color'] == 'thread-hot') {
			$thread['icon'] = "icon-post-red";
		}
	}
	public function get_newlist($where=array(),$limit){
		$limit2 = $limit * 3;	// 去重
		$digestlist = $this->index_fetch($where, array('tid'=>-1), 0, $limit2);
		$newlist = array();
		foreach($digestlist as $k=>$digest) {
			if(isset($newlist[$digest['tid']])) continue;
			$this->format($digest);
			$newlist[$digest['tid']] = $digest;
		}
		$newlist = array_slice($newlist, 0, $limit);
		return $newlist;
	}
	public function get_hotlist($where=array(),$limit){
		$limit2 = $limit * 3;	// 去重
		$digestlist = $this->index_fetch($where, array('posts'=>-1), 0, $limit2);
		$newlist = array();
		foreach($digestlist as $k=>$digest) {
			if(isset($newlist[$digest['tid']])) continue;
			$this->format($digest);
			$newlist[$digest['tid']] = $digest;
		}
		$newlist = array_slice($newlist, 0, $limit);
		return $newlist;
	}
	// 调用别的model->xdelete 时要特别小心，确定 xdelete 不会相互依赖！
	// 调用次函数以后，最好再调用 $this->clear_forum_cache();
	public function xdelete($fid, $tid, $updatestat = TRUE,$rc=0) {
		// 加载配置
		if(!isset($this->conf['credits_policy_post'])) {
			$this->conf += $this->kv->xget('conf_ext');
		}
		
		$forum = $this->forum->read($fid);
		$thread = $this->topic->read($fid, $tid);
		$user = $this->member->read($thread['authorid']);
		$uid = $thread['authorid'];
		
		// 受影响的值。
		$default_user = array('topics'=>0, 'posts'=>0, 'digests'=>0, 'credits'=>0,'golds'=>0, 'myposts'=>0);
		$default_forum = array('topics'=>0, 'posts'=>0, 'digests'=>0, 'todayposts'=>0);
		$return = array(
			'forum'=> array($fid=>$default_forum),
			'user' => array($uid=>$default_user)
		);
		$rforum = &$return['forum'][$fid];
		$ruser = &$return['user'];
		
		// 算出分页，一页一页的删除
		$pagesize = $this->conf['pagesize'];
		$pagenum = ceil($thread['posts'] / $pagesize);
		$todayposts=0;
		for($i = 1; $i <= $pagenum; $i++) {
			$postlist = $this->post->index_fetch(array('fid'=>$fid, 'tid'=>$tid, 'page'=>$i), array(), 0, $pagesize);
			foreach($postlist as $post) {
				
				
				!isset($ruser[$post['authorid']]) && $ruser[$post['authorid']] = $default_user;
				
				// 删除 attach image
				$post['attachnum'] && $this->attachment->xdelete($post['fid'], $post['pid']);
				$post['imagenum'] && $this->attachment->xdelete($post['fid'], $post['pid']);
				
				// 删除 mypost，删除主题一定不会空删除
				$this->mypost->_delete($post['authorid'], $post['fid'], $post['pid']);
				
				$ruser[$post['authorid']]['myposts']++;
				
				$post['dateline'] > $_SERVER['time_today'] && $todayposts++;
				// 删除 $post
				$this->post->_delete($post['fid'], $post['pid']);
				
				/*// 删除 reply
				list($r, $replies) = $this->reply->delete_by_fid_pid($post['fid'], $post['pid']);
				foreach($r as $_uid=>$arr) {
					!isset($ruser[$_uid]) && $ruser[$_uid] = $default_user;
					$ruser[$_uid]['replies'] += $arr['replies'];
					$ruser[$_uid]['credits'] += $arr['credits'];
					$ruser[$_uid]['golds'] += $arr['golds'];
					$rforum['replies'] += $replies;
				}*/
				
				$ruser[$post['authorid']]['posts']++;
				$ruser[$post['authorid']]['credits'] += $this->conf['credits_policy_post'];
				$ruser[$post['authorid']]['golds'] += $this->conf['golds_policy_post'];
				
			}
		}
		// 发表主题的积分策略不同于回帖的策略。
		$ruser[$uid]['credits'] += $this->conf['credits_policy_thread'];
		$ruser[$uid]['golds'] += $this->conf['golds_policy_thread'];
		if($thread['digest'] > 0) {
			$ruser[$uid]['digests']++;
			$ruser[$uid]['credits'] += $this->conf['credits_policy_digest_'.$thread['digest']];
			$ruser[$uid]['golds'] += $this->conf['golds_policy_digest_'.$thread['digest']];
		}
		
		$ruser[$uid]['topics']++;
		
		$rforum['topics']++;
		$rforum['posts'] += $thread['posts'];
		$rforum['todayposts'] += $todayposts;
		$thread['digest'] > 0 && $rforum['digests']++;
		
		/*/ 删除精华
		if($thread['digest'] > 0) {
			$rforum['digests']++;
			$this->digest->delete_by_fid_tid($fid, $tid);
			
			// 用户积分，精华数
			$ruser[$uid]['digests']++;
			$ruser[$uid]['credits'] += $this->conf['credits_policy_digest_'.$thread['digest']];
			$ruser[$uid]['golds'] += $this->conf['golds_policy_digest_'.$thread['digest']];
		}
		
		// 删除置顶
		if($thread['top']) {
			$pforum = $this->forum->read($forum['fup']);
			$thread['top'] == 1 && $this->thread_top->delete_top_1($forum, array("$fid-$tid"));
			$thread['top'] == 2 && $this->thread_top->delete_top_2($forum, array("$fid-$tid"), $pforum);
			$thread['top'] == 3 && $this->thread_top->delete_top_3($forum, array("$fid-$tid"), $runtime);
		}*/
		// 删除置顶
		if($thread['top']) {
			$thread['top'] == 1 && $this->topic_top->delete_top_1($forum, array("$fid-$tid"));
			$thread['top'] == 3 && $this->topic_top->delete_top_3(array("$fid-$tid"));
		}
		//更新分类统计
		if($thread['typeid']){
		   $this->type_count->dec($fid,$thread['typeid']);
		}
		// 删除主题
		$this->topic->_delete($fid, $tid);
		// 删除图片主题
		//$this->topic_position->delete($tid);
		$this->topic_digest->delete($tid);
		// 删除 topic_subject
		$this->topic_subject->delete($thread['tid']);
		
		$this->tags_data->delete_by_tid($tid);
		// modlog
		$this->modlog->delete_by_fid_tid($fid, $tid);
		//topic_pic
		$thread['coverimg'] && $this->topic_pic->delete($fid,$tid);
		// 更新 runtime
		$this->runtime->xset('threads', '-1');
		$this->runtime->xset('posts', '-'.$thread['posts']);
		$this->runtime->xset('todayposts', '-'.$todayposts);
		
		if($updatestat) {
			$this->xdelete_update($return);
			
			/*/ 更新最后发帖，直接清零
			if($forum['lasttid'] == $tid) {
				$forum['lasttid'] = 0;
				$forum['lastuid'] = 0;
				$forum['lastusername'] = '';
				$forum['lastsubject'] = '';
			}*/
		}
		
		/*/ 更新主题分类数
		if($thread['typeid'] > 0) {
			$thread_type = $this->thread_type->read($thread['typeid']);
			$thread_type['threads']--;
			$this->thread_type->update($thread['typeid'], $thread_type);
		}*/
		
		return $return;
	}
	
	// 合并返回值，用户删除板块时候，合并主题。
	public function xdelete_merge_return(&$return, &$return2) {
		foreach($return2['user'] as $uid=>$arr) {
			if(!$uid) continue;
			if(!isset($return['user'][$uid])) { $return['user'][$uid] = $arr; continue; }
			$return['user'][$uid]['topics'] += $arr['topics'];
			$return['user'][$uid]['posts'] += $arr['posts'];
			//$return['user'][$uid]['replies'] += $arr['replies'];
			$return['user'][$uid]['myposts'] += $arr['myposts'];
			$return['user'][$uid]['digests'] += $arr['digests'];
			$return['user'][$uid]['credits'] += $arr['credits'];
			$return['user'][$uid]['golds'] += $arr['golds'];
		}
		foreach($return2['forum'] as $fid=>$arr) {
			if(!$fid) continue;
			if(!isset($return['forum'][$fid])) { $return['forum'][$fid] = $arr; continue; }
			$return['forum'][$fid]['topics'] += $arr['topics'];
			$return['forum'][$fid]['posts'] += $arr['posts'];
			//$return['forum'][$fid]['replies'] += $arr['replies'];
			$return['forum'][$fid]['digests'] += $arr['digests'];
			$return['forum'][$fid]['todayposts'] += $arr['todayposts'];
		}
	}
	
	// 关联删除后的更新
	public function xdelete_update($return) {
		// 更新回复用户的积分
		if(isset($return['user'])) {
			foreach($return['user'] as $uid=>$arr) {
				if(!$uid) continue;
				$user = $this->member->read($uid);
				if(empty($user)) continue;
				$user['topics'] -= $arr['topics'];
				$user['posts'] -= $arr['posts'];
				//$user['replies'] -= $arr['replies'];
				$user['myposts'] -= $arr['myposts'];
				//$user['digests'] -= $arr['digests'];
				$user['credits'] -= $arr['credits'];
				$user['golds'] -= $arr['golds'];
				$this->member->update($user);
			}
		}
		
		if(isset($return['forum'])) {
			foreach($return['forum'] as $fid=>$arr) {
				
				if(!$fid) continue;
				$forum = $this->forum->read($fid);
				if(empty($forum)) continue;
				$forum['topics'] -= $arr['topics'];
				$forum['posts'] -= $arr['posts'];
				$forum['todayposts'] -= $arr['todayposts'];
				$forum['digests'] -= $arr['digests'];
				$this->forum->xupdate($forum);
				//$this->forum->update_last($fid);
				//$this->runtime->xupdate('forumarr');
			}
		}
	}
	
}
?>