Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.51% covered (warning)
76.51%
114 / 149
41.18% covered (danger)
41.18%
7 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
HiiveConnection
76.51% covered (warning)
76.51%
114 / 149
41.18% covered (danger)
41.18%
7 / 17
77.86
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_verification_hooks
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 rest_api_init
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 ajax_verify
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 verify_token
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 is_connected
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 connect
93.33% covered (success)
93.33%
28 / 30
0.00% covered (danger)
0.00%
0 / 1
6.01
 reconnect
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 throttle
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_throttle_interval
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 is_throttled
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 send_event
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
3.04
 notify
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
6
 hiive_request
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
9
 get_auth_token
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_core_data
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 add_plugin_name_version_to_user_agent
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace NewfoldLabs\WP\Module\Data;
4
5use NewfoldLabs\WP\Module\Data\Helpers\Plugin as PluginHelper;
6use NewfoldLabs\WP\Module\Data\Helpers\Transient;
7use WP_Error;
8use function NewfoldLabs\WP\ModuleLoader\container;
9
10/**
11 * Manages a Hiive connection instance and interactions with it
12 */
13class HiiveConnection implements SubscriberInterface {
14
15    /**
16     * Hiive API url
17     *
18     * @var string
19     */
20    private $api;
21
22    /**
23     * Authentication token for data api
24     *
25     * @var string
26     */
27    private $token;
28
29
30    /**
31     * Whether connection attempts are currently throttled
32     *
33     * @var bool
34     */
35    private $throttled;
36
37    /**
38     * The throttle
39     *
40     * @var bool
41     */
42    protected $throttle;
43
44    /**
45     * Construct
46     */
47    public function __construct() {
48
49        if ( ! defined( 'NFD_HIIVE_URL' ) ) {
50            define( 'NFD_HIIVE_URL', 'https://hiive.cloud/api' );
51        }
52
53        $this->api = constant( 'NFD_HIIVE_URL' );
54    }
55
56    /**
57     * Register the hooks required for site verification
58     *
59     * @return void
60     */
61    public function register_verification_hooks() {
62        add_action( 'rest_api_init', array( $this, 'rest_api_init' ) );
63        add_action( 'wp_ajax_nopriv_nfd-hiive-verify', array( $this, 'ajax_verify' ) );
64    }
65
66    /**
67     * Set up REST API routes
68     *
69     * @hooked rest_api_init
70     */
71    public function rest_api_init(): void {
72        $controller = new API\Verify( $this );
73        $controller->register_routes();
74    }
75
76    /**
77     * Process the admin-ajax request
78     *
79     * Hiive will first attempt to verify using the REST API, and fallback to this AJAX endpoint on error.
80     *
81     * Token is generated in {@see self::connect()} using {@see md5()}.
82     *
83     * @hooked wp_ajax_nopriv_nfd-hiive-verify
84     *
85     * @return never
86     */
87    public function ajax_verify() {
88        // PHPCS: Ignore the nonce verification here – the token _is_ a nonce.
89        // @phpcs:ignore WordPress.Security.NonceVerification.Recommended
90        $token = $_REQUEST['token'];
91
92        $is_valid = $this->verify_token( $token );
93        $status   = ( $is_valid ) ? 200 : 400;
94
95        $data = array(
96            'token' => $token,
97            'valid' => $is_valid,
98        );
99        \wp_send_json( $data, $status );
100    }
101
102    /**
103     * Confirm whether verification token is valid
104     *
105     * Token is generated in {@see self::connect()} using {@see md5()}.
106     *
107     * @param string $token Token to verify
108     */
109    public function verify_token( string $token ): bool {
110        $saved_token = Transient::get( 'nfd_data_verify_token' );
111
112        if ( $saved_token && $saved_token === $token ) {
113            Transient::delete( 'nfd_data_verify_token' );
114
115            return true;
116        }
117
118        return false;
119    }
120
121    /**
122     * Check whether site has established connection to hiive
123     *
124     * This is cleared whenever Hiive returns 401 unauthenticated {@see Data::delete_token_on_401_response()}.
125     *
126     * @used-by Data::init()
127     */
128    public static function is_connected(): bool {
129        return (bool) ( self::get_auth_token() );
130    }
131
132    /**
133     * Attempt to connect to Hiive
134     *
135     * @used-by Data::init()
136     * @used-by HiiveConnection::reconnect()
137     *
138     * @param string  $path Additional path to append to the API URL
139     * @param ?string $authorization The authorization header
140     * @return bool Success
141     */
142    public function connect( string $path = '/sites/v2/connect', ?string $authorization = null ): bool {
143
144        if ( $this->is_throttled() ) {
145            return false;
146        }
147
148        $this->throttle();
149
150        $token = md5( \wp_generate_password() );
151        Transient::set( 'nfd_data_verify_token', $token, 5 * constant( 'MINUTE_IN_SECONDS' ) );
152
153        $data                 = $this->get_core_data();
154        $data['verify_token'] = $token;
155        $data['plugins']      = ( new PluginHelper() )->collect_installed();
156
157        $args = array(
158            'body'     => \wp_json_encode( $data ),
159            'headers'  => array(
160                'Content-Type' => 'application/json',
161                'Accept'       => 'application/json',
162            ),
163            'blocking' => true,
164            'timeout'  => 30,
165        );
166
167        if ( $authorization ) {
168            $args['headers']['Authorization'] = $authorization;
169        }
170
171        $attempts = intval( get_option( 'nfd_data_connection_attempts', 0 ) );
172        \update_option( 'nfd_data_connection_attempts', $attempts + 1 );
173
174        $response = \wp_remote_post( $this->api . $path, $args );
175        $status   = \wp_remote_retrieve_response_code( $response );
176
177        // Created = 201; Updated = 200
178        if ( 201 === $status || 200 === $status ) {
179            $body = json_decode( \wp_remote_retrieve_body( $response ) );
180            if ( ! empty( $body->token ) ) {
181
182                // Token is auto-encrypted using the `pre_update_option_nfd_data_token` hook.
183                \update_option( 'nfd_data_token', $body->token );
184
185                ( new SiteCapabilities() )->clear();
186
187                return true;
188            }
189        }
190        return false;
191    }
192
193    /**
194     * Rename the site URL in Hiive.
195     *
196     * This performs almost the same request as {@see self::connect} but includes the Site authorization token,
197     * to verify this site is the owner of the existing site in Hiive, and Hiive pings back the new URL to verify
198     * the DNS points to this site.
199     */
200    public function reconnect(): bool {
201        return $this->connect( '/sites/v2/reconnect', 'Bearer ' . self::get_auth_token() );
202    }
203
204    /**
205     * Set the connection throttle
206     *
207     * @return void
208     */
209    public function throttle() {
210        $interval = $this->get_throttle_interval();
211
212        $this->throttle = Transient::set( 'nfd_data_connection_throttle', true, $interval );
213    }
214
215    /**
216     * Determine the throttle interval based off number of connection attempts
217     *
218     * @return integer Time to wait until next connection attempt
219     */
220    public function get_throttle_interval() {
221
222        $attempts = intval( \get_option( 'nfd_data_connection_attempts', 0 ) );
223
224        // Throttle intervals step-up:
225        // Hourly for 4 hours
226        // Twice a day for 3 days
227        // Once a day for 3 days
228        // Every 3 days for 3 times
229        // Once a week
230        if ( $attempts <= 4 ) {
231            return HOUR_IN_SECONDS;
232        } elseif ( $attempts <= 10 ) {
233            return 12 * HOUR_IN_SECONDS;
234        } elseif ( $attempts <= 13 ) {
235            return DAY_IN_SECONDS;
236        } elseif ( $attempts <= 16 ) {
237            return 3 * DAY_IN_SECONDS;
238        } else {
239            return WEEK_IN_SECONDS;
240        }
241    }
242
243    /**
244     * Check whether connection is throttled
245     *
246     * @return boolean
247     */
248    public function is_throttled() {
249        $this->throttled = Transient::get( 'nfd_data_connection_throttle' );
250
251        return $this->throttled;
252    }
253
254    /**
255     * Synchronously send a single event and return the notifications.
256     *
257     * @used-by Events::create_item()
258     *
259     * @param Event $event the event
260     *
261     * @phpstan-type Notification_Array array{id:string,locations:array,query:string|null,expiration:int,content:string}
262     * @return array<Notification_Array>|WP_Error
263     */
264    public function send_event( Event $event ) {
265
266        $payload = array(
267            'environment' => $this->get_core_data(),
268            'events'      => array( $event ),
269        );
270
271        $hiive_response = $this->hiive_request( 'sites/v1/events', $payload );
272
273        if ( is_wp_error( $hiive_response ) ) {
274            return $hiive_response;
275        }
276
277        $status_code = \wp_remote_retrieve_response_code( $hiive_response );
278
279        if ( ! in_array( $status_code, array( 200, 201 ), true ) ) {
280            return new \WP_Error( $status_code, \wp_remote_retrieve_response_message( $hiive_response ) );
281        }
282
283        /**
284         * Sample shape.
285         *
286         * @var array{data:array{id:string,locations:array,query:string|null,expiration:int,content:string}} $response_payload
287         * */
288        $response_payload = json_decode( \wp_remote_retrieve_body( $hiive_response ), true );
289
290        return $response_payload['data'] ?? array();
291    }
292
293    /**
294     * Send events to the v2 events endpoint and return the list of successes and list of failures.
295     *
296     * @see SubscriberInterface::notify()
297     * @used-by EventManager::send()
298     *
299     * @param Event[] $events Array of Event objects representing the actions that occurred.
300     *
301     * @return array{succeededEvents:array,failedEvents:array}|WP_Error
302     */
303    public function notify( $events ) {
304
305        $payload = array(
306            'environment' => $this->get_core_data(),
307            'events'      => $events,
308        );
309
310        $hiive_response = $this->hiive_request( 'sites/v2/events', $payload );
311
312        if ( \is_wp_error( ( $hiive_response ) ) ) {
313            return $hiive_response;
314        }
315
316        if ( ! in_array( \wp_remote_retrieve_response_code( $hiive_response ), array( 200, 201, 500 ), true ) ) {
317            return new WP_Error( \wp_remote_retrieve_response_code( $hiive_response ), \wp_remote_retrieve_response_message( $hiive_response ) );
318        }
319
320        $response_body = json_decode( wp_remote_retrieve_body( $hiive_response ), true );
321
322        // If the response from Hiive is not shaped as expected, e.g. a more serious 500 error, return as an error, not as the expected array.
323        if ( ! is_array( $response_body ) || ! array_key_exists( 'succeededEvents', $response_body ) || ! array_key_exists( 'failedEvents', $response_body ) ) {
324            return new WP_Error( 'hiive_response', 'Response body does not contain succeededEvents and failedEvents keys.' );
325        }
326
327        return $response_body;
328    }
329
330    /**
331     * Send an HTTP request to Hiive and return the body of the request.
332     *
333     * Handles throttling and reconnection, clients should handle queueing if necessary.
334     *
335     * Defaults to POST. Override with `$args = array('method' => 'GET')`.
336     *
337     * @param string     $path The Hiive api path (after /api/).
338     * @param array|null $payload the payload
339     * @param array|null $args and args for the request
340     *
341     * @return array|WP_Error The response array or a WP_Error when no Hiive connection, no network connection, network requests disabled.
342     */
343    public function hiive_request( string $path, ?array $payload = array(), ?array $args = array() ) {
344
345        /**
346         * Add plugin name/version to user agent
347         *
348         * @see \WP_Http::request()
349         * @see https://developer.wordpress.org/reference/hooks/http_headers_useragent/
350         */
351        add_filter( 'http_headers_useragent', array( $this, 'add_plugin_name_version_to_user_agent' ), 10, 2 );
352
353        // If for some reason we are not connected, bail out now.
354        // If we are not connected, the throttling logic should eventually reconnect.
355        if ( ! self::is_connected() ) {
356            return new WP_Error( 'hiive_connection', __( 'This site is not connected to the hiive.', 'wp-module-data' ) );
357        }
358
359        $defaults = array(
360            'method'  => 'POST',
361            'headers' => array(
362                'Content-Type'  => 'application/json',
363                'Accept'        => 'application/json',
364                'Authorization' => 'Bearer ' . self::get_auth_token(),
365            ),
366            'timeout' => \wp_is_serving_rest_request() ? 15 : 60, // If we're responding to the frontend, we need to be quick.
367        );
368
369        $parsed_args = \wp_parse_args( $args ?? array(), $defaults );
370        $url         = "{$this->api}/{$path}";
371
372        if ( ! empty( $payload ) ) {
373            $parsed_args['body'] = 'GET' === $parsed_args['method']
374                ? $payload
375                : \wp_json_encode( $payload );
376        }
377
378        $request_response = \wp_remote_request( $url, $parsed_args );
379
380        // E.g. Hiive is down, or the site has disabled HTTP requests.
381        if ( \is_wp_error( $request_response ) ) {
382            return $request_response;
383        }
384
385        // Authentication token is valid for Hiive but not for the resource or Site.
386        if ( 403 === $request_response['response']['code'] ) {
387            $body = json_decode( $request_response['body'], true );
388            if ( 'Invalid token for url' === $body['message'] ) {
389                if ( $this->reconnect() ) {
390                    return $this->hiive_request( $path, $payload, $args );
391                }
392
393                return new WP_Error( 'hiive_connection', __( 'This site is not connected to the hiive.', 'wp-module-data' ) );
394            }
395        }
396
397        \remove_filter( 'http_headers_useragent', array( $this, 'add_plugin_name_version_to_user_agent' ) );
398
399        return $request_response;
400    }
401
402    /**
403     * Try to return the auth token
404     *
405     * This is cleared whenever Hiive returns 401 unauthenticated {@see Data::delete_token_on_401_response()}.
406     *
407     * @return string|false The decrypted token if it's set
408     */
409    public static function get_auth_token() {
410        // Check if a custom token is defined via constant
411        if ( defined( 'NFD_HIIVE_AUTH_TOKEN' ) ) {
412            return NFD_HIIVE_AUTH_TOKEN;
413        }
414
415        // Fall back to the stored option
416        return \get_option( 'nfd_data_token' );
417    }
418
419    /**
420     * Get core site data for initial connection
421     *
422     * @return array
423     */
424    public function get_core_data() {
425        global $wpdb, $wp_version;
426        $container = container();
427
428        $data = array(
429            'brand'       => \sanitize_title( $container->plugin()->brand ),
430            'cache_level' => intval( \get_option( 'newfold_cache_level', 2 ) ),
431            'cloudflare'  => \get_option( 'newfold_cloudflare_enabled', false ),
432            'data'        => defined( 'NFD_DATA_MODULE_VERSION' ) ? constant( 'NFD_DATA_MODULE_VERSION' ) : '0.0',
433            'email'       => \get_option( 'admin_email' ),
434            'hostname'    => gethostname(),
435            'mysql'       => $wpdb->db_version(),
436            'origin'      => $container->plugin()->get( 'id', 'error' ),
437            'php'         => phpversion(),
438            'plugin'      => $container->plugin()->get( 'version', '0' ),
439            'url'         => \get_site_url(),
440            'username'    => get_current_user(),
441            'wp'          => $wp_version,
442            'server_path' => \untrailingslashit( defined( 'ABSPATH' ) ? constant( 'ABSPATH' ) : '' ),
443        );
444
445        return apply_filters( 'newfold_wp_data_module_core_data_filter', $data );
446    }
447
448    /**
449     * Add the plugin name and version to the user agent string
450     *
451     * @param string $user_agent E.g. "WordPress/6.4.3; https://example.org".
452     * @param string $url   E.g. "https://hiive.cloud/api/sites/v2/events".
453     *
454     * @return string E.g. "WordPress/6.4.3; bluehost/1.2.3; https://example.org".
455     */
456    public function add_plugin_name_version_to_user_agent( string $user_agent, string $url ): string {
457        $container      = container();
458        $plugin_brand   = \sanitize_title( $container->plugin()->brand );
459        $plugin_version = $container->plugin()->get( 'version', '0' );
460
461        $user_agent_parts = array_map( 'trim', explode( ';', $user_agent ) );
462
463        array_splice( $user_agent_parts, 1, 0, "{$plugin_brand}/{$plugin_version}" );
464
465        return implode( '; ', $user_agent_parts );
466    }
467}