1/**
2 * 博客、文章访问量缓存
3 * useage: makeCount(int 博客ID [, int 文章ID [, int 更新间隔(1800s) [, int 博客访问量 [, int 文章访问量]]]] )
4 * @author MrAsong 2012-04-26
5 */
6function makeCount($bid=1, $pid=0, $update_interval=1800, $num_home=50, $num_post=15){
7 global $wpdb;
8
9 $count_file = ABSPATH . 'cache/blogcount_'.$bid.'.js' ;
10
11 if( $json = @file_get_contents($count_file) ){
12 $c = json_decode($json,true); //获取数据
13 }else{ //如果不存在,创建count文件
14 $c = array(
15 'create' => time(), //上次更新时间
16 'blogcount' => 0
17 );
18 }
19
20 if( $pid == 0 ){ // 判断是否为首页
21 $c['blogcount'] = $c['blogcount'] + 1 ; //count+1
22
23 if( $c['blogcount'] >= $num_home && (time()-$c['create']) > $update_interval ){//更新博客访问量
24 $sql = "UPDATE $wpdb->blogs SET count=count+{$c['blogcount']} WHERE blog_id=$bid";
25 $wpdb->query($sql);
26 $c['create'] = time();
27 $c['blogcount'] = 0;
28 }
29 }else{
30 $c['post'][$pid]['c'] = isset($c['post'][$pid]['c']) ? ($c['post'][$pid]['c'] + 1) : 1 ;
31 $c['post'][$pid]['t'] = isset($c['post'][$pid]['t']) ? $c['post'][$pid]['t'] : time();
32 if( $c['post'][$pid]['c'] >= $num_post && (time()-$c['post'][$pid]['t']) > $update_interval ){//更新博客访问量
33 $sql = "UPDATE $wpdb->posts SET count=count+{$c['post'][$pid]} WHERE ID=$pid";
34 $wpdb->query($sql);
35 unset($c['post'][$pid]); //删除此元组
36 }
37 }
38
39 if($fp = @fopen($count_file, 'wb')) {
40 @fwrite( $fp, json_encode($c) );//写入json
41 fclose($fp);
42 }
43
44}