| 1 |
<?php |
| 2 |
|
| 3 |
class Logtivity_Log_API |
| 4 |
{ |
| 5 |
public $logtivityApiUrl = 'https://api.logtivity.io'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Option class to access the plugin settings |
| 9 |
* |
| 10 |
* @var object |
| 11 |
*/ |
| 12 |
protected $options; |
| 13 |
|
| 14 |
/** |
| 15 |
* Should we wait to return the response from the API? |
| 16 |
* |
| 17 |
* @var boolean |
| 18 |
*/ |
| 19 |
public $waitForResponse = false; |
| 20 |
|
| 21 |
public function __construct() |
| 22 |
{ |
| 23 |
$this->options = new Logtivity_Options; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Get the API URL for the Logtivity endpoint |
| 28 |
* |
| 29 |
* @return string |
| 30 |
*/ |
| 31 |
public function getEndpoint($endpoint) |
| 32 |
{ |
| 33 |
if (defined('LOGTIVITY_API_URL')) { |
| 34 |
return LOGTIVITY_API_URL . $endpoint; |
| 35 |
} |
| 36 |
|
| 37 |
return $this->logtivityApiUrl . $endpoint; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Make a request to the Logtivity API |
| 42 |
* |
| 43 |
* @param string $url |
| 44 |
* @param array $body |
| 45 |
* @param string $method |
| 46 |
* @return mixed $response |
| 47 |
*/ |
| 48 |
public function makeRequest($url, $body, $method = 'POST') |
| 49 |
{ |
| 50 |
$api_key = logtivity_get_api_key(); |
| 51 |
|
| 52 |
if (!$api_key) |
| 53 |
{ |
| 54 |
return; |
| 55 |
} |
| 56 |
|
| 57 |
$shouldLogLatestResponse = $this->waitForResponse || $this->options->shouldLogLatestResponse(); |
| 58 |
|
| 59 |
$response = wp_remote_post( $url, [ |
| 60 |
'method' => $method, |
| 61 |
'timeout' => ( $shouldLogLatestResponse ? 45 : 0.01), |
| 62 |
'blocking' => ( $shouldLogLatestResponse ? true : false), |
| 63 |
'redirection' => 5, |
| 64 |
'httpversion' => '1.0', |
| 65 |
'headers' => array(), |
| 66 |
'body' => array_merge(['api_key' => $api_key], $body), |
| 67 |
'cookies' => array() |
| 68 |
]); |
| 69 |
|
| 70 |
$response = wp_remote_retrieve_body($response); |
| 71 |
|
| 72 |
if ($shouldLogLatestResponse) { |
| 73 |
|
| 74 |
$this->options->update([ |
| 75 |
'logtivity_latest_response' => [ |
| 76 |
'date' => date("Y-m-d H:i:s"), |
| 77 |
'response' => print_r($response, true) |
| 78 |
] |
| 79 |
]); |
| 80 |
|
| 81 |
} |
| 82 |
|
| 83 |
return $response; |
| 84 |
} |
| 85 |
} |