Completed
Push — fix/plugins-callables ( 2c7db1 )
by
unknown
17:10 queued 07:59
created

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