<?php
/**************************************************
*  Created:  2010-08-19
*
*  crond
*
*  @Xweibo (C)1996-2099 SINA Inc.
*  @Author zhenquan<zhenquan@staff.sina.com.cn>
*
***************************************************/
class crond {

	function crond()
	{
		$this->db = APP::ADP('db');
	}

	function default_action() {
		$this->follow();
	}
	
	/**
	 * 定时出sina关注10TOP
	 *
	 */
	function follow()
	{
		$time_fragments = 1800;
		$file = P_VAR_LOCK . '/' . CRON_LOCK_FILE_PREFIX . 'follow_count';

		if (file_exists($file)) {
			$rs = file_get_contents($file);
			if (!empty($rs)) {
				$flag = explode('|', $rs);
				$flag[0] = (int)$flag[0];
				if ($flag[0] + $time_fragments > time()) {
					exit;
				}
			}
		}
		// lock
		if (!is_dir(P_VAR_LOCK)) {
			if (!@mkdir(P_VAR_LOCK)) {
				exit(P_VAR_LOCK . ' not exists.');
			}
		}
		$flag = array(isset($flag) ? $flag[0] : time(), 1);
		file_put_contents($file, implode('|', $flag));
		$flag[1] = 0;

		//实例化微博api
		$wb = APP::N('weibo');
		set_time_limit(0);

		$q = array(
						'q' => 'a',
						'sdomain' => 1,
						'sort' => '2',
						'count' =>20,
						'page' => 1
						);

		//$o = App::N('oAuthReq');
		$ord = ord('a');
		$data = array();
		// disable some acc
		$disabled_uid = array(
			1640601392,
			1638629382,
			1638782947,
			1642591402,
			1671526850,
			1687503652,
			1653689003,
			1618051664,
			1642909335,
			1668216997,
			1668217657,
			1654164742
			);

		for ($i=0; $i<26; $i++) {
			$q['q'] = chr($ord + $i);
			$rs = $wb->searchUser($q);
			foreach ($rs as $row) {
				if (in_array($row['id'], $disabled_uid)) {
					continue;
				}
				$data[] = '("' . $row['id']. '","' .$row['screen_name'] . '","' . $row['followers_count'] . '")';
			}
		}
		if (sizeof($data)) {
			$this->db->execute('truncate `' .DB_PREFIX . T_FOLLOWERS_COUNT. '`');
			$sql = 'INSERT ignore INTO `' . DB_PREFIX . T_FOLLOWERS_COUNT . '`(uid, screen_name, followers_count) VALUES' . implode(',', $data);
			$this->db->execute($sql);

			if ($err = $this->db->getError()) {

			} else {
				$flag[0] = time();
			}
			$this->db->close();
		}
		file_put_contents($file, implode('|', $flag));
	}
}
