- <?php
-
- /**
- *
- * User: shikiliu
- * Date: 14-8-27
- */
-
- class ActiveDate
- {
-
-
- private $redisConf = array('host' => 'localhost', 'port' => 6379);
-
- private $redis = null;
-
- private $userPrefix = 'user_active_';
-
-
- /**
- * 設(shè)置用戶某天登錄過
- */
- public function setActiveDate($userId, $time = null)
- {
-
- if (emptyempty($time)) {
-
- $time = time();
- }
-
- $redis = $this->getRedis();
-
- $redis->setBit($this->userPrefix . $userId . '_' . date('Y-m', $time), intval(date('d', $time)) - 1, 1);
-
- return true;
- }
-
-
- /**
- * 得到用戶本月登錄天數(shù)
- * redis >= 2.6.0 才可以
- */
- public function getActiveDatesCount($userId, $time = null){
-
- if (emptyempty($time)) {
-
- $time = time();
- }
-
- $redis = $this->getRedis();
-
- return $redis->bitcount($this->userPrefix . $userId . '_' . date('Y-m', $time));
-
- }
-
-
- /**
- * 得到用戶某月所有的登錄過日期
- */
- public function getActiveDates($userId, $time = null)
- {
-
-
- $result = array();
-
- if (emptyempty($time)) {
-
- $time = time();
- }
-
- $redis = $this->getRedis();
-
- $strData = $redis->get($this->userPrefix . $userId . '_' . date('Y-m', $time));
-
- if (emptyempty($strData)) {
- return $result;
- }
-
- $monthFirstDay = mktime(0, 0, 0, date("m", $time), 1, date("Y", $time));
-
- $maxDay = cal_days_in_month(CAL_GREGORIAN, date("m", $time), date("Y", $time));
-
- $charData = unpack("C*", $strData);
-
- for ($index = 1; $index <= count($charData); $index++) {
-
- for ($bit = 0; $bit < 8; $bit++) {
-
- if ($charData[$index] & 1 << $bit) {
-
- //$intervalDay = ($index - 1) * 8 + 8-$bit;
- $intervalDay = $index * 8 -$bit;
- //如果數(shù)據(jù)有大于當(dāng)月最大天數(shù)的時(shí)候
- if ($intervalDay > $maxDay) {
-
- return $result;
-
- }
-
- $result [] = date('Y-m-d', $monthFirstDay + ($intervalDay-1) * 86400);
-
- }
-
- }
-
- }
-
- return $result;
-
-
- }
-
-
- /**
- * redis連接
- */
- private function getRedis()
- {
-
- if (emptyempty($this->redis)) {
-
-
- $redis = new Redis();
-
- if (!$redis->connect($this->redisConf['host'], $this->redisConf['port'])) {
-
- throw new Exception("Error Redis Connect", 100);
-
- }
-
- $redis->select(3);
-
- $this->redis = $redis;
-
-
- }
-
- return $this->redis;
-
- }
-
-
- }
-
|