PayloadBuilder.php
3 weeks ago
RegisterSite.php
3 weeks ago
Scheduler.php
3 weeks ago
Sender.php
3 weeks ago
Sender.php
68 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Sends the usage report payload to the API. |
| 4 | * |
| 5 | * @package TwitterFeed\UsageTracking\Core |
| 6 | * @since 2.6 |
| 7 | */ |
| 8 | |
| 9 | namespace TwitterFeed\UsageTracking\Core; |
| 10 | |
| 11 | use TwitterFeed\UsageTracking\Config; |
| 12 | |
| 13 | if ( ! defined( 'ABSPATH' ) ) { |
| 14 | exit; |
| 15 | } |
| 16 | |
| 17 | class Sender { |
| 18 | |
| 19 | /** |
| 20 | * Send the usage report payload to the API. |
| 21 | * Skips send if payload exceeds max size to avoid timeouts; uses longer timeout for large bodies. |
| 22 | * |
| 23 | * @param array $payload Full JSON-serializable payload. |
| 24 | * @return bool True if request was sent successfully (2xx), false otherwise. |
| 25 | */ |
| 26 | public function send( array $payload ) { |
| 27 | $url = Config::get_usage_report_url(); |
| 28 | $body = wp_json_encode( $payload ); |
| 29 | if ( false === $body ) { |
| 30 | return false; |
| 31 | } |
| 32 | |
| 33 | $max_bytes = (int) apply_filters( 'ctf_smash_usage_tracking_max_payload_bytes', Config::MAX_PAYLOAD_BYTES ); |
| 34 | if ( $max_bytes > 0 && strlen( $body ) > $max_bytes ) { |
| 35 | if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG && function_exists( 'error_log' ) ) { |
| 36 | error_log( '[CTF Usage Tracking] Payload size ' . strlen( $body ) . ' exceeds max ' . $max_bytes . ', send skipped.' ); |
| 37 | } |
| 38 | return false; |
| 39 | } |
| 40 | |
| 41 | $timeout = (int) apply_filters( 'ctf_smash_usage_tracking_request_timeout', Config::REQUEST_TIMEOUT ); |
| 42 | $timeout = max( 15, min( 120, $timeout ) ); |
| 43 | |
| 44 | $response = wp_remote_post( |
| 45 | $url, |
| 46 | array( |
| 47 | 'method' => 'POST', |
| 48 | 'timeout' => $timeout, |
| 49 | 'redirection' => 5, |
| 50 | 'httpversion' => '1.1', |
| 51 | 'blocking' => true, |
| 52 | 'headers' => array( |
| 53 | 'Content-Type' => 'application/json', |
| 54 | ), |
| 55 | 'body' => $body, |
| 56 | 'user-agent' => 'CTF/' . (defined( 'CTF_VERSION' ) ? CTF_VERSION : '') . '; ' . get_bloginfo( 'url' ), |
| 57 | ) |
| 58 | ); |
| 59 | |
| 60 | if ( is_wp_error( $response ) ) { |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | $code = wp_remote_retrieve_response_code( $response ); |
| 65 | return $code >= 200 && $code < 300; |
| 66 | } |
| 67 | } |
| 68 |