Completed
Push — fix/non-admin-no-ui-when-prote... ( 85feb2 )
by
unknown
11:34
created

Jetpack_Sync_Module_Full_Sync::get_config()   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
/**
4
 * This class does a full resync of the database by
5
 * enqueuing an outbound action for every single object
6
 * that we care about.
7
 *
8
 * This class, and its related class Jetpack_Sync_Module, contain a few non-obvious optimisations that should be explained:
9
 * - we fire an action called jetpack_full_sync_start so that WPCOM can erase the contents of the cached database
10
 * - for each object type, we page through the object IDs and enqueue them by firing some monitored actions
11
 * - we load the full objects for those IDs in chunks of Jetpack_Sync_Module::ARRAY_CHUNK_SIZE (to reduce the number of MySQL calls)
12
 * - we fire a trigger for the entire array which the Jetpack_Sync_Listener then serializes and queues.
13
 */
14
15
class Jetpack_Sync_Module_Full_Sync extends Jetpack_Sync_Module {
16
	const STATUS_OPTION_PREFIX = 'jetpack_sync_full_';
17
	const FULL_SYNC_TIMEOUT = 3600;
18
19
	public function name() {
20
		return 'full-sync';
21
	}
22
23
	function init_full_sync_listeners( $callable ) {
24
		// synthetic actions for full sync
25
		add_action( 'jetpack_full_sync_start', $callable );
26
		add_action( 'jetpack_full_sync_end', $callable );
27
		add_action( 'jetpack_full_sync_cancelled', $callable );
28
	}
29
30
	function init_before_send() {
31
		// this is triggered after actions have been processed on the server
32
		add_action( 'jetpack_sync_processed_actions', array( $this, 'update_sent_progress_action' ) );
33
	}
34
35
	function start( $module_configs = null ) {
36
		$was_already_running = $this->is_started() && ! $this->is_finished();
37
38
		// remove all evidence of previous full sync items and status
39
		$this->reset_data();
40
41
		if ( $was_already_running ) {
42
			/**
43
			 * Fires when a full sync is cancelled.
44
			 *
45
			 * @since 4.2.0
46
			 */
47
			do_action( 'jetpack_full_sync_cancelled' );
48
		}
49
50
		$this->update_status_option( 'started', time() );
51
		$this->update_status_option( 'params', $module_configs );
52
53
		$enqueue_status = array();
54
		$full_sync_config = array();
55
56
		// default value is full sync
57
		if ( ! is_array( $module_configs ) ) {
58
			$module_configs = array();
59
			foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
60
				$module_configs[ $module->name() ] = true;
61
			}
62
		}
63
64
		// set default configuration, calculate totals, and save configuration if totals > 0
65
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
66
			$module_name = $module->name();
67
			$module_config = isset( $module_configs[ $module_name ] ) ? $module_configs[ $module_name ] : false;
68
			
69
			if ( ! $module_config ) {
70
				continue;
71
			}
72
73
			if ( 'users' === $module_name && 'initial' === $module_config ) {
74
				$module_config = $module->get_initial_sync_user_config();
75
			}
76
77
			$enqueue_status[ $module_name ] = false;
78
79
			$total_items = $module->estimate_full_sync_actions( $module_config );
80
81
			// if there's information to process, configure this module
82
			if ( ! is_null( $total_items ) && $total_items > 0 ) {
83
				$full_sync_config[ $module_name ] = $module_config;
84
				$enqueue_status[ $module_name ] = array(
85
					$total_items,   // total
86
					0,              // queued
87
					false,          // current state
88
				);
89
			}
90
		}
91
92
		$this->set_config( $full_sync_config );
93
		$this->set_enqueue_status( $enqueue_status );
94
95
		/**
96
		 * Fires when a full sync begins. This action is serialized
97
		 * and sent to the server so that it knows a full sync is coming.
98
		 *
99
		 * @since 4.2.0
100
		 */
101
		do_action( 'jetpack_full_sync_start', $full_sync_config );
102
103
		$this->continue_enqueuing( $full_sync_config, $enqueue_status );
104
105
		return true;
106
	}
107
108
	function continue_enqueuing( $configs = null, $enqueue_status = null ) {
109
		if ( ! $this->is_started() || $this->get_status_option( 'queue_finished' ) ) {
110
			return;
111
		}
112
113
		// if full sync queue is full, don't enqueue more items
114
		$max_queue_size_full_sync = Jetpack_Sync_Settings::get_setting( 'max_queue_size_full_sync' );
115
		$full_sync_queue = new Jetpack_Sync_Queue( 'full_sync' );
116
		
117
		$available_queue_slots = $max_queue_size_full_sync - $full_sync_queue->size();
118
119
		if ( $available_queue_slots <= 0 ) {
120
			return;
121
		} else {
122
			$remaining_items_to_enqueue = min( Jetpack_Sync_Settings::get_setting( 'max_enqueue_full_sync' ), $available_queue_slots );
123
		}
124
125
		if ( ! $configs ) {
126
			$configs = $this->get_config();
127
		}
128
129
		if ( ! $enqueue_status ) {
130
			$enqueue_status = $this->get_enqueue_status();
131
		}
132
133
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
134
			$module_name = $module->name();
135
136
			// skip module if not configured for this sync or module is done
137
			if ( ! isset( $configs[ $module_name ] ) 
138
				|| // no module config
139
					! $configs[ $module_name ] 
140
				|| // no enqueue status
141
					! $enqueue_status[ $module_name ] 
142
				|| // finished enqueuing this module
143
					true === $enqueue_status[ $module_name ][ 2 ] ) {
144
				continue;
145
			}
146
147
			list( $items_enqueued, $next_enqueue_state ) = $module->enqueue_full_sync_actions( $configs[ $module_name ], $remaining_items_to_enqueue, $enqueue_status[ $module_name ][ 2 ] );
148
149
			$enqueue_status[ $module_name ][ 2 ] = $next_enqueue_state;
150
151
			// if items were processed, subtract them from the limit
152
			if ( ! is_null( $items_enqueued ) && $items_enqueued > 0 ) {
153
				$enqueue_status[ $module_name ][ 1 ] += $items_enqueued;
154
				$remaining_items_to_enqueue -= $items_enqueued;
155
			}
156
157
			// stop processing if we've reached our limit of items to enqueue
158
			if ( 0 >= $remaining_items_to_enqueue ) {
159
				$this->set_enqueue_status( $enqueue_status );
160
				return;
161
			}
162
		}
163
		
164
		$this->set_enqueue_status( $enqueue_status );
165
166
		// setting autoload to true means that it's faster to check whether we should continue enqueuing
167
		$this->update_status_option( 'queue_finished', time(), true );
168
169
		/**
170
		 * Fires when a full sync ends. This action is serialized
171
		 * and sent to the server with checksums so that we can confirm the
172
		 * sync was successful.
173
		 *
174
		 * @since 4.2.0
175
		 */
176
		do_action( 'jetpack_full_sync_end', '' );
177
	}
178
179
	function update_sent_progress_action( $actions ) {
180
181
		// quick way to map to first items with an array of arrays
182
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
183
184
		if ( ! $this->is_started() || $this->is_finished() ) {
185
			return;
186
		}
187
188
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
189
			$this->update_status_option( 'send_started', time() );
190
		}
191
192
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
193
			$module_actions     = $module->get_full_sync_actions();
194
			$status_option_name = "{$module->name()}_sent";
195
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
196
197
			foreach ( $module_actions as $module_action ) {
198
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
199
					$items_sent += $actions_with_counts[ $module_action ];
200
				}
201
			}
202
203
			if ( $items_sent > 0 ) {
204
				$this->update_status_option( $status_option_name, $items_sent );
205
			}	
206
		}
207
208
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
209
			$this->update_status_option( 'finished', time() );
210
		}
211
	}
212
213
	public function get_action_name( $queue_item ) {
214
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
215
			return $queue_item[0];
216
		}
217
		return false;
218
	}
219
220
	public function is_started() {
221
		return !! $this->get_status_option( 'started' );
222
	}
223
224
	public function is_finished() {
225
		return !! $this->get_status_option( 'finished' );
226
	}
227
228
	public function get_status() {
229
		$status = array(
230
			'started'        => $this->get_status_option( 'started' ),
231
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
232
			'send_started'   => $this->get_status_option( 'send_started' ),
233
			'finished'       => $this->get_status_option( 'finished' ),
234
			'sent'           => array(),
235
			'queue'          => array(),
236
			'config'         => $this->get_status_option( 'params' ),
237
			'total'          => array(),
238
		);
239
240
		$enqueue_status = $this->get_enqueue_status();
241
		$module_config = $this->get_config();
0 ignored issues
show
Unused Code introduced by
$module_config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
242
243
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
244
			$name = $module->name();
245
246
			if ( ! isset( $enqueue_status[ $name ] ) ) {
247
				continue;
248
			}
249
250
			list( $total, $queued, $state ) = $enqueue_status[ $name ];
0 ignored issues
show
Unused Code introduced by
The assignment to $state is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
251
252
			if ( $total ) {
253
				$status[ 'total' ][ $name ] = $total;
254
			}
255
256
			if ( $queued ) {
257
				$status[ 'queue' ][ $name ] = $queued;
258
			}
259
			
260
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
261
				$status[ 'sent' ][ $name ] = $sent;
262
			}
263
		}
264
265
		return $status;
266
	}
267
268
	public function clear_status() {
269
		$prefix = self::STATUS_OPTION_PREFIX;
270
		delete_option( "{$prefix}_started" );
271
		delete_option( "{$prefix}_params" );
272
		delete_option( "{$prefix}_queue_finished" );
273
		delete_option( "{$prefix}_send_started" );
274
		delete_option( "{$prefix}_finished" );
275
276
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
277
			delete_option( "{$prefix}_{$module->name()}_sent" );
278
		}
279
	}
280
281
	public function reset_data() {
282
		$this->clear_status();
283
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
284
		$listener = Jetpack_Sync_Listener::get_instance();
285
		$listener->get_full_sync_queue()->reset();
286
	}
287
288
	private function get_status_option( $name, $default = null ) {
289
		$prefix = self::STATUS_OPTION_PREFIX;
290
291
		$value = get_option( "{$prefix}_{$name}", $default );
292
		
293
		if ( ! $value ) {
294
			// don't cast to int if we didn't find a value - we want to preserve null or false as sentinals
295
			return $default;
296
		}
297
298
		return is_numeric( $value ) ? intval( $value ) : $value;
299
	}
300
301
	private function update_status_option( $name, $value, $autoload = false ) {
302
		$prefix = self::STATUS_OPTION_PREFIX;
303
		update_option( "{$prefix}_{$name}", $value, $autoload );
304
	}
305
306
	private function set_enqueue_status( $new_status ) {
307
		$this->write_option( 'jetpack_sync_full_enqueue_status', $new_status );
308
	}
309
310
	private function get_enqueue_status() {
311
		return $this->read_option( 'jetpack_sync_full_enqueue_status' );
312
	}
313
314
	private function set_config( $config ) {
315
		$this->write_option( 'jetpack_sync_full_config', $config );
316
	}
317
	
318
	private function get_config() {
319
		return $this->read_option( 'jetpack_sync_full_config' );
320
	}
321
322
	private function write_option( $name, $value ) {
323
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
324
		global $wpdb;
325
		$serialized_value = maybe_serialize( $value );
326
		// try updating, if no update then insert
327
		// TODO: try to deal with the fact that unchanged values can return updated_num = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
328
		// below we used "insert ignore" to at least suppress the resulting error
329
		$updated_num = $wpdb->query(
330
			$wpdb->prepare(
331
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", 
332
				$serialized_value,
333
				$name
334
			)
335
		);
336
337
		if ( ! $updated_num ) {
338
			$updated_num = $wpdb->query(
339
				$wpdb->prepare(
340
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", 
341
					$name,
342
					$serialized_value
343
				)
344
			);
345
		}
346
		return $updated_num;
347
	}
348
349
	private function read_option( $name, $default = null ) {
350
		global $wpdb;
351
		$value = $wpdb->get_var( 
352
			$wpdb->prepare(
353
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", 
354
				$name
355
			)
356
		);
357
		$value = maybe_unserialize( $value );
358
359
		if ( $value === null && $default !== null ) {
360
			return $default;
361
		}
362
363
		return $value;
364
	}
365
}
366