Completed
Push — add/cli ( 74cf7f...2842da )
by
unknown
10:13
created

Sender::do_sync_and_set_delays()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 10
nop 1
dl 0
loc 44
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Sync sender.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
use Automattic\Jetpack\Connection\Manager;
11
use Automattic\Jetpack\Constants;
12
13
/**
14
 * This class grabs pending actions from the queue and sends them
15
 */
16
class Sender {
17
	/**
18
	 * Name of the option that stores the time of the next sync.
19
	 *
20
	 * @access public
21
	 *
22
	 * @var string
23
	 */
24
	const NEXT_SYNC_TIME_OPTION_NAME = 'jetpack_next_sync_time';
25
26
	/**
27
	 * Sync timeout after a WPCOM error.
28
	 *
29
	 * @access public
30
	 *
31
	 * @var int
32
	 */
33
	const WPCOM_ERROR_SYNC_DELAY = 60;
34
35
	/**
36
	 * Sync timeout after a queue has been locked.
37
	 *
38
	 * @access public
39
	 *
40
	 * @var int
41
	 */
42
	const QUEUE_LOCKED_SYNC_DELAY = 10;
43
44
	/**
45
	 * Maximum bytes to checkout without exceeding the memory limit.
46
	 *
47
	 * @access private
48
	 *
49
	 * @var int
50
	 */
51
	private $dequeue_max_bytes;
52
53
	/**
54
	 * Maximum bytes in a single encoded item.
55
	 *
56
	 * @access private
57
	 *
58
	 * @var int
59
	 */
60
	private $upload_max_bytes;
61
62
	/**
63
	 * Maximum number of sync items in a single action.
64
	 *
65
	 * @access private
66
	 *
67
	 * @var int
68
	 */
69
	private $upload_max_rows;
70
71
	/**
72
	 * Maximum time for perfirming a checkout of items from the queue (in seconds).
73
	 *
74
	 * @access private
75
	 *
76
	 * @var int
77
	 */
78
	private $max_dequeue_time;
79
80
	/**
81
	 * How many seconds to wait after sending sync items after exceeding the sync wait threshold (in seconds).
82
	 *
83
	 * @access private
84
	 *
85
	 * @var int
86
	 */
87
	private $sync_wait_time;
88
89
	/**
90
	 * How much maximum time to wait for the checkout to finish (in seconds).
91
	 *
92
	 * @access private
93
	 *
94
	 * @var int
95
	 */
96
	private $sync_wait_threshold;
97
98
	/**
99
	 * How much maximum time to wait for the sync items to be queued for sending (in seconds).
100
	 *
101
	 * @access private
102
	 *
103
	 * @var int
104
	 */
105
	private $enqueue_wait_time;
106
107
	/**
108
	 * Incremental sync queue object.
109
	 *
110
	 * @access private
111
	 *
112
	 * @var Automattic\Jetpack\Sync\Queue
113
	 */
114
	private $sync_queue;
115
116
	/**
117
	 * Full sync queue object.
118
	 *
119
	 * @access private
120
	 *
121
	 * @var Automattic\Jetpack\Sync\Queue
122
	 */
123
	private $full_sync_queue;
124
125
	/**
126
	 * Codec object for encoding and decoding sync items.
127
	 *
128
	 * @access private
129
	 *
130
	 * @var Automattic\Jetpack\Sync\Codec_Interface
131
	 */
132
	private $codec;
133
134
	/**
135
	 * The current user before we change or clear it.
136
	 *
137
	 * @access private
138
	 *
139
	 * @var \WP_User
140
	 */
141
	private $old_user;
142
143
	/**
144
	 * Container for the singleton instance of this class.
145
	 *
146
	 * @access private
147
	 * @static
148
	 *
149
	 * @var Automattic\Jetpack\Sync\Sender
150
	 */
151
	private static $instance;
152
153
	/**
154
	 * Retrieve the singleton instance of this class.
155
	 *
156
	 * @access public
157
	 * @static
158
	 *
159
	 * @return Sender
160
	 */
161
	public static function get_instance() {
162
		if ( null === self::$instance ) {
163
			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...
164
		}
165
166
		return self::$instance;
167
	}
168
169
	/**
170
	 * Constructor.
171
	 * This is necessary because you can't use "new" when you declare instance properties >:(
172
	 *
173
	 * @access protected
174
	 * @static
175
	 */
176
	protected function __construct() {
177
		$this->set_defaults();
178
		$this->init();
179
	}
180
181
	/**
182
	 * Initialize the sender.
183
	 * Prepares the current user and initializes all sync modules.
184
	 *
185
	 * @access private
186
	 */
187
	private function init() {
188
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_set_user_from_token' ), 1 );
189
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_clear_user_from_token' ), 20 );
190
		add_filter( 'jetpack_xmlrpc_unauthenticated_methods', array( $this, 'register_jetpack_xmlrpc_methods' ) );
191
		foreach ( Modules::get_modules() as $module ) {
192
			$module->init_before_send();
193
		}
194
	}
195
196
	/**
197
	 * Detect if this is a XMLRPC request with a valid signature.
198
	 * If so, changes the user to the new one.
199
	 *
200
	 * @access public
201
	 */
202
	public function maybe_set_user_from_token() {
203
		$connection    = new Manager();
204
		$verified_user = $connection->verify_xml_rpc_signature();
205
		if ( Constants::is_true( 'XMLRPC_REQUEST' ) &&
206
			! is_wp_error( $verified_user )
207
			&& $verified_user
208
		) {
209
			$old_user       = wp_get_current_user();
210
			$this->old_user = isset( $old_user->ID ) ? $old_user->ID : 0;
211
			wp_set_current_user( $verified_user['user_id'] );
212
		}
213
	}
214
215
	/**
216
	 * If we used to have a previous current user, revert back to it.
217
	 *
218
	 * @access public
219
	 */
220
	public function maybe_clear_user_from_token() {
221
		if ( isset( $this->old_user ) ) {
222
			wp_set_current_user( $this->old_user );
223
		}
224
	}
225
226
	/**
227
	 * Retrieve the next sync time.
228
	 *
229
	 * @access public
230
	 *
231
	 * @param string $queue_name Name of the queue.
232
	 * @return float Timestamp of the next sync.
233
	 */
234
	public function get_next_sync_time( $queue_name ) {
235
		return (float) get_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, 0 );
236
	}
237
238
	/**
239
	 * Set the next sync time.
240
	 *
241
	 * @access public
242
	 *
243
	 * @param int    $time       Timestamp of the next sync.
244
	 * @param string $queue_name Name of the queue.
245
	 * @return boolean True if update was successful, false otherwise.
246
	 */
247
	public function set_next_sync_time( $time, $queue_name ) {
248
		return update_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, $time, true );
249
	}
250
251
	/**
252
	 * Trigger a full sync.
253
	 *
254
	 * @access public
255
	 *
256
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
257
	 */
258
	public function do_full_sync() {
259
		$sync_module = Modules::get_module( 'full-sync' );
260
		if ( ! $sync_module ) {
261
			return;
262
		}
263
		if ( ! Settings::get_setting( 'full_sync_sender_enabled' ) ) {
264
			return;
265
		}
266
267
		// Don't sync if request is marked as read only.
268
		if ( Constants::is_true( 'JETPACK_SYNC_READ_ONLY' ) ) {
269
			return new \WP_Error( 'jetpack_sync_read_only' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_sync_read_only'.

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...
270
		}
271
272
		$this->continue_full_sync_enqueue();
273
		// immediate full sync sends data in continue_full_sync_enqueue.
274
		if ( false === strpos( get_class( $sync_module ), 'Full_Sync_Immediately' ) ) {
275
			return $this->do_sync_and_set_delays( $this->full_sync_queue );
276
		} else {
277
			$status = $sync_module->get_status();
278
			// Sync not started or Sync finished.
279
			if ( false === $status['started'] || ( ! empty( $status['started'] ) && ! empty( $status['finished'] ) ) ) {
280
				return false;
281
			} else {
282
				return true;
283
			}
284
		}
285
	}
286
287
	/**
288
	 * Enqueue the next sync items for sending.
289
	 * Will not be done if the current request is a WP import one.
290
	 * Will be delayed until the next sync time comes.
291
	 *
292
	 * @access private
293
	 */
294
	private function continue_full_sync_enqueue() {
295
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
296
			return false;
297
		}
298
299
		if ( $this->get_next_sync_time( 'full-sync-enqueue' ) > microtime( true ) ) {
300
			return false;
301
		}
302
303
		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...
304
305
		$this->set_next_sync_time( time() + $this->get_enqueue_wait_time(), 'full-sync-enqueue' );
306
	}
307
308
	/**
309
	 * Trigger incremental sync.
310
	 *
311
	 * @access public
312
	 *
313
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
314
	 */
315
	public function do_sync() {
316
		return $this->do_sync_and_set_delays( $this->sync_queue );
317
	}
318
319
	/**
320
	 * Trigger sync for a certain sync queue.
321
	 * Responsible for setting next sync time.
322
	 * Will not be delayed if the current request is a WP import one.
323
	 * Will be delayed until the next sync time comes.
324
	 *
325
	 * @access public
326
	 *
327
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
328
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
329
	 */
330
	public function do_sync_and_set_delays( $queue ) {
331
		// Don't sync if importing.
332
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
333
			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...
334
		}
335
336
		// Don't sync if request is marked as read only.
337
		if ( Constants::is_true( 'JETPACK_SYNC_READ_ONLY' ) ) {
338
			return new \WP_Error( 'jetpack_sync_read_only' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_sync_read_only'.

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...
339
		}
340
341
		if ( ! Settings::is_sender_enabled( $queue->id ) ) {
342
			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...
343
		}
344
345
		// Don't sync if we are throttled.
346
		if ( $this->get_next_sync_time( $queue->id ) > microtime( true ) ) {
347
			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...
348
		}
349
350
		$start_time = microtime( true );
351
352
		Settings::set_is_syncing( true );
353
354
		$sync_result = $this->do_sync_for_queue( $queue );
355
356
		Settings::set_is_syncing( false );
357
358
		$exceeded_sync_wait_threshold = ( microtime( true ) - $start_time ) > (float) $this->get_sync_wait_threshold();
359
360
		if ( is_wp_error( $sync_result ) ) {
361
			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...
362
				$this->set_next_sync_time( time() + self::QUEUE_LOCKED_SYNC_DELAY, $queue->id );
363
			}
364
			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...
365
				$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY, $queue->id );
366
			}
367
		} elseif ( $exceeded_sync_wait_threshold ) {
368
			// If we actually sent data and it took a while, wait before sending again.
369
			$this->set_next_sync_time( time() + $this->get_sync_wait_time(), $queue->id );
370
		}
371
372
		return $sync_result;
373
	}
374
375
	/**
376
	 * Retrieve the next sync items to send.
377
	 *
378
	 * @access public
379
	 *
380
	 * @param (array|Automattic\Jetpack\Sync\Queue_Buffer) $buffer_or_items Queue buffer or array of objects.
381
	 * @param boolean                                      $encode Whether to encode the items.
382
	 * @return array Sync items to send.
383
	 */
384
	public function get_items_to_send( $buffer_or_items, $encode = true ) {
385
		// Track how long we've been processing so we can avoid request timeouts.
386
		$start_time    = microtime( true );
387
		$upload_size   = 0;
388
		$items_to_send = array();
389
		$items         = is_array( $buffer_or_items ) ? $buffer_or_items : $buffer_or_items->get_items();
390
		// Set up current screen to avoid errors rendering content.
391
		require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
392
		require_once ABSPATH . 'wp-admin/includes/screen.php';
393
		set_current_screen( 'sync' );
394
		$skipped_items_ids = array();
395
		/**
396
		 * We estimate the total encoded size as we go by encoding each item individually.
397
		 * This is expensive, but the only way to really know :/
398
		 */
399
		foreach ( $items as $key => $item ) {
400
			// Suspending cache addition help prevent overloading in memory cache of large sites.
401
			wp_suspend_cache_addition( true );
402
			/**
403
			 * Modify the data within an action before it is serialized and sent to the server
404
			 * For example, during full sync this expands Post ID's into full Post objects,
405
			 * so that we don't have to serialize the whole object into the queue.
406
			 *
407
			 * @since 4.2.0
408
			 *
409
			 * @param array The action parameters
410
			 * @param int The ID of the user who triggered the action
411
			 */
412
			$item[1] = apply_filters( 'jetpack_sync_before_send_' . $item[0], $item[1], $item[2] );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $item[2].

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...
413
			wp_suspend_cache_addition( false );
414
			if ( false === $item[1] ) {
415
				$skipped_items_ids[] = $key;
416
				continue;
417
			}
418
			$encoded_item = $encode ? $this->codec->encode( $item ) : $item;
419
			$upload_size += strlen( $encoded_item );
420
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
421
				break;
422
			}
423
			$items_to_send[ $key ] = $encoded_item;
424
			if ( microtime( true ) - $start_time > $this->max_dequeue_time ) {
425
				break;
426
			}
427
		}
428
429
		return array( $items_to_send, $skipped_items_ids, $items, microtime( true ) - $start_time );
430
	}
431
432
	/**
433
	 * If supported, flush all response data to the client and finish the request.
434
	 * This allows for time consuming tasks to be performed without leaving the connection open.
435
	 *
436
	 * @access private
437
	 */
438
	private function fastcgi_finish_request() {
439
		if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
440
			fastcgi_finish_request();
441
		}
442
	}
443
444
	/**
445
	 * Perform sync for a certain sync queue.
446
	 *
447
	 * @access public
448
	 *
449
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
450
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
451
	 */
452
	public function do_sync_for_queue( $queue ) {
453
		do_action( 'jetpack_sync_before_send_queue_' . $queue->id );
454
		if ( $queue->size() === 0 ) {
455
			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...
456
		}
457
458
		/**
459
		 * Now that we're sure we are about to sync, try to ignore user abort
460
		 * so we can avoid getting into a bad state.
461
		 */
462
		if ( function_exists( 'ignore_user_abort' ) ) {
463
			ignore_user_abort( true );
464
		}
465
466
		/* Don't make the request block till we finish, if possible. */
467
		if ( Constants::is_true( 'REST_REQUEST' ) || Constants::is_true( 'XMLRPC_REQUEST' ) ) {
468
			$this->fastcgi_finish_request();
469
		}
470
471
		$checkout_start_time = microtime( true );
472
473
		$buffer = $queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
474
475
		if ( ! $buffer ) {
476
			// Buffer has no items.
477
			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...
478
		}
479
480
		if ( is_wp_error( $buffer ) ) {
481
			return $buffer;
482
		}
483
484
		$checkout_duration = microtime( true ) - $checkout_start_time;
485
486
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $buffer, true );
487
		if ( ! empty( $items_to_send ) ) {
488
			/**
489
			 * Fires when data is ready to send to the server.
490
			 * Return false or WP_Error to abort the sync (e.g. if there's an error)
491
			 * The items will be automatically re-sent later
492
			 *
493
			 * @since 4.2.0
494
			 *
495
			 * @param array  $data The action buffer
496
			 * @param string $codec The codec name used to encode the data
497
			 * @param double $time The current time
498
			 * @param string $queue The queue used to send ('sync' or 'full_sync')
499
			 * @param float  $checkout_duration The duration of the checkout operation.
500
			 * @param float  $preprocess_duration The duration of the pre-process operation.
501
			 * @param int    $queue_size The size of the sync queue at the time of processing.
502
			 */
503
			Settings::set_is_sending( true );
504
			$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->codec->name(), microtime( true ), $queue->id, $checkout_duration, $preprocess_duration, $queue->size(), $buffer->id );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this->codec->name().

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...
505
			Settings::set_is_sending( false );
506
		} else {
507
			$processed_item_ids = $skipped_items_ids;
508
			$skipped_items_ids  = array();
509
		}
510
511
		if ( 'non-blocking' !== $processed_item_ids ) {
512
			if ( ! $processed_item_ids || is_wp_error( $processed_item_ids ) ) {
513
				$checked_in_item_ids = $queue->checkin( $buffer );
514
				if ( is_wp_error( $checked_in_item_ids ) ) {
515
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
516
					error_log( 'Error checking in buffer: ' . $checked_in_item_ids->get_error_message() );
517
					$queue->force_checkin();
518
				}
519
				if ( is_wp_error( $processed_item_ids ) ) {
520
					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...
521
				}
522
523
				// Returning a wpcom_error is a sign to the caller that we should wait a while before syncing again.
524
				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...
525
			} else {
526
				// Detect if the last item ID was an error.
527
				$had_wp_error = is_wp_error( end( $processed_item_ids ) );
528
				if ( $had_wp_error ) {
529
					$wp_error = array_pop( $processed_item_ids );
530
				}
531
				// Also checkin any items that were skipped.
532
				if ( count( $skipped_items_ids ) > 0 ) {
533
					$processed_item_ids = array_merge( $processed_item_ids, $skipped_items_ids );
534
				}
535
				$processed_items = array_intersect_key( $items, array_flip( $processed_item_ids ) );
536
				/**
537
				 * Allows us to keep track of all the actions that have been sent.
538
				 * Allows us to calculate the progress of specific actions.
539
				 *
540
				 * @since 4.2.0
541
				 *
542
				 * @param array $processed_actions The actions that we send successfully.
543
				 */
544
				do_action( 'jetpack_sync_processed_actions', $processed_items );
545
				$queue->close( $buffer, $processed_item_ids );
546
				// Returning a WP_Error is a sign to the caller that we should wait a while before syncing again.
547
				if ( $had_wp_error ) {
548
					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...
549
				}
550
			}
551
		}
552
553
		return true;
554
	}
555
556
	/**
557
	 * Immediately sends a single item without firing or enqueuing it
558
	 *
559
	 * @param string $action_name The action.
560
	 * @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...
561
	 *
562
	 * @return Items processed. TODO: this doesn't make much sense anymore, it should probably be just a bool.
563
	 */
564
	public function send_action( $action_name, $data = null ) {
565
		if ( ! Settings::is_sender_enabled( 'full_sync' ) ) {
566
			return array();
567
		}
568
569
		// Compose the data to be sent.
570
		$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 564 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...
571
572
		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...
573
		Settings::set_is_sending( true );
574
		$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->get_codec()->name(), microtime( true ), 'immediate-send', 0, $preprocess_duration );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this->get_codec()->name().

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...
575
		Settings::set_is_sending( false );
576
577
		/**
578
		 * Allows us to keep track of all the actions that have been sent.
579
		 * Allows us to calculate the progress of specific actions.
580
		 *
581
		 * @param array $processed_actions The actions that we send successfully.
582
		 *
583
		 * @since 4.2.0
584
		 */
585
		do_action( 'jetpack_sync_processed_actions', $action_to_send );
586
587
		return $processed_item_ids;
588
	}
589
590
	/**
591
	 * Create an synthetic action for direct sending to WPCOM during full sync (for example)
592
	 *
593
	 * @access private
594
	 *
595
	 * @param string $action_name The action.
596
	 * @param array  $data The data associated with the action.
597
	 * @return array An array of synthetic sync actions keyed by current microtime(true)
598
	 */
599
	private function create_action_to_send( $action_name, $data ) {
600
		return array(
601
			(string) microtime( true ) => array(
602
				$action_name,
603
				$data,
604
				get_current_user_id(),
605
				microtime( true ),
606
				Settings::is_importing(),
607
			),
608
		);
609
	}
610
611
	/**
612
	 * Returns any object that is able to be synced.
613
	 *
614
	 * @access public
615
	 *
616
	 * @param array $args the synchronized object parameters.
617
	 * @return string Encoded sync object.
618
	 */
619
	public function sync_object( $args ) {
620
		// For example: posts, post, 5.
621
		list( $module_name, $object_type, $id ) = $args;
622
623
		$sync_module = Modules::get_module( $module_name );
624
		$codec       = $this->get_codec();
625
626
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
627
	}
628
629
	/**
630
	 * Register additional sync XML-RPC methods available to Jetpack for authenticated users.
631
	 *
632
	 * @access public
633
	 * @since 7.8
634
	 *
635
	 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
636
	 * @return array Filtered XML-RPC methods.
637
	 */
638
	public function register_jetpack_xmlrpc_methods( $jetpack_methods ) {
639
		$jetpack_methods['jetpack.syncObject'] = array( $this, 'sync_object' );
640
		return $jetpack_methods;
641
	}
642
643
	/**
644
	 * Get the incremental sync queue object.
645
	 *
646
	 * @access public
647
	 *
648
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
649
	 */
650
	public function get_sync_queue() {
651
		return $this->sync_queue;
652
	}
653
654
	/**
655
	 * Get the full sync queue object.
656
	 *
657
	 * @access public
658
	 *
659
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
660
	 */
661
	public function get_full_sync_queue() {
662
		return $this->full_sync_queue;
663
	}
664
665
	/**
666
	 * Get the codec object.
667
	 *
668
	 * @access public
669
	 *
670
	 * @return Automattic\Jetpack\Sync\Codec_Interface Codec object.
671
	 */
672
	public function get_codec() {
673
		return $this->codec;
674
	}
675
676
	/**
677
	 * Determine the codec object.
678
	 * Use gzip deflate if supported.
679
	 *
680
	 * @access public
681
	 */
682
	public function set_codec() {
683
		if ( function_exists( 'gzinflate' ) ) {
684
			$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...
685
		} else {
686
			$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...
687
		}
688
	}
689
690
	/**
691
	 * Compute and send all the checksums.
692
	 *
693
	 * @access public
694
	 */
695
	public function send_checksum() {
696
		$store = new Replicastore();
697
		do_action( 'jetpack_sync_checksum', $store->checksum_all() );
698
	}
699
700
	/**
701
	 * Reset the incremental sync queue.
702
	 *
703
	 * @access public
704
	 */
705
	public function reset_sync_queue() {
706
		$this->sync_queue->reset();
707
	}
708
709
	/**
710
	 * Reset the full sync queue.
711
	 *
712
	 * @access public
713
	 */
714
	public function reset_full_sync_queue() {
715
		$this->full_sync_queue->reset();
716
	}
717
718
	/**
719
	 * Set the maximum bytes to checkout without exceeding the memory limit.
720
	 *
721
	 * @access public
722
	 *
723
	 * @param int $size Maximum bytes to checkout.
724
	 */
725
	public function set_dequeue_max_bytes( $size ) {
726
		$this->dequeue_max_bytes = $size;
727
	}
728
729
	/**
730
	 * Set the maximum bytes in a single encoded item.
731
	 *
732
	 * @access public
733
	 *
734
	 * @param int $max_bytes Maximum bytes in a single encoded item.
735
	 */
736
	public function set_upload_max_bytes( $max_bytes ) {
737
		$this->upload_max_bytes = $max_bytes;
738
	}
739
740
	/**
741
	 * Set the maximum number of sync items in a single action.
742
	 *
743
	 * @access public
744
	 *
745
	 * @param int $max_rows Maximum number of sync items.
746
	 */
747
	public function set_upload_max_rows( $max_rows ) {
748
		$this->upload_max_rows = $max_rows;
749
	}
750
751
	/**
752
	 * Set the sync wait time (in seconds).
753
	 *
754
	 * @access public
755
	 *
756
	 * @param int $seconds Sync wait time.
757
	 */
758
	public function set_sync_wait_time( $seconds ) {
759
		$this->sync_wait_time = $seconds;
760
	}
761
762
	/**
763
	 * Get current sync wait time (in seconds).
764
	 *
765
	 * @access public
766
	 *
767
	 * @return int Sync wait time.
768
	 */
769
	public function get_sync_wait_time() {
770
		return $this->sync_wait_time;
771
	}
772
773
	/**
774
	 * Set the enqueue wait time (in seconds).
775
	 *
776
	 * @access public
777
	 *
778
	 * @param int $seconds Enqueue wait time.
779
	 */
780
	public function set_enqueue_wait_time( $seconds ) {
781
		$this->enqueue_wait_time = $seconds;
782
	}
783
784
	/**
785
	 * Get current enqueue wait time (in seconds).
786
	 *
787
	 * @access public
788
	 *
789
	 * @return int Enqueue wait time.
790
	 */
791
	public function get_enqueue_wait_time() {
792
		return $this->enqueue_wait_time;
793
	}
794
795
	/**
796
	 * Set the sync wait threshold (in seconds).
797
	 *
798
	 * @access public
799
	 *
800
	 * @param int $seconds Sync wait threshold.
801
	 */
802
	public function set_sync_wait_threshold( $seconds ) {
803
		$this->sync_wait_threshold = $seconds;
804
	}
805
806
	/**
807
	 * Get current sync wait threshold (in seconds).
808
	 *
809
	 * @access public
810
	 *
811
	 * @return int Sync wait threshold.
812
	 */
813
	public function get_sync_wait_threshold() {
814
		return $this->sync_wait_threshold;
815
	}
816
817
	/**
818
	 * Set the maximum time for perfirming a checkout of items from the queue (in seconds).
819
	 *
820
	 * @access public
821
	 *
822
	 * @param int $seconds Maximum dequeue time.
823
	 */
824
	public function set_max_dequeue_time( $seconds ) {
825
		$this->max_dequeue_time = $seconds;
826
	}
827
828
	/**
829
	 * Initialize the sync queues, codec and set the default settings.
830
	 *
831
	 * @access public
832
	 */
833
	public function set_defaults() {
834
		$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...
835
		$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...
836
		$this->set_codec();
837
838
		// Saved settings.
839
		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...
840
		$settings = Settings::get_settings();
841
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
842
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
843
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
844
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
845
		$this->set_enqueue_wait_time( $settings['enqueue_wait_time'] );
846
		$this->set_sync_wait_threshold( $settings['sync_wait_threshold'] );
847
		$this->set_max_dequeue_time( Defaults::get_max_sync_execution_time() );
848
	}
849
850
	/**
851
	 * Reset sync queues, modules and settings.
852
	 *
853
	 * @access public
854
	 */
855
	public function reset_data() {
856
		$this->reset_sync_queue();
857
		$this->reset_full_sync_queue();
858
859
		foreach ( Modules::get_modules() as $module ) {
860
			$module->reset_data();
861
		}
862
863
		foreach ( array( 'sync', 'full_sync', 'full-sync-enqueue' ) as $queue_name ) {
864
			delete_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name );
865
		}
866
867
		Settings::reset_data();
868
	}
869
870
	/**
871
	 * Perform cleanup at the event of plugin uninstallation.
872
	 *
873
	 * @access public
874
	 */
875
	public function uninstall() {
876
		// Lets delete all the other fun stuff like transient and option and the sync queue.
877
		$this->reset_data();
878
879
		// Delete the full sync status.
880
		delete_option( 'jetpack_full_sync_status' );
881
882
		// Clear the sync cron.
883
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
884
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
885
	}
886
}
887