| 1 |
<?php |
| 2 |
/** |
| 3 |
* Send Usage Task class. |
| 4 |
* |
| 5 |
* @package Merchant |
| 6 |
* @since 1.0.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
if ( ! defined( 'ABSPATH' ) ) { |
| 10 |
exit; // Exit if accessed directly. |
| 11 |
} |
| 12 |
|
| 13 |
/** |
| 14 |
* Merchant_Send_Usage_Task class. |
| 15 |
*/ |
| 16 |
class Merchant_Send_Usage_Task { |
| 17 |
|
| 18 |
/** |
| 19 |
* Action name for this task. |
| 20 |
* |
| 21 |
* @since 2.2.0 |
| 22 |
*/ |
| 23 |
const ACTION = 'merchant_send_usage_data'; |
| 24 |
|
| 25 |
/** |
| 26 |
* Server URL to send requests to. |
| 27 |
* |
| 28 |
* @since 2.2.0 |
| 29 |
*/ |
| 30 |
const TRACK_URL = 'https://athemesusage.com/merchant/v1/track'; |
| 31 |
|
| 32 |
/** |
| 33 |
* Option name to store the timestamp of the last run. |
| 34 |
* |
| 35 |
* @since 2.2.0 |
| 36 |
*/ |
| 37 |
const LAST_RUN = 'merchant_send_usage_last_run'; |
| 38 |
|
| 39 |
/** |
| 40 |
* Initialize the task. |
| 41 |
* |
| 42 |
* @since 2.2.0 |
| 43 |
*/ |
| 44 |
public function init() { |
| 45 |
|
| 46 |
$this->hooks(); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Attach hooks to the WordPress API. |
| 51 |
* |
| 52 |
* @since 2.2.0 |
| 53 |
*/ |
| 54 |
public function hooks() { |
| 55 |
|
| 56 |
// Register the action handler. |
| 57 |
add_action( self::ACTION, array( $this, 'process' ) ); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Send the actual data in a POST request. |
| 62 |
* |
| 63 |
* @since 2.2.0 |
| 64 |
*/ |
| 65 |
public function process() { |
| 66 |
|
| 67 |
$last_run = get_option( self::LAST_RUN ); |
| 68 |
|
| 69 |
// Make sure we do not run it more than once a day. |
| 70 |
if ( |
| 71 |
$last_run !== false && |
| 72 |
( time() - $last_run ) < DAY_IN_SECONDS |
| 73 |
) { |
| 74 |
return; |
| 75 |
} |
| 76 |
|
| 77 |
// Send data to the usage tracking API. |
| 78 |
$ut = new Merchant_Usage_Tracking(); |
| 79 |
|
| 80 |
$response = wp_remote_post( |
| 81 |
self::TRACK_URL, |
| 82 |
array( |
| 83 |
'timeout' => 5, |
| 84 |
'redirection' => 5, |
| 85 |
'httpversion' => '1.1', |
| 86 |
'blocking' => true, |
| 87 |
'body' => $ut->get_data(), |
| 88 |
'user-agent' => $ut->get_user_agent(), |
| 89 |
) |
| 90 |
); |
| 91 |
|
| 92 |
// Update the last run option to the current timestamp. |
| 93 |
update_option( self::LAST_RUN, time(), false ); |
| 94 |
|
| 95 |
/** |
| 96 |
* Action fired after usage data is sent. |
| 97 |
* |
| 98 |
* @param array|WP_Error $response The response from the API. |
| 99 |
* |
| 100 |
* @since 2.2.0 |
| 101 |
*/ |
| 102 |
do_action( 'merchant_usage_tracking_sent', $response ); |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
|