Completed
Push — 4.2-schedules ( 872172 )
by
unknown
720:32 queued 709:14
created

Jetpack_Sync_Actions::schedule_full_sync()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 3 Features 1
Metric Value
cc 5
eloc 12
c 5
b 3
f 1
nc 9
nop 2
dl 0
loc 25
rs 8.439
1
<?php
2
require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
3
4
/**
5
 * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
6
 * when to send, when to perform a full sync, etc.
7
 *
8
 * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
9
 */
10
class Jetpack_Sync_Actions {
11
	static $sender = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $sender.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
12
	static $listener = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $listener.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
13
	const MAX_INITIAL_SYNC_USERS = 100;
14
	const INITIAL_SYNC_MULTISITE_INTERVAL = 10;
15
16
	static function init() {
17
		
18
		// Add a custom "every minute" cron schedule
19
		add_filter( 'cron_schedules', array( __CLASS__, 'minute_cron_schedule' ) );
20
21
		// On jetpack authorization, schedule a full sync
22
		add_action( 'jetpack_client_authorized', array( __CLASS__, 'schedule_full_sync' ) );
23
		
24
		// When imports are finished, schedule a full sync
25
		add_action( 'import_end', array( __CLASS__, 'schedule_full_sync' ) );
26
27
		// When importing via cron, do not sync
28
		add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
29
30
		// Sync connected user role changes to .com
31
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
32
33
		// everything below this point should only happen if we're a valid sync site
34
		if ( ! self::sync_allowed() ) {
35
			return;
36
		}
37
38
		// cron hooks
39
		add_action( 'jetpack_sync_send_db_checksum', array( __CLASS__, 'send_db_checksum' ) );
40
		add_action( 'jetpack_sync_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
41
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
42
43
		if ( ! wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
44
			// Schedule a job to send DB checksums once an hour
45
			wp_schedule_event( time(), 'hourly', 'jetpack_sync_send_db_checksum' );
46
		}
47
48
		if ( ! wp_next_scheduled( 'jetpack_sync_cron' ) ) {
49
			// Schedule a job to send pending queue items once a minute
50
			wp_schedule_event( time(), '1min', 'jetpack_sync_cron' );
51
		}
52
53
		/**
54
		 * Fires on every request before default loading sync listener code.
55
		 * Return false to not load sync listener code that monitors common
56
		 * WP actions to be serialized.
57
		 *
58
		 * By default this returns true for non-GET-requests, or requests where the
59
		 * user is logged-in.
60
		 *
61
		 * @since 4.2.0
62
		 *
63
		 * @param bool should we load sync listener code for this request
64
		 */
65
		if ( apply_filters( 'jetpack_sync_listener_should_load',
66
			(
67
				'GET' !== $_SERVER['REQUEST_METHOD']
68
				||
69
				is_user_logged_in()
70
				||
71
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
72
			)
73
		) ) {
74
			self::initialize_listener();
75
		}
76
77
		/**
78
		 * Fires on every request before default loading sync sender code.
79
		 * Return false to not load sync sender code that serializes pending
80
		 * data and sends it to WPCOM for processing.
81
		 *
82
		 * By default this returns true for POST requests, admin requests, or requests
83
		 * by users who can manage_options.
84
		 *
85
		 * @since 4.2.0
86
		 *
87
		 * @param bool should we load sync sender code for this request
88
		 */
89
		if ( apply_filters( 'jetpack_sync_sender_should_load',
90
			(
91
				'POST' === $_SERVER['REQUEST_METHOD']
92
				||
93
				current_user_can( 'manage_options' )
94
				||
95
				is_admin()
96
				||
97
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
98
			)
99
		) ) {
100
			self::initialize_sender();
101
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
102
		}
103
104
	}
105
106
	static function sync_allowed() {
107
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
108
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
109
	}
110
111
	static function set_is_importing_true() {
112
		Jetpack_Sync_Settings::set_importing( true );
113
	}
114
115
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id ) {
116
		Jetpack::load_xml_rpc_client();
117
118
		$url = add_query_arg( array(
119
			'sync'      => '1', // add an extra parameter to the URL so we can tell it's a sync action
120
			'codec'     => $codec_name, // send the name of the codec used to encode the data
121
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
122
			'queue'     => $queue_id, // sync or full_sync
123
		), Jetpack::xmlrpc_api_url() );
124
125
		$rpc = new Jetpack_IXR_Client( array(
126
			'url'     => $url,
127
			'user_id' => JETPACK_MASTER_USER,
128
			'timeout' => 30,
129
		) );
130
131
		$result = $rpc->query( 'jetpack.syncActions', $data );
132
133
		if ( ! $result ) {
134
			return $rpc->get_jetpack_error();
135
		}
136
137
		return $rpc->getResponse();
138
	}
139
140
	static function get_initial_sync_user_config() {
141
		global $wpdb;
142
143
		$user_ids = $wpdb->get_col( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}user_level' AND meta_value > 0 LIMIT " . ( self::MAX_INITIAL_SYNC_USERS + 1 ) );
144
145
		if ( count( $user_ids ) <= self::MAX_INITIAL_SYNC_USERS ) {
146
			return $user_ids;
147
		} else {
148
			return false;
149
		}
150
	}
151
152
	static function schedule_initial_sync() {
153
		// we need this function call here because we have to run this function
154
		// reeeeally early in init, before WP_CRON_LOCK_TIMEOUT is defined.
155
		wp_functionality_constants();
156
157
		if ( is_multisite() ) {
158
			// stagger initial syncs for multisite blogs so they don't all pile on top of each other
159
			$time_offset = ( rand() / getrandmax() ) * self::INITIAL_SYNC_MULTISITE_INTERVAL * get_blog_count();
160
		} else {
161
			$time_offset = 1;
162
		}
163
164
		self::schedule_full_sync( 
165
			array( 
166
				'options' => true, 
167
				'network_options' => true, 
168
				'functions' => true, 
169
				'constants' => true, 
170
				'users' => self::get_initial_sync_user_config() 
171
			),
172
			$time_offset
173
		);
174
	}
175
176
	static function schedule_full_sync( $modules = null, $time_offset = 1 ) {
177
		if ( ! self::sync_allowed() ) {
178
			return false;
179
		}
180
181
		// Parse cron args
182
		$args = array();
183
184
		if ( $modules ) {
185
			$args = array( $modules );
186
		}
187
188
		// Clear existing scheduled events
189
		if ( wp_next_scheduled( 'jetpack_sync_cron', $args ) ) {
190
			wp_clear_scheduled_hook( 'jetpack_sync_cron', $args );
191
		}
192
193
		wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full', $args );
194
195
		if ( $time_offset === 1 ) {
196
			spawn_cron();
197
		}
198
199
		return true;
200
	}
201
202
	static function is_scheduled_full_sync( $modules = null ) {
203
		if ( is_null( $modules ) ) {
204
			$crons = _get_cron_array();
205
			
206
			foreach ( $crons as $timestamp => $cron ) {
207
				if ( ! empty( $cron['jetpack_sync_full'] ) ) {
208
					return true;
209
				}
210
			}
211
			return false;
212
		}
213
214
		return wp_next_scheduled( 'jetpack_sync_full', array( $modules ) );
215
	}
216
217
	static function do_full_sync( $modules = null ) {
218
		if ( ! self::sync_allowed() ) {
219
			return;
220
		}
221
222
		self::initialize_listener();
223
		Jetpack_Sync_Modules::get_module( 'full-sync' )->start( $modules );
224
		self::do_cron_sync(); // immediately run a cron sync, which sends pending data
225
	}
226
227
	static function minute_cron_schedule( $schedules ) {
228
		if( ! isset( $schedules["1min"] ) ) {
229
			$schedules["1min"] = array(
230
				'interval' => 60,
231
				'display' => __( 'Every minute' ) 
232
			);
233
		}
234
		return $schedules;
235
	}
236
237
	// try to send actions until we run out of things to send,
238
	// or have to wait more than 15s before sending again,
239
	// or we hit a lock or some other sending issue
240
	static function do_cron_sync() {
241
		if ( ! self::sync_allowed() ) {
242
			return;
243
		}
244
245
		self::initialize_sender();
246
		
247
		// remove shutdown hook - no need to sync twice
248
		if ( has_action( 'shutdown', array( self::$sender, 'do_sync' ) ) ) {
249
			remove_action( 'shutdown', array( self::$sender, 'do_sync' ) );
250
		}
251
252
		do {
253
			$next_sync_time = self::$sender->get_next_sync_time();
254
			
255
			if ( $next_sync_time ) {
256
				$delay = $next_sync_time - time() + 1;
257
				if ( $delay > 15 ) {
258
					break;
259
				} elseif ( $delay > 0 ) {
260
					sleep( $delay );
261
				}
262
			}
263
264
			$result = self::$sender->do_sync();
265
		} while ( $result );
266
	}
267
268
	static function send_db_checksum() {
269
		self::initialize_listener();
270
		self::initialize_sender();
271
		self::$sender->send_checksum();
272
		self::$sender->do_sync();
273
	}
274
275
	static function initialize_listener() {
276
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
277
		self::$listener = Jetpack_Sync_Listener::get_instance();
278
	}
279
280
	static function initialize_sender() {
281
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
282
		self::$sender = Jetpack_Sync_Sender::get_instance();
283
284
		// bind the sending process
285
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
286
	}
287
}
288
289
// Allow other plugins to add filters before we initialize the actions.
290
// Load the listeners if before modules get loaded so that we can capture version changes etc.
291
add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
292
293
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
294
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'schedule_initial_sync' ), 10 );
295