Completed
Push — fix/dont-delay-sync-if-no-item... ( d1da56 )
by
unknown
162:13 queued 146:26
created

Jetpack_Sync_Sender::do_sync()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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