Completed
Push — master-stable ( 1bac3c...e4630d )
by Jeremy
384:01 queued 373:54
created

Jetpack_Sync_Actions::send_db_checksum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 9.4285
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_full', array( __CLASS__, 'do_full_sync' ), 10, 1 );
40
		add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
41
42
		if ( ! wp_next_scheduled( 'jetpack_sync_cron' ) ) {
43
			// Schedule a job to send pending queue items once a minute
44
			wp_schedule_event( time(), '1min', 'jetpack_sync_cron' );
45
		}
46
47
		/**
48
		 * Fires on every request before default loading sync listener code.
49
		 * Return false to not load sync listener code that monitors common
50
		 * WP actions to be serialized.
51
		 *
52
		 * By default this returns true for non-GET-requests, or requests where the
53
		 * user is logged-in.
54
		 *
55
		 * @since 4.2.0
56
		 *
57
		 * @param bool should we load sync listener code for this request
58
		 */
59
		if ( apply_filters( 'jetpack_sync_listener_should_load',
60
			(
61
				'GET' !== $_SERVER['REQUEST_METHOD']
62
				||
63
				is_user_logged_in()
64
				||
65
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
66
			)
67
		) ) {
68
			self::initialize_listener();
69
		}
70
71
		/**
72
		 * Fires on every request before default loading sync sender code.
73
		 * Return false to not load sync sender code that serializes pending
74
		 * data and sends it to WPCOM for processing.
75
		 *
76
		 * By default this returns true for POST requests, admin requests, or requests
77
		 * by users who can manage_options.
78
		 *
79
		 * @since 4.2.0
80
		 *
81
		 * @param bool should we load sync sender code for this request
82
		 */
83
		if ( apply_filters( 'jetpack_sync_sender_should_load',
84
			(
85
				'POST' === $_SERVER['REQUEST_METHOD']
86
				||
87
				current_user_can( 'manage_options' )
88
				||
89
				is_admin()
90
				||
91
				defined( 'PHPUNIT_JETPACK_TESTSUITE' )
92
			)
93
		) ) {
94
			self::initialize_sender();
95
			add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
96
		}
97
98
	}
99
100
	static function sync_allowed() {
101
		return ( ! Jetpack_Sync_Settings::get_setting( 'disable' ) && Jetpack::is_active() && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
102
			   || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
103
	}
104
105
	static function set_is_importing_true() {
106
		Jetpack_Sync_Settings::set_importing( true );
107
	}
108
109
	static function send_data( $data, $codec_name, $sent_timestamp, $queue_id ) {
110
		Jetpack::load_xml_rpc_client();
111
112
		$url = add_query_arg( array(
113
			'sync'      => '1', // add an extra parameter to the URL so we can tell it's a sync action
114
			'codec'     => $codec_name, // send the name of the codec used to encode the data
115
			'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
116
			'queue'     => $queue_id, // sync or full_sync
117
		), Jetpack::xmlrpc_api_url() );
118
119
		$rpc = new Jetpack_IXR_Client( array(
120
			'url'     => $url,
121
			'user_id' => JETPACK_MASTER_USER,
122
			'timeout' => 30,
123
		) );
124
125
		$result = $rpc->query( 'jetpack.syncActions', $data );
126
127
		if ( ! $result ) {
128
			return $rpc->get_jetpack_error();
129
		}
130
131
		return $rpc->getResponse();
132
	}
133
134
	static function get_initial_sync_user_config() {
135
		global $wpdb;
136
137
		$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 ) );
138
139
		if ( count( $user_ids ) <= self::MAX_INITIAL_SYNC_USERS ) {
140
			return $user_ids;
141
		} else {
142
			return false;
143
		}
144
	}
145
146
	static function schedule_initial_sync() {
147
		// we need this function call here because we have to run this function
148
		// reeeeally early in init, before WP_CRON_LOCK_TIMEOUT is defined.
149
		wp_functionality_constants();
150
151
		if ( is_multisite() ) {
152
			// stagger initial syncs for multisite blogs so they don't all pile on top of each other
153
			$time_offset = ( rand() / getrandmax() ) * self::INITIAL_SYNC_MULTISITE_INTERVAL * get_blog_count();
154
		} else {
155
			$time_offset = 1;
156
		}
157
158
		self::schedule_full_sync( 
159
			array( 
160
				'options' => true, 
161
				'network_options' => true, 
162
				'functions' => true, 
163
				'constants' => true, 
164
				'users' => self::get_initial_sync_user_config() 
165
			),
166
			$time_offset
167
		);
168
	}
169
170
	static function schedule_full_sync( $modules = null, $time_offset = 1 ) {
171
		if ( ! self::sync_allowed() ) {
172
			return false;
173
		}
174
175
		if ( self::is_scheduled_full_sync() ) {
176
			self::unschedule_all_full_syncs();
177
		}
178
179
		if ( $modules ) {
180
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full', array( $modules ) );
181
		} else {
182
			wp_schedule_single_event( time() + $time_offset, 'jetpack_sync_full' );
183
		}
184
185
		if ( $time_offset === 1 ) {
186
			spawn_cron();
187
		}
188
189
		return true;
190
	}
191
192
	static function unschedule_all_full_syncs() {
193
		foreach ( _get_cron_array() as $timestamp => $cron ) {
194
			if ( ! empty( $cron['jetpack_sync_full'] ) ) {
195
				foreach( $cron['jetpack_sync_full'] as $key => $config ) {
196
					wp_unschedule_event( $timestamp, 'jetpack_sync_full', $config['args'] );
197
				}
198
			}
199
		}
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 initialize_listener() {
269
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
270
		self::$listener = Jetpack_Sync_Listener::get_instance();
271
	}
272
273
	static function initialize_sender() {
274
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
275
		self::$sender = Jetpack_Sync_Sender::get_instance();
276
277
		// bind the sending process
278
		add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 4 );
279
	}
280
}
281
282
// Allow other plugins to add filters before we initialize the actions.
283
// Load the listeners if before modules get loaded so that we can capture version changes etc.
284
add_action( 'init', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
285
286
// We need to define this here so that it's hooked before `updating_jetpack_version` is called
287
add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'schedule_initial_sync' ), 10 );
288