Completed
Push — try/sync-package ( 228b13 )
by Marin
07:37
created

Sender::set_defaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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