| 1 |
<?php |
| 2 |
|
| 3 |
namespace Hurrytimer; |
| 4 |
|
| 5 |
class EvergreenCampaign extends Campaign |
| 6 |
{ |
| 7 |
/** |
| 8 |
* @var CookieDetection |
| 9 |
*/ |
| 10 |
private $cookieDetection; |
| 11 |
|
| 12 |
/** |
| 13 |
* @var IPDetection |
| 14 |
*/ |
| 15 |
private $IPDetection; |
| 16 |
|
| 17 |
const RESET_FLAG = '_hurrytimer_reset_compaign_flag'; |
| 18 |
|
| 19 |
public function __construct($id, $cookieDetection, $IPDetection) |
| 20 |
{ |
| 21 |
parent::__construct($id); |
| 22 |
$this->IPDetection = $IPDetection; |
| 23 |
$this->cookieDetection = $cookieDetection; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Reset timer. |
| 28 |
*/ |
| 29 |
public function reset() |
| 30 |
{ |
| 31 |
$this->IPDetection->forget($this->getId()); |
| 32 |
$this->markReset(); |
| 33 |
} |
| 34 |
|
| 35 |
private function markReset(){ |
| 36 |
update_post_meta($this->getId(), self::RESET_FLAG, 1); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Returns client expiration time. |
| 41 |
* |
| 42 |
* @return int |
| 43 |
*/ |
| 44 |
public function getEndDate() |
| 45 |
{ |
| 46 |
// Get expire timestamp if cookie exists. |
| 47 |
$clientEndTimestamp = $this->cookieDetection->find($this->getId()); |
| 48 |
|
| 49 |
// If cookie doesn't exist. |
| 50 |
if (is_null($clientEndTimestamp)) { |
| 51 |
// Fallback to IP detection |
| 52 |
$result = $this->IPDetection->find($this->getId()); |
| 53 |
|
| 54 |
if ($result) { |
| 55 |
// Return IP `client_expires_at`. |
| 56 |
return $result['client_expires_at']; |
| 57 |
} |
| 58 |
|
| 59 |
// A new cookie will be created from client side |
| 60 |
// containing the expiration timestamp. |
| 61 |
return null; |
| 62 |
} |
| 63 |
|
| 64 |
$result = $this->IPDetection->find($this->getId()); |
| 65 |
|
| 66 |
if ($result) { |
| 67 |
// Update IP expiration timestamp. |
| 68 |
$this->IPDetection->update( $result['id'], $clientEndTimestamp); |
| 69 |
} else { |
| 70 |
// We create an IP entry. |
| 71 |
$this->IPDetection->create($this->getId(), $clientEndTimestamp); |
| 72 |
} |
| 73 |
|
| 74 |
return $clientEndTimestamp; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Returns true to force reset timer. |
| 79 |
* |
| 80 |
* @return bool |
| 81 |
*/ |
| 82 |
public function reseting() |
| 83 |
{ |
| 84 |
$reset = filter_var( |
| 85 |
get_post_meta($this->getId(), self::RESET_FLAG, true), |
| 86 |
FILTER_VALIDATE_BOOLEAN |
| 87 |
); |
| 88 |
|
| 89 |
$isDeleted = delete_post_meta($this->getId(), self::RESET_FLAG); |
| 90 |
|
| 91 |
// Make sure timer won't reset again before returning reset state. |
| 92 |
return $isDeleted ? $reset : false; |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* Returns given timer's cookie name. |
| 97 |
* |
| 98 |
* @return string |
| 99 |
*/ |
| 100 |
public function cookieName() |
| 101 |
{ |
| 102 |
return CookieDetection::cookieName($this->getId()); |
| 103 |
} |
| 104 |
} |
| 105 |
|