Completed
Push — update/sync-small-queue-action... ( 3a4b3f )
by
unknown
10:16
created

Jetpack_Sync_Sender::get_instance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 9.4285
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-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 SYNC_THROTTLE_OPTION_NAME = 'jetpack_sync_min_wait';
15
	const NEXT_SYNC_TIME_OPTION_NAME = 'jetpack_next_sync_time';
16
	const WPCOM_ERROR_SYNC_DELAY = 60;
17
18
	private $dequeue_max_bytes;
19
	private $upload_max_bytes;
20
	private $upload_max_rows;
21
	private $sync_wait_time;
22
	private $sync_queue;
23
	private $full_sync_queue;
24
	private $codec;
25
26
	// singleton functions
27
	private static $instance;
28
29
	public static function get_instance() {
30
		if ( null === self::$instance ) {
31
			self::$instance = new self();
32
		}
33
34
		return self::$instance;
35
	}
36
37
	// this is necessary because you can't use "new" when you declare instance properties >:(
38
	protected function __construct() {
39
		$this->set_defaults();
40
		$this->init();
41
	}
42
43
	private function init() {
44
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
45
			$module->init_before_send();
46
		}
47
	}
48
49
	public function get_next_sync_time() {
50
		return (double) get_option( self::NEXT_SYNC_TIME_OPTION_NAME, 0 );
51
	}
52
53
	public function set_next_sync_time( $time ) {
54
		return update_option( self::NEXT_SYNC_TIME_OPTION_NAME, $time, true );
55
	}
56
57
	public function do_sync() {
58
		// don't sync if importing
59
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
60
			return false;
61
		}
62
63
		// don't sync if we are throttled
64
		if ( $this->get_next_sync_time() > microtime( true ) ) {
65
			// even though we shouldn't be syncing untill next time if the queue is really small
66
			// lets try any way.
67
			if ( $this->sync_queue->size() < 12 ) {
68
				$sync_result  = $this->do_sync_for_queue( $this->sync_queue );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
69
				if ( is_wp_error( $sync_result ) ) {
70
					$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY );
71
				}
72
			}
73
			return false;
74
		}
75
		
76
		$full_sync_result = $this->do_sync_for_queue( $this->full_sync_queue );
77
		$sync_result      = $this->do_sync_for_queue( $this->sync_queue );
78
79
		if ( is_wp_error( $full_sync_result ) || is_wp_error( $sync_result ) ) {
80
			$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY );
81
			$full_sync_result = false;
82
			$sync_result      = false;
83
		} else {
84
			$this->set_next_sync_time( time() + $this->get_sync_wait_time() );
85
		}
86
87
		// we use OR here because if either one returns true then the caller should
88
		// be allowed to call do_sync again, as there may be more items
89
		return $full_sync_result || $sync_result;
90
	}
91
92
	public function do_sync_for_queue( $queue ) {
93
94
		do_action( 'jetpack_sync_before_send_queue_' . $queue->id );
95
96
		if ( $queue->size() === 0 ) {
97
			return false;
98
		}
99
100
		// now that we're sure we are about to sync, try to
101
		// ignore user abort so we can avoid getting into a
102
		// bad state
103
		if ( function_exists( 'ignore_user_abort' ) ) {
104
			ignore_user_abort( true );
105
		}
106
107
		$buffer = $queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
108
109
		if ( ! $buffer ) {
110
			// buffer has no items
111
			return false;
112
		}
113
114
		if ( is_wp_error( $buffer ) ) {
115
			// another buffer is currently sending
116
			return false;
117
		}
118
119
		$upload_size   = 0;
120
		$items_to_send = array();
121
		$items         = $buffer->get_items();
122
123
		// set up current screen to avoid errors rendering content
124
		require_once(ABSPATH . 'wp-admin/includes/class-wp-screen.php');
125
		require_once(ABSPATH . 'wp-admin/includes/screen.php');
126
		set_current_screen( 'sync' );
127
128
		// we estimate the total encoded size as we go by encoding each item individually
129
		// this is expensive, but the only way to really know :/
130
		foreach ( $items as $key => $item ) {
131
			/**
132
			 * Modify the data within an action before it is serialized and sent to the server
133
			 * For example, during full sync this expands Post ID's into full Post objects,
134
			 * so that we don't have to serialize the whole object into the queue.
135
			 *
136
			 * @since 4.2.0
137
			 *
138
			 * @param array The action parameters
139
			 */
140
			$item[1] = apply_filters( 'jetpack_sync_before_send_' . $item[0], $item[1], $item[2] );
141
142
			$encoded_item = $this->codec->encode( $item );
143
144
			$upload_size += strlen( $encoded_item );
145
146
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
147
				break;
148
			}
149
150
			$items_to_send[ $key ] = $encoded_item;
151
		}
152
153
		/**
154
		 * Fires when data is ready to send to the server.
155
		 * Return false or WP_Error to abort the sync (e.g. if there's an error)
156
		 * The items will be automatically re-sent later
157
		 *
158
		 * @since 4.2.0
159
		 *
160
		 * @param array $data The action buffer
161
		 */
162
		$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->codec->name(), microtime( true ) );
163
164
		if ( ! $processed_item_ids || is_wp_error( $processed_item_ids ) ) {
165
			$checked_in_item_ids = $queue->checkin( $buffer );
166
167
			if ( is_wp_error( $checked_in_item_ids ) ) {
168
				error_log( 'Error checking in buffer: ' . $checked_in_item_ids->get_error_message() );
169
				$queue->force_checkin();
170
			}
171
172
			// returning a WP_Error is a sign to the caller that we should wait a while
173
			// before syncing again
174
			return new WP_Error( 'server_error' );
175
			
176
		} else {
177
178
			// detect if the last item ID was an error
179
			$had_wp_error = is_wp_error( end( $processed_item_ids ) );
180
181
			if ( $had_wp_error ) {
182
				$wp_error = array_pop( $processed_item_ids );
183
			}
184
185
			$processed_items = array_intersect_key( $items, array_flip( $processed_item_ids ) );
186
187
			/**
188
			 * Allows us to keep track of all the actions that have been sent.
189
			 * Allows us to calculate the progress of specific actions.
190
			 *
191
			 * @since 4.2.0
192
			 *
193
			 * @param array $processed_actions The actions that we send successfully.
194
			 */
195
			do_action( 'jetpack_sync_processed_actions', $processed_items );
196
197
			$queue->close( $buffer, $processed_item_ids );
198
199
			// returning a WP_Error is a sign to the caller that we should wait a while
200
			// before syncing again
201
			if ( $had_wp_error ) {
202
				return $wp_error;
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...
203
			} 
204
		}
205
		
206
		return true;
207
	}
208
209
	function get_sync_queue() {
210
		return $this->sync_queue;
211
	}
212
213
	function get_full_sync_queue() {
214
		return $this->full_sync_queue;
215
	}
216
217
	function get_codec() {
218
		return $this->codec;
219
	}
220
221
	function send_checksum() {
222
		require_once 'class.jetpack-sync-wp-replicastore.php';
223
		$store = new Jetpack_Sync_WP_Replicastore();
224
		do_action( 'jetpack_sync_checksum', $store->checksum_all() );
225
	}
226
227
	function reset_sync_queue() {
228
		Jetpack_Sync_Modules::get_module( 'full-sync' )->clear_status();
229
		$this->sync_queue->reset();
230
		$this->full_sync_queue->reset();
231
	}
232
233
	function set_dequeue_max_bytes( $size ) {
234
		$this->dequeue_max_bytes = $size;
235
	}
236
237
	// in bytes
238
	function set_upload_max_bytes( $max_bytes ) {
239
		$this->upload_max_bytes = $max_bytes;
240
	}
241
242
	// in rows
243
	function set_upload_max_rows( $max_rows ) {
244
		$this->upload_max_rows = $max_rows;
245
	}
246
247
	// in seconds
248
	function set_sync_wait_time( $seconds ) {
249
		$this->sync_wait_time = $seconds;
250
	}
251
252
	function get_sync_wait_time() {
253
		return $this->sync_wait_time;
254
	}
255
256
	function set_defaults() {
257
		$this->sync_queue = new Jetpack_Sync_Queue( 'sync' );
258
		$this->full_sync_queue = new Jetpack_Sync_Queue( 'full_sync' );
259
		$this->codec      = new Jetpack_Sync_JSON_Deflate_Codec();
260
261
		// saved settings
262
		$settings = Jetpack_Sync_Settings::get_settings();
263
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
264
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
265
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
266
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
267
	}
268
269
	function reset_data() {
270
		$this->reset_sync_queue();
271
272
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
273
			$module->reset_data();
274
		}
275
276
		delete_option( self::SYNC_THROTTLE_OPTION_NAME );
277
		delete_option( self::NEXT_SYNC_TIME_OPTION_NAME );
278
279
		Jetpack_Sync_Settings::reset_data();
280
	}
281
282
	function uninstall() {
283
		// Lets delete all the other fun stuff like transient and option and the sync queue
284
		$this->reset_data();
285
286
		// delete the full sync status
287
		delete_option( 'jetpack_full_sync_status' );
288
289
		// clear the sync cron.
290
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
291
292
		// clear the checksum cron
293
		wp_clear_scheduled_hook( 'jetpack_send_db_checksum' );
294
	}
295
}
296