Completed
Push — branch-8.sync ( b15093 )
by Jeremy
07:09
created

Sender::get_next_sync_time()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Sync sender.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
use Automattic\Jetpack\Constants;
11
12
/**
13
 * This class grabs pending actions from the queue and sends them
14
 */
15
class Sender {
16
	/**
17
	 * Name of the option that stores the time of the next sync.
18
	 *
19
	 * @access public
20
	 *
21
	 * @var string
22
	 */
23
	const NEXT_SYNC_TIME_OPTION_NAME = 'jetpack_next_sync_time';
24
25
	/**
26
	 * Sync timeout after a WPCOM error.
27
	 *
28
	 * @access public
29
	 *
30
	 * @var int
31
	 */
32
	const WPCOM_ERROR_SYNC_DELAY = 60;
33
34
	/**
35
	 * Sync timeout after a queue has been locked.
36
	 *
37
	 * @access public
38
	 *
39
	 * @var int
40
	 */
41
	const QUEUE_LOCKED_SYNC_DELAY = 10;
42
43
	/**
44
	 * Maximum bytes to checkout without exceeding the memory limit.
45
	 *
46
	 * @access private
47
	 *
48
	 * @var int
49
	 */
50
	private $dequeue_max_bytes;
51
52
	/**
53
	 * Maximum bytes in a single encoded item.
54
	 *
55
	 * @access private
56
	 *
57
	 * @var int
58
	 */
59
	private $upload_max_bytes;
60
61
	/**
62
	 * Maximum number of sync items in a single action.
63
	 *
64
	 * @access private
65
	 *
66
	 * @var int
67
	 */
68
	private $upload_max_rows;
69
70
	/**
71
	 * Maximum time for perfirming a checkout of items from the queue (in seconds).
72
	 *
73
	 * @access private
74
	 *
75
	 * @var int
76
	 */
77
	private $max_dequeue_time;
78
79
	/**
80
	 * How many seconds to wait after sending sync items after exceeding the sync wait threshold (in seconds).
81
	 *
82
	 * @access private
83
	 *
84
	 * @var int
85
	 */
86
	private $sync_wait_time;
87
88
	/**
89
	 * How much maximum time to wait for the checkout to finish (in seconds).
90
	 *
91
	 * @access private
92
	 *
93
	 * @var int
94
	 */
95
	private $sync_wait_threshold;
96
97
	/**
98
	 * How much maximum time to wait for the sync items to be queued for sending (in seconds).
99
	 *
100
	 * @access private
101
	 *
102
	 * @var int
103
	 */
104
	private $enqueue_wait_time;
105
106
	/**
107
	 * Incremental sync queue object.
108
	 *
109
	 * @access private
110
	 *
111
	 * @var Automattic\Jetpack\Sync\Queue
112
	 */
113
	private $sync_queue;
114
115
	/**
116
	 * Full sync queue object.
117
	 *
118
	 * @access private
119
	 *
120
	 * @var Automattic\Jetpack\Sync\Queue
121
	 */
122
	private $full_sync_queue;
123
124
	/**
125
	 * Codec object for encoding and decoding sync items.
126
	 *
127
	 * @access private
128
	 *
129
	 * @var Automattic\Jetpack\Sync\Codec_Interface
130
	 */
131
	private $codec;
132
133
	/**
134
	 * The current user before we change or clear it.
135
	 *
136
	 * @access private
137
	 *
138
	 * @var \WP_User
139
	 */
140
	private $old_user;
141
142
	/**
143
	 * Container for the singleton instance of this class.
144
	 *
145
	 * @access private
146
	 * @static
147
	 *
148
	 * @var Automattic\Jetpack\Sync\Sender
149
	 */
150
	private static $instance;
151
152
	/**
153
	 * Retrieve the singleton instance of this class.
154
	 *
155
	 * @access public
156
	 * @static
157
	 *
158
	 * @return Sender
159
	 */
160
	public static function get_instance() {
161
		if ( null === self::$instance ) {
162
			self::$instance = new self();
0 ignored issues
show
Documentation Bug introduced by
It seems like new self() of type object<Automattic\Jetpack\Sync\Sender> is incompatible with the declared type object<Automattic\Jetpac...ic\Jetpack\Sync\Sender> of property $instance.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
163
		}
164
165
		return self::$instance;
166
	}
167
168
	/**
169
	 * Constructor.
170
	 * This is necessary because you can't use "new" when you declare instance properties >:(
171
	 *
172
	 * @access protected
173
	 * @static
174
	 */
175
	protected function __construct() {
176
		$this->set_defaults();
177
		$this->init();
178
	}
179
180
	/**
181
	 * Initialize the sender.
182
	 * Prepares the current user and initializes all sync modules.
183
	 *
184
	 * @access private
185
	 */
186
	private function init() {
187
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_set_user_from_token' ), 1 );
188
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_clear_user_from_token' ), 20 );
189
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'register_jetpack_xmlrpc_methods' ) );
190
		foreach ( Modules::get_modules() as $module ) {
191
			$module->init_before_send();
192
		}
193
	}
194
195
	/**
196
	 * Detect if this is a XMLRPC request with a valid signature.
197
	 * If so, changes the user to the new one.
198
	 *
199
	 * @access public
200
	 */
201
	public function maybe_set_user_from_token() {
202
		$verified_user = \Jetpack::connection()->verify_xml_rpc_signature();
203
		if ( Constants::is_true( 'XMLRPC_REQUEST' ) &&
204
			! is_wp_error( $verified_user )
205
			&& $verified_user
206
		) {
207
			$old_user       = wp_get_current_user();
208
			$this->old_user = isset( $old_user->ID ) ? $old_user->ID : 0;
209
			wp_set_current_user( $verified_user['user_id'] );
210
		}
211
	}
212
213
	/**
214
	 * If we used to have a previous current user, revert back to it.
215
	 *
216
	 * @access public
217
	 */
218
	public function maybe_clear_user_from_token() {
219
		if ( isset( $this->old_user ) ) {
220
			wp_set_current_user( $this->old_user );
221
		}
222
	}
223
224
	/**
225
	 * Retrieve the next sync time.
226
	 *
227
	 * @access public
228
	 *
229
	 * @param string $queue_name Name of the queue.
230
	 * @return float Timestamp of the next sync.
231
	 */
232
	public function get_next_sync_time( $queue_name ) {
233
		return (float) get_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, 0 );
234
	}
235
236
	/**
237
	 * Set the next sync time.
238
	 *
239
	 * @access public
240
	 *
241
	 * @param int    $time       Timestamp of the next sync.
242
	 * @param string $queue_name Name of the queue.
243
	 * @return boolean True if update was successful, false otherwise.
244
	 */
245
	public function set_next_sync_time( $time, $queue_name ) {
246
		return update_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, $time, true );
247
	}
248
249
	/**
250
	 * Trigger a full sync.
251
	 *
252
	 * @access public
253
	 *
254
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
255
	 */
256
	public function do_full_sync() {
257
		if ( ! Modules::get_module( 'full-sync' ) ) {
258
			return;
259
		}
260
		if ( ! Settings::get_setting( 'full_sync_sender_enabled' ) ) {
261
			return;
262
		}
263
		$this->continue_full_sync_enqueue();
264
		return $this->do_sync_and_set_delays( $this->full_sync_queue );
265
	}
266
267
	/**
268
	 * Enqueue the next sync items for sending.
269
	 * Will not be done if the current request is a WP import one.
270
	 * Will be delayed until the next sync time comes.
271
	 *
272
	 * @access private
273
	 */
274
	private function continue_full_sync_enqueue() {
275
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
276
			return false;
277
		}
278
279
		if ( $this->get_next_sync_time( 'full-sync-enqueue' ) > microtime( true ) ) {
280
			return false;
281
		}
282
283
		Modules::get_module( 'full-sync' )->continue_enqueuing();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Automattic\Jetpack\Sync\Modules\Module as the method continue_enqueuing() does only exist in the following sub-classes of Automattic\Jetpack\Sync\Modules\Module: Automattic\Jetpack\Sync\Modules\Full_Sync, Automattic\Jetpack\Sync\...s\Full_Sync_Immediately. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
284
285
		$this->set_next_sync_time( time() + $this->get_enqueue_wait_time(), 'full-sync-enqueue' );
286
	}
287
288
	/**
289
	 * Trigger incremental sync.
290
	 *
291
	 * @access public
292
	 *
293
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
294
	 */
295
	public function do_sync() {
296
		return $this->do_sync_and_set_delays( $this->sync_queue );
297
	}
298
299
	/**
300
	 * Trigger sync for a certain sync queue.
301
	 * Responsible for setting next sync time.
302
	 * Will not be delayed if the current request is a WP import one.
303
	 * Will be delayed until the next sync time comes.
304
	 *
305
	 * @access public
306
	 *
307
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
308
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
309
	 */
310
	public function do_sync_and_set_delays( $queue ) {
311
		// Don't sync if importing.
312
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
313
			return new \WP_Error( 'is_importing' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'is_importing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
314
		}
315
316
		if ( ! Settings::is_sender_enabled( $queue->id ) ) {
317
			return new \WP_Error( 'sender_disabled_for_queue_' . $queue->id );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'sender_disabled_for_queue_' . $queue->id.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
318
		}
319
320
		// Don't sync if we are throttled.
321
		if ( $this->get_next_sync_time( $queue->id ) > microtime( true ) ) {
322
			return new \WP_Error( 'sync_throttled' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'sync_throttled'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
323
		}
324
325
		$start_time = microtime( true );
326
327
		Settings::set_is_syncing( true );
328
329
		$sync_result = $this->do_sync_for_queue( $queue );
330
331
		Settings::set_is_syncing( false );
332
333
		$exceeded_sync_wait_threshold = ( microtime( true ) - $start_time ) > (float) $this->get_sync_wait_threshold();
334
335
		if ( is_wp_error( $sync_result ) ) {
336
			if ( 'unclosed_buffer' === $sync_result->get_error_code() ) {
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
337
				$this->set_next_sync_time( time() + self::QUEUE_LOCKED_SYNC_DELAY, $queue->id );
338
			}
339
			if ( 'wpcom_error' === $sync_result->get_error_code() ) {
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
340
				$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY, $queue->id );
341
			}
342
		} elseif ( $exceeded_sync_wait_threshold ) {
343
			// If we actually sent data and it took a while, wait before sending again.
344
			$this->set_next_sync_time( time() + $this->get_sync_wait_time(), $queue->id );
345
		}
346
347
		return $sync_result;
348
	}
349
350
	/**
351
	 * Retrieve the next sync items to send.
352
	 *
353
	 * @access public
354
	 *
355
	 * @param (array|Automattic\Jetpack\Sync\Queue_Buffer) $buffer_or_items Queue buffer or array of objects.
356
	 * @param boolean                                      $encode Whether to encode the items.
357
	 * @return array Sync items to send.
358
	 */
359
	public function get_items_to_send( $buffer_or_items, $encode = true ) {
360
		// Track how long we've been processing so we can avoid request timeouts.
361
		$start_time    = microtime( true );
362
		$upload_size   = 0;
363
		$items_to_send = array();
364
		$items         = is_array( $buffer_or_items ) ? $buffer_or_items : $buffer_or_items->get_items();
365
		// Set up current screen to avoid errors rendering content.
366
		require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
367
		require_once ABSPATH . 'wp-admin/includes/screen.php';
368
		set_current_screen( 'sync' );
369
		$skipped_items_ids = array();
370
		/**
371
		 * We estimate the total encoded size as we go by encoding each item individually.
372
		 * This is expensive, but the only way to really know :/
373
		 */
374
		foreach ( $items as $key => $item ) {
375
			// Suspending cache addition help prevent overloading in memory cache of large sites.
376
			wp_suspend_cache_addition( true );
377
			/**
378
			 * Modify the data within an action before it is serialized and sent to the server
379
			 * For example, during full sync this expands Post ID's into full Post objects,
380
			 * so that we don't have to serialize the whole object into the queue.
381
			 *
382
			 * @since 4.2.0
383
			 *
384
			 * @param array The action parameters
385
			 * @param int The ID of the user who triggered the action
386
			 */
387
			$item[1] = apply_filters( 'jetpack_sync_before_send_' . $item[0], $item[1], $item[2] );
388
			wp_suspend_cache_addition( false );
389
			if ( false === $item[1] ) {
390
				$skipped_items_ids[] = $key;
391
				continue;
392
			}
393
			$encoded_item = $encode ? $this->codec->encode( $item ) : $item;
394
			$upload_size += strlen( $encoded_item );
395
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
396
				break;
397
			}
398
			$items_to_send[ $key ] = $encoded_item;
399
			if ( microtime( true ) - $start_time > $this->max_dequeue_time ) {
400
				break;
401
			}
402
		}
403
404
		return array( $items_to_send, $skipped_items_ids, $items, microtime( true ) - $start_time );
405
	}
406
407
	/**
408
	 * If supported, flush all response data to the client and finish the request.
409
	 * This allows for time consuming tasks to be performed without leaving the connection open.
410
	 *
411
	 * @access private
412
	 */
413
	private function fastcgi_finish_request() {
414
		if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
415
			fastcgi_finish_request();
416
		}
417
	}
418
419
	/**
420
	 * Perform sync for a certain sync queue.
421
	 *
422
	 * @access public
423
	 *
424
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
425
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
426
	 */
427
	public function do_sync_for_queue( $queue ) {
428
		do_action( 'jetpack_sync_before_send_queue_' . $queue->id );
429
		if ( $queue->size() === 0 ) {
430
			return new \WP_Error( 'empty_queue_' . $queue->id );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_queue_' . $queue->id.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
431
		}
432
		/**
433
		 * Now that we're sure we are about to sync, try to ignore user abort
434
		 * so we can avoid getting into a bad state.
435
		 */
436
		if ( function_exists( 'ignore_user_abort' ) ) {
437
			ignore_user_abort( true );
438
		}
439
440
		/* Don't make the request block till we finish, if possible. */
441
		if ( Constants::is_true( 'REST_REQUEST' ) || Constants::is_true( 'XMLRPC_REQUEST' ) ) {
442
			$this->fastcgi_finish_request();
443
		}
444
445
		$checkout_start_time = microtime( true );
446
447
		$buffer = $queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
448
449
		if ( ! $buffer ) {
450
			// Buffer has no items.
451
			return new \WP_Error( 'empty_buffer' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_buffer'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
452
		}
453
454
		if ( is_wp_error( $buffer ) ) {
455
			return $buffer;
456
		}
457
458
		$checkout_duration = microtime( true ) - $checkout_start_time;
459
460
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $buffer, true );
461
		if ( ! empty( $items_to_send ) ) {
462
			/**
463
			 * Fires when data is ready to send to the server.
464
			 * Return false or WP_Error to abort the sync (e.g. if there's an error)
465
			 * The items will be automatically re-sent later
466
			 *
467
			 * @since 4.2.0
468
			 *
469
			 * @param array $data The action buffer
470
			 * @param string $codec The codec name used to encode the data
471
			 * @param double $time The current time
472
			 * @param string $queue The queue used to send ('sync' or 'full_sync')
473
			 */
474
			Settings::set_is_sending( true );
475
			$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->codec->name(), microtime( true ), $queue->id, $checkout_duration, $preprocess_duration );
476
			Settings::set_is_sending( false );
477
		} else {
478
			$processed_item_ids = $skipped_items_ids;
479
			$skipped_items_ids  = array();
480
		}
481
482
		if ( ! $processed_item_ids || is_wp_error( $processed_item_ids ) ) {
483
			$checked_in_item_ids = $queue->checkin( $buffer );
484
			if ( is_wp_error( $checked_in_item_ids ) ) {
485
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
486
				error_log( 'Error checking in buffer: ' . $checked_in_item_ids->get_error_message() );
487
				$queue->force_checkin();
488
			}
489
			if ( is_wp_error( $processed_item_ids ) ) {
490
				return new \WP_Error( 'wpcom_error', $processed_item_ids->get_error_code() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
491
			}
492
			// Returning a wpcom_error is a sign to the caller that we should wait a while before syncing again.
493
			return new \WP_Error( 'wpcom_error', 'jetpack_sync_send_data_false' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
494
		} else {
495
			// Detect if the last item ID was an error.
496
			$had_wp_error = is_wp_error( end( $processed_item_ids ) );
497
			if ( $had_wp_error ) {
498
				$wp_error = array_pop( $processed_item_ids );
499
			}
500
			// Also checkin any items that were skipped.
501
			if ( count( $skipped_items_ids ) > 0 ) {
502
				$processed_item_ids = array_merge( $processed_item_ids, $skipped_items_ids );
503
			}
504
			$processed_items = array_intersect_key( $items, array_flip( $processed_item_ids ) );
505
			/**
506
			 * Allows us to keep track of all the actions that have been sent.
507
			 * Allows us to calculate the progress of specific actions.
508
			 *
509
			 * @since 4.2.0
510
			 *
511
			 * @param array $processed_actions The actions that we send successfully.
512
			 */
513
			do_action( 'jetpack_sync_processed_actions', $processed_items );
514
			$queue->close( $buffer, $processed_item_ids );
515
			// Returning a WP_Error is a sign to the caller that we should wait a while before syncing again.
516
			if ( $had_wp_error ) {
517
				return new \WP_Error( 'wpcom_error', $wp_error->get_error_code() );
0 ignored issues
show
Bug introduced by
The variable $wp_error does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
518
			}
519
		}
520
		return true;
521
	}
522
523
	/**
524
	 * Immediately sends a single item without firing or enqueuing it
525
	 *
526
	 * @param string $action_name The action.
527
	 * @param array  $data The data associated with the action.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $data not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
528
	 *
529
	 * @return Items processed. TODO: this doesn't make much sense anymore, it should probably be just a bool.
530
	 */
531
	public function send_action( $action_name, $data = null ) {
532
		if ( ! Settings::is_sender_enabled( 'full_sync' ) ) {
533
			return array();
534
		}
535
536
		// Compose the data to be sent.
537
		$action_to_send = $this->create_action_to_send( $action_name, $data );
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 531 can also be of type null; however, Automattic\Jetpack\Sync\...create_action_to_send() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
538
539
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $action_to_send, true ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
0 ignored issues
show
Unused Code introduced by
The assignment to $skipped_items_ids is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Unused Code introduced by
The assignment to $items is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
540
		Settings::set_is_sending( true );
541
		$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->get_codec()->name(), microtime( true ), 'immediate-send', 0, $preprocess_duration );
542
		Settings::set_is_sending( false );
543
544
		/**
545
		 * Allows us to keep track of all the actions that have been sent.
546
		 * Allows us to calculate the progress of specific actions.
547
		 *
548
		 * @param array $processed_actions The actions that we send successfully.
549
		 *
550
		 * @since 4.2.0
551
		 */
552
		do_action( 'jetpack_sync_processed_actions', $action_to_send );
553
554
		return $processed_item_ids;
555
	}
556
557
	/**
558
	 * Create an synthetic action for direct sending to WPCOM during full sync (for example)
559
	 *
560
	 * @access private
561
	 *
562
	 * @param string $action_name The action.
563
	 * @param array  $data The data associated with the action.
564
	 * @return array An array of synthetic sync actions keyed by current microtime(true)
565
	 */
566
	private function create_action_to_send( $action_name, $data ) {
567
		return array(
568
			microtime( true ) => array(
569
				$action_name,
570
				$data,
571
				get_current_user_id(),
572
				microtime( true ),
573
				Settings::is_importing(),
574
			),
575
		);
576
	}
577
578
	/**
579
	 * Returns any object that is able to be synced.
580
	 *
581
	 * @access public
582
	 *
583
	 * @param array $args the synchronized object parameters.
584
	 * @return string Encoded sync object.
585
	 */
586
	public function sync_object( $args ) {
587
		// For example: posts, post, 5.
588
		list( $module_name, $object_type, $id ) = $args;
589
590
		$sync_module = Modules::get_module( $module_name );
591
		$codec       = $this->get_codec();
592
593
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
594
	}
595
596
	/**
597
	 * Register additional sync XML-RPC methods available to Jetpack for authenticated users.
598
	 *
599
	 * @access public
600
	 * @since 7.8
601
	 *
602
	 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
603
	 * @return array Filtered XML-RPC methods.
604
	 */
605
	public function register_jetpack_xmlrpc_methods( $jetpack_methods ) {
606
		$jetpack_methods['jetpack.syncObject'] = array( $this, 'sync_object' );
607
		return $jetpack_methods;
608
	}
609
610
	/**
611
	 * Get the incremental sync queue object.
612
	 *
613
	 * @access public
614
	 *
615
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
616
	 */
617
	public function get_sync_queue() {
618
		return $this->sync_queue;
619
	}
620
621
	/**
622
	 * Get the full sync queue object.
623
	 *
624
	 * @access public
625
	 *
626
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
627
	 */
628
	public function get_full_sync_queue() {
629
		return $this->full_sync_queue;
630
	}
631
632
	/**
633
	 * Get the codec object.
634
	 *
635
	 * @access public
636
	 *
637
	 * @return Automattic\Jetpack\Sync\Codec_Interface Codec object.
638
	 */
639
	public function get_codec() {
640
		return $this->codec;
641
	}
642
643
	/**
644
	 * Determine the codec object.
645
	 * Use gzip deflate if supported.
646
	 *
647
	 * @access public
648
	 */
649
	public function set_codec() {
650
		if ( function_exists( 'gzinflate' ) ) {
651
			$this->codec = new JSON_Deflate_Array_Codec();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\...N_Deflate_Array_Codec() of type object<Automattic\Jetpac...ON_Deflate_Array_Codec> is incompatible with the declared type object<Automattic\Jetpac...k\Sync\Codec_Interface> of property $codec.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
652
		} else {
653
			$this->codec = new Simple_Codec();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Simple_Codec() of type object<Automattic\Jetpack\Sync\Simple_Codec> is incompatible with the declared type object<Automattic\Jetpac...k\Sync\Codec_Interface> of property $codec.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
654
		}
655
	}
656
657
	/**
658
	 * Compute and send all the checksums.
659
	 *
660
	 * @access public
661
	 */
662
	public function send_checksum() {
663
		$store = new Replicastore();
664
		do_action( 'jetpack_sync_checksum', $store->checksum_all() );
665
	}
666
667
	/**
668
	 * Reset the incremental sync queue.
669
	 *
670
	 * @access public
671
	 */
672
	public function reset_sync_queue() {
673
		$this->sync_queue->reset();
674
	}
675
676
	/**
677
	 * Reset the full sync queue.
678
	 *
679
	 * @access public
680
	 */
681
	public function reset_full_sync_queue() {
682
		$this->full_sync_queue->reset();
683
	}
684
685
	/**
686
	 * Set the maximum bytes to checkout without exceeding the memory limit.
687
	 *
688
	 * @access public
689
	 *
690
	 * @param int $size Maximum bytes to checkout.
691
	 */
692
	public function set_dequeue_max_bytes( $size ) {
693
		$this->dequeue_max_bytes = $size;
694
	}
695
696
	/**
697
	 * Set the maximum bytes in a single encoded item.
698
	 *
699
	 * @access public
700
	 *
701
	 * @param int $max_bytes Maximum bytes in a single encoded item.
702
	 */
703
	public function set_upload_max_bytes( $max_bytes ) {
704
		$this->upload_max_bytes = $max_bytes;
705
	}
706
707
	/**
708
	 * Set the maximum number of sync items in a single action.
709
	 *
710
	 * @access public
711
	 *
712
	 * @param int $max_rows Maximum number of sync items.
713
	 */
714
	public function set_upload_max_rows( $max_rows ) {
715
		$this->upload_max_rows = $max_rows;
716
	}
717
718
	/**
719
	 * Set the sync wait time (in seconds).
720
	 *
721
	 * @access public
722
	 *
723
	 * @param int $seconds Sync wait time.
724
	 */
725
	public function set_sync_wait_time( $seconds ) {
726
		$this->sync_wait_time = $seconds;
727
	}
728
729
	/**
730
	 * Get current sync wait time (in seconds).
731
	 *
732
	 * @access public
733
	 *
734
	 * @return int Sync wait time.
735
	 */
736
	public function get_sync_wait_time() {
737
		return $this->sync_wait_time;
738
	}
739
740
	/**
741
	 * Set the enqueue wait time (in seconds).
742
	 *
743
	 * @access public
744
	 *
745
	 * @param int $seconds Enqueue wait time.
746
	 */
747
	public function set_enqueue_wait_time( $seconds ) {
748
		$this->enqueue_wait_time = $seconds;
749
	}
750
751
	/**
752
	 * Get current enqueue wait time (in seconds).
753
	 *
754
	 * @access public
755
	 *
756
	 * @return int Enqueue wait time.
757
	 */
758
	public function get_enqueue_wait_time() {
759
		return $this->enqueue_wait_time;
760
	}
761
762
	/**
763
	 * Set the sync wait threshold (in seconds).
764
	 *
765
	 * @access public
766
	 *
767
	 * @param int $seconds Sync wait threshold.
768
	 */
769
	public function set_sync_wait_threshold( $seconds ) {
770
		$this->sync_wait_threshold = $seconds;
771
	}
772
773
	/**
774
	 * Get current sync wait threshold (in seconds).
775
	 *
776
	 * @access public
777
	 *
778
	 * @return int Sync wait threshold.
779
	 */
780
	public function get_sync_wait_threshold() {
781
		return $this->sync_wait_threshold;
782
	}
783
784
	/**
785
	 * Set the maximum time for perfirming a checkout of items from the queue (in seconds).
786
	 *
787
	 * @access public
788
	 *
789
	 * @param int $seconds Maximum dequeue time.
790
	 */
791
	public function set_max_dequeue_time( $seconds ) {
792
		$this->max_dequeue_time = $seconds;
793
	}
794
795
	/**
796
	 * Initialize the sync queues, codec and set the default settings.
797
	 *
798
	 * @access public
799
	 */
800
	public function set_defaults() {
801
		$this->sync_queue      = new Queue( 'sync' );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Queue('sync') of type object<Automattic\Jetpack\Sync\Queue> is incompatible with the declared type object<Automattic\Jetpac...tic\Jetpack\Sync\Queue> of property $sync_queue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
802
		$this->full_sync_queue = new Queue( 'full_sync' );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Queue('full_sync') of type object<Automattic\Jetpack\Sync\Queue> is incompatible with the declared type object<Automattic\Jetpac...tic\Jetpack\Sync\Queue> of property $full_sync_queue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
803
		$this->set_codec();
804
805
		// Saved settings.
806
		Settings::set_importing( null );
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
807
		$settings = Settings::get_settings();
808
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
809
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
810
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
811
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
812
		$this->set_enqueue_wait_time( $settings['enqueue_wait_time'] );
813
		$this->set_sync_wait_threshold( $settings['sync_wait_threshold'] );
814
		$this->set_max_dequeue_time( Defaults::get_max_sync_execution_time() );
815
	}
816
817
	/**
818
	 * Reset sync queues, modules and settings.
819
	 *
820
	 * @access public
821
	 */
822
	public function reset_data() {
823
		$this->reset_sync_queue();
824
		$this->reset_full_sync_queue();
825
826
		foreach ( Modules::get_modules() as $module ) {
827
			$module->reset_data();
828
		}
829
830
		foreach ( array( 'sync', 'full_sync', 'full-sync-enqueue' ) as $queue_name ) {
831
			delete_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name );
832
		}
833
834
		Settings::reset_data();
835
	}
836
837
	/**
838
	 * Perform cleanup at the event of plugin uninstallation.
839
	 *
840
	 * @access public
841
	 */
842
	public function uninstall() {
843
		// Lets delete all the other fun stuff like transient and option and the sync queue.
844
		$this->reset_data();
845
846
		// Delete the full sync status.
847
		delete_option( 'jetpack_full_sync_status' );
848
849
		// Clear the sync cron.
850
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
851
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
852
	}
853
}
854