Completed
Push — master-stable ( 2e1c2b...fd6891 )
by
unknown
07:39
created

Jetpack_Sync_Module_Full_Sync::read_option()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 2
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
require_once dirname( __FILE__ ) . '/class.jetpack-sync-options.php';
4
5
/**
6
 * This class does a full resync of the database by
7
 * enqueuing an outbound action for every single object
8
 * that we care about.
9
 *
10
 * This class, and its related class Jetpack_Sync_Module, contain a few non-obvious optimisations that should be explained:
11
 * - we fire an action called jetpack_full_sync_start so that WPCOM can erase the contents of the cached database
12
 * - for each object type, we page through the object IDs and enqueue them by firing some monitored actions
13
 * - we load the full objects for those IDs in chunks of Jetpack_Sync_Module::ARRAY_CHUNK_SIZE (to reduce the number of MySQL calls)
14
 * - we fire a trigger for the entire array which the Jetpack_Sync_Listener then serializes and queues.
15
 */
16
17
class Jetpack_Sync_Module_Full_Sync extends Jetpack_Sync_Module {
18
	const STATUS_OPTION_PREFIX = 'jetpack_sync_full_';
19
	const FULL_SYNC_TIMEOUT = 3600;
20
21
	public function name() {
22
		return 'full-sync';
23
	}
24
25
	function init_full_sync_listeners( $callable ) {
26
		// synthetic actions for full sync
27
		add_action( 'jetpack_full_sync_start', $callable );
28
		add_action( 'jetpack_full_sync_end', $callable );
29
		add_action( 'jetpack_full_sync_cancelled', $callable );
30
	}
31
32
	function init_before_send() {
33
		// this is triggered after actions have been processed on the server
34
		add_action( 'jetpack_sync_processed_actions', array( $this, 'update_sent_progress_action' ) );
35
	}
36
37
	function start( $module_configs = null ) {
38
		$was_already_running = $this->is_started() && ! $this->is_finished();
39
40
		// remove all evidence of previous full sync items and status
41
		$this->reset_data();
42
43
		if ( $was_already_running ) {
44
			/**
45
			 * Fires when a full sync is cancelled.
46
			 *
47
			 * @since 4.2.0
48
			 */
49
			do_action( 'jetpack_full_sync_cancelled' );
50
		}
51
52
		$this->update_status_option( 'started', time() );
53
		$this->update_status_option( 'params', $module_configs );
54
55
		$enqueue_status = array();
56
		$full_sync_config = array();
57
58
		// default value is full sync
59
		if ( ! is_array( $module_configs ) ) {
60
			$module_configs = array();
61
			foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
62
				$module_configs[ $module->name() ] = true;
63
			}
64
		}
65
66
		// set default configuration, calculate totals, and save configuration if totals > 0
67
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
68
			$module_name = $module->name();
69
			$module_config = isset( $module_configs[ $module_name ] ) ? $module_configs[ $module_name ] : false;
70
			
71
			if ( ! $module_config ) {
72
				continue;
73
			}
74
75
			if ( 'users' === $module_name && 'initial' === $module_config ) {
76
				$module_config = $module->get_initial_sync_user_config();
77
			}
78
79
			$enqueue_status[ $module_name ] = false;
80
81
			$total_items = $module->estimate_full_sync_actions( $module_config );
82
83
			// if there's information to process, configure this module
84
			if ( ! is_null( $total_items ) && $total_items > 0 ) {
85
				$full_sync_config[ $module_name ] = $module_config;
86
				$enqueue_status[ $module_name ] = array(
87
					$total_items,   // total
88
					0,              // queued
89
					false,          // current state
90
				);
91
			}
92
		}
93
94
		$this->set_config( $full_sync_config );
95
		$this->set_enqueue_status( $enqueue_status );
96
97
		/**
98
		 * Fires when a full sync begins. This action is serialized
99
		 * and sent to the server so that it knows a full sync is coming.
100
		 *
101
		 * @since 4.2.0
102
		 */
103
		do_action( 'jetpack_full_sync_start', $full_sync_config );
104
105
		$this->continue_enqueuing( $full_sync_config, $enqueue_status );
106
107
		return true;
108
	}
109
110
	function continue_enqueuing( $configs = null, $enqueue_status = null ) {
111
		if ( ! $this->is_started() || $this->get_status_option( 'queue_finished' ) ) {
112
			return;
113
		}
114
115
		// if full sync queue is full, don't enqueue more items
116
		$max_queue_size_full_sync = Jetpack_Sync_Settings::get_setting( 'max_queue_size_full_sync' );
117
		$full_sync_queue = new Jetpack_Sync_Queue( 'full_sync' );
118
		
119
		$available_queue_slots = $max_queue_size_full_sync - $full_sync_queue->size();
120
121
		if ( $available_queue_slots <= 0 ) {
122
			return;
123
		} else {
124
			$remaining_items_to_enqueue = min( Jetpack_Sync_Settings::get_setting( 'max_enqueue_full_sync' ), $available_queue_slots );
125
		}
126
127
		if ( ! $configs ) {
128
			$configs = $this->get_config();
129
		}
130
131
		if ( ! $enqueue_status ) {
132
			$enqueue_status = $this->get_enqueue_status();
133
		}
134
135
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
136
			$module_name = $module->name();
137
138
			// skip module if not configured for this sync or module is done
139
			if ( ! isset( $configs[ $module_name ] ) 
140
				|| // no module config
141
					! $configs[ $module_name ] 
142
				|| // no enqueue status
143
					! $enqueue_status[ $module_name ] 
144
				|| // finished enqueuing this module
145
					true === $enqueue_status[ $module_name ][ 2 ] ) {
146
				continue;
147
			}
148
149
			list( $items_enqueued, $next_enqueue_state ) = $module->enqueue_full_sync_actions( $configs[ $module_name ], $remaining_items_to_enqueue, $enqueue_status[ $module_name ][ 2 ] );
150
151
			$enqueue_status[ $module_name ][ 2 ] = $next_enqueue_state;
152
153
			// if items were processed, subtract them from the limit
154
			if ( ! is_null( $items_enqueued ) && $items_enqueued > 0 ) {
155
				$enqueue_status[ $module_name ][ 1 ] += $items_enqueued;
156
				$remaining_items_to_enqueue -= $items_enqueued;
157
			}
158
159
			// stop processing if we've reached our limit of items to enqueue
160
			if ( 0 >= $remaining_items_to_enqueue ) {
161
				$this->set_enqueue_status( $enqueue_status );
162
				return;
163
			}
164
		}
165
		
166
		$this->set_enqueue_status( $enqueue_status );
167
168
		// setting autoload to true means that it's faster to check whether we should continue enqueuing
169
		$this->update_status_option( 'queue_finished', time(), true );
170
171
		/**
172
		 * Fires when a full sync ends. This action is serialized
173
		 * and sent to the server.
174
		 *
175
		 * @since 4.2.0
176
		 */
177
		do_action( 'jetpack_full_sync_end', '' );
178
	}
179
180
	function update_sent_progress_action( $actions ) {
181
182
		// quick way to map to first items with an array of arrays
183
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
184
185
		if ( ! $this->is_started() || $this->is_finished() ) {
186
			return;
187
		}
188
189
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
190
			$this->update_status_option( 'send_started', time() );
191
		}
192
193
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
194
			$module_actions     = $module->get_full_sync_actions();
195
			$status_option_name = "{$module->name()}_sent";
196
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
197
198
			foreach ( $module_actions as $module_action ) {
199
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
200
					$items_sent += $actions_with_counts[ $module_action ];
201
				}
202
			}
203
204
			if ( $items_sent > 0 ) {
205
				$this->update_status_option( $status_option_name, $items_sent );
206
			}	
207
		}
208
209
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
210
			$this->update_status_option( 'finished', time() );
211
		}
212
	}
213
214
	public function get_action_name( $queue_item ) {
215
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
216
			return $queue_item[0];
217
		}
218
		return false;
219
	}
220
221
	public function is_started() {
222
		return !! $this->get_status_option( 'started' );
223
	}
224
225
	public function is_finished() {
226
		return !! $this->get_status_option( 'finished' );
227
	}
228
229
	public function get_status() {
230
		$status = array(
231
			'started'        => $this->get_status_option( 'started' ),
232
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
233
			'send_started'   => $this->get_status_option( 'send_started' ),
234
			'finished'       => $this->get_status_option( 'finished' ),
235
			'sent'           => array(),
236
			'queue'          => array(),
237
			'config'         => $this->get_status_option( 'params' ),
238
			'total'          => array(),
239
		);
240
241
		$enqueue_status = $this->get_enqueue_status();
242
		$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...
243
244
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
245
			$name = $module->name();
246
247
			if ( ! isset( $enqueue_status[ $name ] ) ) {
248
				continue;
249
			}
250
251
			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...
252
253
			if ( $total ) {
254
				$status[ 'total' ][ $name ] = $total;
255
			}
256
257
			if ( $queued ) {
258
				$status[ 'queue' ][ $name ] = $queued;
259
			}
260
			
261
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
262
				$status[ 'sent' ][ $name ] = $sent;
263
			}
264
		}
265
266
		return $status;
267
	}
268
269
	public function clear_status() {
270
		$prefix = self::STATUS_OPTION_PREFIX;
271
		Jetpack_Sync_Options::delete_option( "{$prefix}_started" );
272
		Jetpack_Sync_Options::delete_option( "{$prefix}_params" );
273
		Jetpack_Sync_Options::delete_option( "{$prefix}_queue_finished" );
274
		Jetpack_Sync_Options::delete_option( "{$prefix}_send_started" );
275
		Jetpack_Sync_Options::delete_option( "{$prefix}_finished" );
276
277
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
278
			Jetpack_Sync_Options::delete_option( "{$prefix}_{$module->name()}_sent" );
279
		}
280
	}
281
282
	public function reset_data() {
283
		$this->clear_status();
284
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
285
		$listener = Jetpack_Sync_Listener::get_instance();
286
		$listener->get_full_sync_queue()->reset();
287
	}
288
289
	private function get_status_option( $name, $default = null ) {
290
		$value = Jetpack_Sync_Options::get_option( self::STATUS_OPTION_PREFIX . "_$name", $default );
291
292
		return is_numeric( $value ) ? intval( $value ) : $value;
293
	}
294
295
	private function update_status_option( $name, $value, $autoload = false ) {
296
		Jetpack_Sync_Options::update_option( self::STATUS_OPTION_PREFIX . "_$name", $value, $autoload );
297
	}
298
299
	private function set_enqueue_status( $new_status ) {
300
		Jetpack_Sync_Options::update_option( 'jetpack_sync_full_enqueue_status', $new_status );
301
	}
302
303
	private function get_enqueue_status() {
304
		return Jetpack_Sync_Options::get_option( 'jetpack_sync_full_enqueue_status' );
305
	}
306
307
	private function set_config( $config ) {
308
		Jetpack_Sync_Options::update_option( 'jetpack_sync_full_config', $config );
309
	}
310
	
311
	private function get_config() {
312
		return Jetpack_Sync_Options::get_option( 'jetpack_sync_full_config' );
313
	}
314
315
	private function write_option( $name, $value ) {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
316
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
317
		global $wpdb;
318
		$serialized_value = maybe_serialize( $value );
319
		// try updating, if no update then insert
320
		// 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...
321
		// below we used "insert ignore" to at least suppress the resulting error
322
		$updated_num = $wpdb->query(
323
			$wpdb->prepare(
324
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", 
325
				$serialized_value,
326
				$name
327
			)
328
		);
329
330
		if ( ! $updated_num ) {
331
			$updated_num = $wpdb->query(
332
				$wpdb->prepare(
333
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", 
334
					$name,
335
					$serialized_value
336
				)
337
			);
338
		}
339
		return $updated_num;
340
	}
341
342 View Code Duplication
	private function read_option( $name, $default = null ) {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
343
		global $wpdb;
344
		$value = $wpdb->get_var( 
345
			$wpdb->prepare(
346
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", 
347
				$name
348
			)
349
		);
350
		$value = maybe_unserialize( $value );
351
352
		if ( $value === null && $default !== null ) {
353
			return $default;
354
		}
355
356
		return $value;
357
	}
358
}
359