<?php
!defined('FRAMEWORK_PATH') && exit('FRAMEWORK_PATH not defined.');

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

class api_control extends common_control {
	
	function __construct(&$conf) {
		parent::__construct($conf);
	}
	public function on_topic(){
		$id=intval(core::gpc('id'));
		$f=core::gpc('f');
		
		$api=$this->api->read($id);
		!$api && exit('error:1');
		
		$this->api->format($api);
		if($api['cache'] && $_SERVER['time']<$api['updatetime']){
			$tids=json_decode($api['data']);
			$list=$this->topic->mget($tids);
		}else{
			$cond=array();
			intval($api['fid'])>0 && $cond['fid']=$api['fid'];
			if($api['digest']>0){
				if($api['digest']==1){
					$cond['digest']=array('digest'=>array('>'=>0));
				}else{
					$cond['digest']=$api['digest']-1;
				}
			}
			$api['top']>0 && $cond['top']=$api['top'];
			$api['typeid']>0 && $cond['typeid']=$typeid;
			
			$order=$api['rank']==1?'lasttime':($api['rank']==2?'posts':'dateline');
			$order=array($order=>-1);
			$limit=$api['num']>0?$api['num']:10;
			$list=$this->topic->index_fetch($cond,$order,0,$limit);
		}
		
		$nlist=$tids=array();
		foreach($list as $v){
			$this->topic->format($v);
			$nlist[$v['tid']]=array(
			    'fid'=>$v['fid'],
				'tid'=>$v['tid'],
				'forumname'=>$v['forumname'],
				'forumurl'=>$v['forumurl'],
				'subject'=>$v['subject'],
				'url'=>$v['url'],
				'posts'=>$v['posts'],
				'dateline'=>$v['dateline_fmt'],
				'lasttime'=>$v['lasttime_fmt'],
				'coverimg'=>$v['coverimg'],
			);
			$tids[]=array($v['fid'],$v['tid']);
		}
		
		if($api['cache'] && $_SERVER['time']>$api['updatetime']){
			$api2=$this->api->read($id);
			$api2['data']=core::json_encode($tids);
			$api2['updatetime']=$_SERVER['time']+$api['cache'];
			$this->api->update($api2);
		}
		
		if($f=='json'){
		   echo core::json_encode($nlist);
		   exit;	
		}
		ob_start();
		$this->view->assign('list',$nlist);
		$this->view->display('api_topic.html');
		$body = ob_get_contents();
		ob_end_clean();
		
        echo 'document.write("'.addslashes($body).'")';
	}
	
}

?>