| 1 |
<?php |
| 2 |
|
| 3 |
namespace Boxzilla\Licensing; |
| 4 |
|
| 5 |
if (! defined('ABSPATH')) { |
| 6 |
exit; |
| 7 |
} |
| 8 |
|
| 9 |
class Poller |
| 10 |
{ |
| 11 |
public const HOOK = 'boxzilla_check_license_status'; |
| 12 |
|
| 13 |
/** |
| 14 |
* @var API |
| 15 |
*/ |
| 16 |
protected $api; |
| 17 |
|
| 18 |
/** |
| 19 |
* @var License |
| 20 |
*/ |
| 21 |
protected $license; |
| 22 |
|
| 23 |
/** |
| 24 |
* Poller constructor. |
| 25 |
* |
| 26 |
* @param API $api |
| 27 |
* @param License $license |
| 28 |
*/ |
| 29 |
public function __construct(API $api, License $license) |
| 30 |
{ |
| 31 |
$this->api = $api; |
| 32 |
$this->license = $license; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Add hooks. |
| 37 |
*/ |
| 38 |
public function init() |
| 39 |
{ |
| 40 |
if (! wp_next_scheduled(self::HOOK)) { |
| 41 |
wp_schedule_event(time(), 'daily', self::HOOK); |
| 42 |
} |
| 43 |
|
| 44 |
add_action(self::HOOK, [ $this, 'run' ]); |
| 45 |
} |
| 46 |
|
| 47 |
public static function deactivate() |
| 48 |
{ |
| 49 |
wp_clear_scheduled_hook(self::HOOK); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Run! |
| 54 |
*/ |
| 55 |
public function run() |
| 56 |
{ |
| 57 |
// don't run if license not active |
| 58 |
if (! $this->license->activated) { |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
// assume valid by default, in case of server errors on our side. |
| 63 |
$license_still_valid = true; |
| 64 |
|
| 65 |
try { |
| 66 |
$remote_license = $this->api->get_license(); |
| 67 |
$license_still_valid = $remote_license->valid; |
| 68 |
} catch (API_Exception $e) { |
| 69 |
// license key wasn't found or expired |
| 70 |
if (in_array($e->getApiCode(), [ 'license_invalid', 'license_expired' ], true)) { |
| 71 |
$license_still_valid = false; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
if (! $license_still_valid) { |
| 76 |
$this->license->activated = false; |
| 77 |
$this->license->save(); |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|