<?php

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

/*
	点击服务器，默认采用 mysql/mongodb 作为存储，如果有独立服务器，建议使用 xiuno clickd.

	GET 参数:
	/?r=1,2,3&w=1,2,3
	
	返回 JSON 格式：
	var xn_json = {"1":"100","2":"101","3":"1000"}
	
*/

// 调试模式: 1 打开，0 关闭
define('DEBUG', 0);

// 应用根目录
define('POST_PATH', str_replace('\\', '/', substr(__FILE__, 0, -24)));

// check robot
// check robot
$conf = include POST_PATH.'conf/conf.php';

define('FRAMEWORK_PATH', POST_PATH.'core/xiunophp/');
define('FRAMEWORK_TMP_PATH', $conf['tmp_path']);
define('FRAMEWORK_LOG_PATH', $conf['log_path']);

include FRAMEWORK_PATH.'core.php';
core::init();
core::ob_start();

if(misc::is_robot()) {
	header("HTTP/1.0 403 Forbidden");
	exit;
}

$mthread_views = core::model($conf, 'topic_views');

// read
$tids = array();
$r = isset($_GET['r']) ? $_GET['r'] : '';
$r && $tids = explode(',', $r);

// 过滤
foreach($tids as &$_tid) {
	list($cid,$tid)=explode('_',$_tid);
	
	//$_tid =intval($cid) .'_'. intval($tid);
	$_tid =array(intval($cid) , intval($tid));
}
$tids = array_filter($tids);
if(count($tids) > 100) {
	$tids = array_slice($tids, 0, 100);
}

if(!empty($tids)) {
	$arr = $mthread_views->mget($tids);
	$s = '';
	foreach($arr as $k=>$v) {
		if(empty($v)) {
			list($_, $_, $fid,$_,$tid) = explode('-', $k);
			//$tid = intval($tid);
			$s .= ',"'.$tid.'":'.'"1"';
		} else {
			$s .= ',"'.$v['tid'].'":'.'"'.$v['views'].'"';
		}
	}
	$s = '{'.substr($s, 1).'}';
	$s = "var xn_json = $s;";
	echo $s;
} else {
	echo "var xn_json = {};";
}

$tids = array();
$w = isset($_GET['w']) ? $_GET['w'] : '';
$w && $tids = explode(',', $w);
foreach($tids as &$_tid) {
	list($fid,$tid)=explode('_',$_tid);
	$_tid =array(intval($fid) , intval($tid));
}
if(!empty($tids)) {
	$time=$_SERVER['time'];
	$arr = $mthread_views->mget($tids);

	foreach($arr as $k=>$v) {
		if(empty($v)) {
			//$k=topic_views-fid-10-tid-253;
			list($_, $_, $fid,$_,$tid) = explode('-', $k);
			//list($cid,$_tid2)=explode('_',$tid);
			$v = array('fid'=>$fid,'tid'=>$tid,'views'=>1,'yesterdayviews'=>0,'dayviews'=>1,'weekviews'=>1,'monthviews'=>1,'updatetime'=>$time);
			$mthread_views->create($v);
		} else {	
			$views = $v['views'] + 1;
	        $yesterdayviews = (date('Ymd', $v['updatetime']) == date('Ymd', strtotime('-1 day'))) ? $v['dayviews'] : $v['yesterdayviews'];
	        $dayviews = (date('Ymd', $v['updatetime']) == date('Ymd', $time)) ? ($v['dayviews'] + 1) : 1;
	        $weekviews = (date('YW', $v['updatetime']) == date('YW', $time)) ? ($v['weekviews'] + 1) : 1;
	        $monthviews = (date('Ym', $v['updatetime']) == date('Ym', $time)) ? ($v['monthviews'] + 1) : 1;
	        $v1 = array('views'=>$views,'yesterdayviews'=>$yesterdayviews,'dayviews'=>$dayviews,'weekviews'=>$weekviews,'monthviews'=>$monthviews,'updatetime'=>$time);
			$v=array_merge($v,$v1);
			$mthread_views->update($v);
		}
	}
}

?>