| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Extension_HitCounter |
| 12 |
{ |
| 13 |
|
| 14 |
private $context; |
| 15 |
|
| 16 |
/** |
| 17 |
* @var int |
| 18 |
*/ |
| 19 |
private $numberOfDays; |
| 20 |
|
| 21 |
const OPTION_NAME = 'user_hit_count'; |
| 22 |
|
| 23 |
/** |
| 24 |
* @param MWP_WordPress_Context $context |
| 25 |
* @param int $numberOfDays Number of days to keep the log. |
| 26 |
*/ |
| 27 |
public function __construct(MWP_WordPress_Context $context, $numberOfDays = 1) |
| 28 |
{ |
| 29 |
$this->context = $context; |
| 30 |
$this->numberOfDays = $numberOfDays; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* @param int $incrementBy |
| 35 |
* @param DateTime $dateTime |
| 36 |
*/ |
| 37 |
public function increment($incrementBy = 1, DateTime $dateTime = null) |
| 38 |
{ |
| 39 |
if ($dateTime === null) { |
| 40 |
$dateTime = new DateTime('now', new DateTimeZone('UTC')); |
| 41 |
} |
| 42 |
$date = $dateTime->format('Y-m-d'); |
| 43 |
|
| 44 |
$hitCount = (array)$this->getHitCount(); |
| 45 |
|
| 46 |
if (!isset($hitCount[$date])) { |
| 47 |
$hitCount[$date] = 0; |
| 48 |
|
| 49 |
ksort($hitCount); |
| 50 |
|
| 51 |
$logSince = clone $dateTime; |
| 52 |
$logSince->modify(sprintf('-%d day', $this->numberOfDays)); |
| 53 |
$logSinceDate = $logSince->format('Y-m-d'); |
| 54 |
foreach ($hitCount as $hitDate => $hitTotal) { |
| 55 |
// The old functionality had a bug where keys were invalid dates, hence the date length check. |
| 56 |
if ($hitDate <= $logSinceDate || strlen($hitDate) !== 10) { |
| 57 |
unset($hitCount[$hitDate]); |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
$hitCount[$date] += $incrementBy; |
| 63 |
|
| 64 |
$this->context->optionSet(self::OPTION_NAME, $hitCount); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* @return array |
| 69 |
*/ |
| 70 |
public function getHitCount() |
| 71 |
{ |
| 72 |
$hitCount = $this->context->optionGet(self::OPTION_NAME, array()); |
| 73 |
|
| 74 |
return $hitCount; |
| 75 |
} |
| 76 |
} |
| 77 |
|