Completed
Push — add/sync-middleware ( f86d2e...2f7ec8 )
by
unknown
09:17
created

Jetpack_Sync_Sender::handle_packages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
require_once dirname( __FILE__ ) . '/class.jetpack-sync-queue.php';
4
require_once dirname( __FILE__ ) . '/class.jetpack-sync-defaults.php';
5
require_once dirname( __FILE__ ) . '/class.jetpack-sync-json-deflate-array-codec.php';
6
require_once dirname( __FILE__ ) . '/class.jetpack-sync-modules.php';
7
require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
8
require_once dirname( __FILE__ ) . '/class.jetpack-sync-packager.php';
9
10
/**
11
 * This class grabs pending actions from the queue and sends them
12
 */
13
class Jetpack_Sync_Sender {
14
15
	const NEXT_SYNC_TIME_OPTION_NAME = 'jetpack_next_sync_time';
16
	const WPCOM_ERROR_SYNC_DELAY = 60;
17
	const QUEUE_LOCKED_SYNC_DELAY = 10;
18
19
	private $dequeue_max_bytes;
20
	private $upload_max_bytes;
21
	private $upload_max_rows;
22
	private $max_dequeue_time;
23
	private $sync_wait_time;
24
	private $sync_wait_threshold;
25
	private $enqueue_wait_time;
26
	private $sync_queue;
27
	private $full_sync_queue;
28
	private $packager;
29
	private $codec;
30
	private $old_user;
31
32
	// singleton functions
33
	private static $instance;
34
35
	public static function get_instance() {
36
		if ( null === self::$instance ) {
37
			self::$instance = new self();
38
		}
39
40
		return self::$instance;
41
	}
42
43
	// this is necessary because you can't use "new" when you declare instance properties >:(
44
	protected function __construct() {
45
		$this->set_defaults();
46
		$this->init();
47
	}
48
49
	private function init() {
50
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_set_user_from_token' ), 1 );
51
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_clear_user_from_token' ), 20 );
52
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
53
			$module->init_before_send();
54
		}
55
	}
56
57
	public function maybe_set_user_from_token( ) {
58
		$jetpack = Jetpack::init();
59
		$verified_user = $jetpack->verify_xml_rpc_signature();
60
		if ( Jetpack_Constants::is_true( 'XMLRPC_REQUEST' ) &&
61
			! is_wp_error( $verified_user )
62
			&& $verified_user
63
		) {
64
			$old_user = wp_get_current_user();
65
			$this->old_user = isset( $old_user->ID ) ? $old_user->ID : 0;
66
			wp_set_current_user( $verified_user['user_id'] );
67
		}
68
	}
69
70
	public function maybe_clear_user_from_token() {
71
		if ( isset( $this->old_user ) ) {
72
			wp_set_current_user( $this->old_user );
73
		}
74
	}
75
76
	public function get_next_sync_time( $queue_name ) {
77
		return (double) get_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, 0 );
78
	}
79
80
	public function set_next_sync_time( $time, $queue_name ) {
81
		return update_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, $time, true );
82
	}
83
84
	public function do_full_sync() {
85
		if ( ! Jetpack_Sync_Modules::get_module( 'full-sync' ) ) {
86
			return;
87
		}
88
		$this->continue_full_sync_enqueue();
89
		return $this->do_sync_and_set_delays( $this->full_sync_queue );
90
	}
91
92
	private function continue_full_sync_enqueue() {
93
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
94
			return false;
95
		}
96
97
		if ( $this->get_next_sync_time( 'full-sync-enqueue' ) > microtime( true ) ) {
98
			return false;
99
		}
100
101
		Jetpack_Sync_Modules::get_module( 'full-sync' )->continue_enqueuing();
102
103
		$this->set_next_sync_time( time() + $this->get_enqueue_wait_time(), 'full-sync-enqueue' );
104
	}
105
106
	public function handle_packages() {
107
		$this->packager->send_items_to_queue();
108
	}
109
110
	public function do_sync() {
111
		$this->handle_packages();
112
		return $this->do_sync_and_set_delays( $this->sync_queue );
113
	}
114
115
	public function do_sync_and_set_delays( $queue ) {
116
		// don't sync if importing
117
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
118
			return new WP_Error( 'is_importing' );
119
		}
120
121
		// don't sync if we are throttled
122
		if ( $this->get_next_sync_time( $queue->id ) > microtime( true ) ) {
123
			return new WP_Error( 'sync_throttled' );
124
		}
125
126
		$start_time = microtime( true );
127
128
		Jetpack_Sync_Settings::set_is_syncing( true );
129
130
		$sync_result = $this->do_sync_for_queue( $queue );
131
132
		Jetpack_Sync_Settings::set_is_syncing( false );
133
134
		$exceeded_sync_wait_threshold = ( microtime( true ) - $start_time ) > (double) $this->get_sync_wait_threshold();
135
136
		if ( is_wp_error( $sync_result ) ) {
137
			if ( 'unclosed_buffer' === $sync_result->get_error_code() ) {
138
				$this->set_next_sync_time( time() + self::QUEUE_LOCKED_SYNC_DELAY, $queue->id );
139
			}
140
			if ( 'wpcom_error' === $sync_result->get_error_code() ) {
141
				$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY, $queue->id );
142
			}
143
		} elseif ( $exceeded_sync_wait_threshold ) {
144
			// if we actually sent data and it took a while, wait before sending again
145
			$this->set_next_sync_time( time() + $this->get_sync_wait_time(), $queue->id );
146
		}
147
148
		return $sync_result;
149
	}
150
151
	public function get_items_to_send( $buffer, $encode = true ) {
152
		// track how long we've been processing so we can avoid request timeouts
153
		$start_time = microtime( true );
154
		$upload_size   = 0;
155
		$items_to_send = array();
156
		$items         = $buffer->get_items();
157
		// set up current screen to avoid errors rendering content
158
		require_once( ABSPATH . 'wp-admin/includes/class-wp-screen.php' );
159
		require_once( ABSPATH . 'wp-admin/includes/screen.php' );
160
		set_current_screen( 'sync' );
161
		$skipped_items_ids = array();
162
		// we estimate the total encoded size as we go by encoding each item individually
163
		// this is expensive, but the only way to really know :/
164
		foreach ( $items as $key => $item ) {
165
			// Suspending cache addition help prevent overloading in memory cache of large sites.
166
			wp_suspend_cache_addition( true );
167
			/**
168
			 * Modify the data within an action before it is serialized and sent to the server
169
			 * For example, during full sync this expands Post ID's into full Post objects,
170
			 * so that we don't have to serialize the whole object into the queue.
171
			 *
172
			 * @since 4.2.0
173
			 *
174
			 * @param array The action parameters
175
			 * @param int The ID of the user who triggered the action
176
			 */
177
			$item[1] = apply_filters( 'jetpack_sync_before_send_' . $item[0], $item[1], $item[2] );
178
			wp_suspend_cache_addition( false );
179
			if ( $item[1] === false ) {
180
				$skipped_items_ids[] = $key;
181
				continue;
182
			}
183
			$encoded_item = $encode ? $this->codec->encode( $item ) : $item;
184
			$upload_size += strlen( $encoded_item );
185
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
186
				break;
187
			}
188
			$items_to_send[ $key ] = $encoded_item;
189
			if ( microtime(true) - $start_time > $this->max_dequeue_time ) {
190
				break;
191
			}
192
		}
193
194
		return array( $items_to_send, $skipped_items_ids, $items, microtime( true ) - $start_time );
195
	}
196
197
	public function do_sync_for_queue( $queue ) {
198
199
		do_action( 'jetpack_sync_before_send_queue_' . $queue->id );
200
		if ( $queue->size() === 0 ) {
201
			return new WP_Error( 'empty_queue_' . $queue->id );
202
		}
203
		// now that we're sure we are about to sync, try to
204
		// ignore user abort so we can avoid getting into a
205
		// bad state
206
		if ( function_exists( 'ignore_user_abort' ) ) {
207
			ignore_user_abort( true );
208
		}
209
210
		$checkout_start_time = microtime( true );
211
212
		$buffer = $queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
213
214
		if ( ! $buffer ) {
215
			// buffer has no items
216
			return new WP_Error( 'empty_buffer' );
217
		}
218
219
		if ( is_wp_error( $buffer ) ) {
220
			return $buffer;
221
		}
222
223
		$checkout_duration = microtime( true ) - $checkout_start_time;
224
225
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $buffer, true );
226
227
		/**
228
		 * Fires when data is ready to send to the server.
229
		 * Return false or WP_Error to abort the sync (e.g. if there's an error)
230
		 * The items will be automatically re-sent later
231
		 *
232
		 * @since 4.2.0
233
		 *
234
		 * @param array $data The action buffer
235
		 * @param string $codec The codec name used to encode the data
236
		 * @param double $time The current time
237
		 * @param string $queue The queue used to send ('sync' or 'full_sync')
238
		 */
239
		Jetpack_Sync_Settings::set_is_sending( true );
240
		$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->codec->name(), microtime( true ), $queue->id, $checkout_duration, $preprocess_duration );
241
		Jetpack_Sync_Settings::set_is_sending( false );
242
243
		if ( ! $processed_item_ids || is_wp_error( $processed_item_ids ) ) {
244
			$checked_in_item_ids = $queue->checkin( $buffer );
245
			if ( is_wp_error( $checked_in_item_ids ) ) {
246
				error_log( 'Error checking in buffer: ' . $checked_in_item_ids->get_error_message() );
247
				$queue->force_checkin();
248
			}
249
			if ( is_wp_error( $processed_item_ids ) ) {
250
				return new WP_Error( 'wpcom_error', $processed_item_ids->get_error_code() );
251
			}
252
			// returning a WP_Error('wpcom_error') is a sign to the caller that we should wait a while
253
			// before syncing again
254
			return new WP_Error( 'wpcom_error', 'jetpack_sync_send_data_false' );
255
		} else {
256
			// detect if the last item ID was an error
257
			$had_wp_error = is_wp_error( end( $processed_item_ids ) );
258
			if ( $had_wp_error ) {
259
				$wp_error = array_pop( $processed_item_ids );
260
			}
261
			// also checkin any items that were skipped
262
			if ( count( $skipped_items_ids ) > 0 ) {
263
				$processed_item_ids = array_merge( $processed_item_ids, $skipped_items_ids );
264
			}
265
			$processed_items = array_intersect_key( $items, array_flip( $processed_item_ids ) );
266
			/**
267
			 * Allows us to keep track of all the actions that have been sent.
268
			 * Allows us to calculate the progress of specific actions.
269
			 *
270
			 * @since 4.2.0
271
			 *
272
			 * @param array $processed_actions The actions that we send successfully.
273
			 */
274
			do_action( 'jetpack_sync_processed_actions', $processed_items );
275
			$queue->close( $buffer, $processed_item_ids );
276
			// returning a WP_Error is a sign to the caller that we should wait a while
277
			// before syncing again
278
			if ( $had_wp_error ) {
279
				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...
280
			}
281
		}
282
		return true;
283
	}
284
285
	function get_sync_queue() {
286
		return $this->sync_queue;
287
	}
288
289
	function get_full_sync_queue() {
290
		return $this->full_sync_queue;
291
	}
292
293
	function get_codec() {
294
		return $this->codec;
295
	}
296
297
	function send_checksum() {
298
		require_once 'class.jetpack-sync-wp-replicastore.php';
299
		$store = new Jetpack_Sync_WP_Replicastore();
300
		do_action( 'jetpack_sync_checksum', $store->checksum_all() );
301
	}
302
303
	function reset_sync_queue() {
304
		$this->sync_queue->reset();
305
	}
306
307
	function reset_full_sync_queue() {
308
		$this->full_sync_queue->reset();
309
	}
310
311
	function set_dequeue_max_bytes( $size ) {
312
		$this->dequeue_max_bytes = $size;
313
	}
314
315
	// in bytes
316
	function set_upload_max_bytes( $max_bytes ) {
317
		$this->upload_max_bytes = $max_bytes;
318
	}
319
320
	// in rows
321
	function set_upload_max_rows( $max_rows ) {
322
		$this->upload_max_rows = $max_rows;
323
	}
324
325
	// in seconds
326
	function set_sync_wait_time( $seconds ) {
327
		$this->sync_wait_time = $seconds;
328
	}
329
330
	function get_sync_wait_time() {
331
		return $this->sync_wait_time;
332
	}
333
334
	function set_enqueue_wait_time( $seconds ) {
335
		$this->enqueue_wait_time = $seconds;
336
	}
337
338
	function get_enqueue_wait_time() {
339
		return $this->enqueue_wait_time;
340
	}
341
342
	// in seconds
343
	function set_sync_wait_threshold( $seconds ) {
344
		$this->sync_wait_threshold = $seconds;
345
	}
346
347
	function get_sync_wait_threshold() {
348
		return $this->sync_wait_threshold;
349
	}
350
351
	// in seconds
352
	function set_max_dequeue_time( $seconds ) {
353
		$this->max_dequeue_time = $seconds;
354
	}
355
356
	function set_defaults() {
357
		$this->sync_queue      = new Jetpack_Sync_Queue( 'sync' );
358
		$this->full_sync_queue = new Jetpack_Sync_Queue( 'full_sync' );
359
		$this->codec           = new Jetpack_Sync_JSON_Deflate_Array_Codec();
360
361
		// saved settings
362
		Jetpack_Sync_Settings::set_importing( null );
363
		$settings = Jetpack_Sync_Settings::get_settings();
364
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
365
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
366
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
367
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
368
		$this->set_enqueue_wait_time( $settings['enqueue_wait_time'] );
369
		$this->set_sync_wait_threshold( $settings['sync_wait_threshold'] );
370
		$this->set_max_dequeue_time( Jetpack_Sync_Defaults::get_max_sync_execution_time() );
371
		$this->packager = Jetpack_Sync_Packager::get_instance();
372
	}
373
374
	function reset_data() {
375
		$this->reset_sync_queue();
376
		$this->reset_full_sync_queue();
377
378
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
379
			$module->reset_data();
380
		}
381
382
		foreach ( array( 'sync', 'full_sync', 'full-sync-enqueue' ) as $queue_name ) {
383
			delete_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name );
384
		}
385
386
		Jetpack_Sync_Settings::reset_data();
387
	}
388
389
	function uninstall() {
390
		// Lets delete all the other fun stuff like transient and option and the sync queue
391
		$this->reset_data();
392
393
		// delete the full sync status
394
		delete_option( 'jetpack_full_sync_status' );
395
396
		// clear the sync cron.
397
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
398
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
399
	}
400
}
401