Completed
Push — update/pre_connection_jitms_pl... ( 9bf136...a14e59 )
by
unknown
214:58 queued 207:06
created

Replicastore::comment_meta_checksum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Sync replicastore.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
/**
11
 * An implementation of Replicastore Interface which returns data stored in a WordPress.org DB.
12
 * This is useful to compare values in the local WP DB to values in the synced replica store
13
 */
14
class Replicastore implements Replicastore_Interface {
15
	/**
16
	 * Empty and reset the replicastore.
17
	 *
18
	 * @access public
19
	 */
20
	public function reset() {
21
		global $wpdb;
22
23
		$wpdb->query( "DELETE FROM $wpdb->posts" );
24
25
		// Delete comments from cache.
26
		$comment_ids = $wpdb->get_col( "SELECT comment_ID FROM $wpdb->comments" );
27
		if ( ! empty( $comment_ids ) ) {
28
			clean_comment_cache( $comment_ids );
29
		}
30
		$wpdb->query( "DELETE FROM $wpdb->comments" );
31
32
		// Also need to delete terms from cache.
33
		$term_ids = $wpdb->get_col( "SELECT term_id FROM $wpdb->terms" );
34
		foreach ( $term_ids as $term_id ) {
35
			wp_cache_delete( $term_id, 'terms' );
36
		}
37
38
		$wpdb->query( "DELETE FROM $wpdb->terms" );
39
40
		$wpdb->query( "DELETE FROM $wpdb->term_taxonomy" );
41
		$wpdb->query( "DELETE FROM $wpdb->term_relationships" );
42
43
		// Callables and constants.
44
		$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'jetpack_%'" );
45
		$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key NOT LIKE '\_%'" );
46
	}
47
48
	/**
49
	 * Ran when full sync has just started.
50
	 *
51
	 * @access public
52
	 *
53
	 * @param array $config Full sync configuration for this sync module.
54
	 */
55
	public function full_sync_start( $config ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
56
		$this->reset();
57
	}
58
59
	/**
60
	 * Ran when full sync has just finished.
61
	 *
62
	 * @access public
63
	 *
64
	 * @param string $checksum Deprecated since 7.3.0.
65
	 */
66
	public function full_sync_end( $checksum ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
67
		// Noop right now.
68
	}
69
70
	/**
71
	 * Retrieve the number of terms.
72
	 *
73
	 * @access public
74
	 *
75
	 * @return int Number of terms.
76
	 */
77
	public function term_count() {
78
		global $wpdb;
79
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->terms" );
80
	}
81
82
	/**
83
	 * Retrieve the number of rows in the `term_taxonomy` table.
84
	 *
85
	 * @access public
86
	 *
87
	 * @return int Number of terms.
88
	 */
89
	public function term_taxonomy_count() {
90
		global $wpdb;
91
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->term_taxonomy" );
92
	}
93
94
	/**
95
	 * Retrieve the number of term relationships.
96
	 *
97
	 * @access public
98
	 *
99
	 * @return int Number of rows in the term relationships table.
100
	 */
101
	public function term_relationship_count() {
102
		global $wpdb;
103
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->term_relationships" );
104
	}
105
106
	/**
107
	 * Retrieve the number of posts with a particular post status within a certain range.
108
	 *
109
	 * @access public
110
	 *
111
	 * @todo Prepare the SQL query before executing it.
112
	 *
113
	 * @param string $status Post status.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
114
	 * @param int    $min_id Minimum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
115
	 * @param int    $max_id Maximum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
116
	 * @return int Number of posts.
117
	 */
118 View Code Duplication
	public function post_count( $status = null, $min_id = null, $max_id = null ) {
119
		global $wpdb;
120
121
		$where = '';
0 ignored issues
show
Unused Code introduced by
$where 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...
122
123
		if ( $status ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $status of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
124
			$where = "post_status = '" . esc_sql( $status ) . "'";
125
		} else {
126
			$where = '1=1';
127
		}
128
129
		if ( ! empty( $min_id ) ) {
130
			$where .= ' AND ID >= ' . (int) $min_id;
131
		}
132
133
		if ( ! empty( $max_id ) ) {
134
			$where .= ' AND ID <= ' . (int) $max_id;
135
		}
136
137
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
138
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE $where" );
139
	}
140
141
	/**
142
	 * Retrieve the posts with a particular post status.
143
	 *
144
	 * @access public
145
	 *
146
	 * @todo Implement range and actually use max_id/min_id arguments.
147
	 *
148
	 * @param string $status Post status.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
149
	 * @param int    $min_id Minimum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
150
	 * @param int    $max_id Maximum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
151
	 * @return array Array of posts.
152
	 */
153
	public function get_posts( $status = null, $min_id = null, $max_id = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
154
		$args = array(
155
			'orderby'        => 'ID',
156
			'posts_per_page' => -1,
157
		);
158
159
		if ( $status ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $status of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
160
			$args['post_status'] = $status;
161
		} else {
162
			$args['post_status'] = 'any';
163
		}
164
165
		return get_posts( $args );
166
	}
167
168
	/**
169
	 * Retrieve a post object by the post ID.
170
	 *
171
	 * @access public
172
	 *
173
	 * @param int $id Post ID.
174
	 * @return \WP_Post Post object.
175
	 */
176
	public function get_post( $id ) {
177
		return get_post( $id );
178
	}
179
180
	/**
181
	 * Update or insert a post.
182
	 *
183
	 * @access public
184
	 *
185
	 * @param \WP_Post $post   Post object.
186
	 * @param bool     $silent Whether to perform a silent action. Not used in this implementation.
187
	 */
188
	public function upsert_post( $post, $silent = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
189
		global $wpdb;
190
191
		// Reject the post if it's not a \WP_Post.
192
		if ( ! $post instanceof \WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
193
			return;
194
		}
195
196
		$post = $post->to_array();
197
198
		// Reject posts without an ID.
199
		if ( ! isset( $post['ID'] ) ) {
200
			return;
201
		}
202
203
		$now     = current_time( 'mysql' );
204
		$now_gmt = get_gmt_from_date( $now );
205
206
		$defaults = array(
207
			'ID'                    => 0,
208
			'post_author'           => '0',
209
			'post_content'          => '',
210
			'post_content_filtered' => '',
211
			'post_title'            => '',
212
			'post_name'             => '',
213
			'post_excerpt'          => '',
214
			'post_status'           => 'draft',
215
			'post_type'             => 'post',
216
			'comment_status'        => 'closed',
217
			'comment_count'         => '0',
218
			'ping_status'           => '',
219
			'post_password'         => '',
220
			'to_ping'               => '',
221
			'pinged'                => '',
222
			'post_parent'           => 0,
223
			'menu_order'            => 0,
224
			'guid'                  => '',
225
			'post_date'             => $now,
226
			'post_date_gmt'         => $now_gmt,
227
			'post_modified'         => $now,
228
			'post_modified_gmt'     => $now_gmt,
229
		);
230
231
		$post = array_intersect_key( $post, $defaults );
232
233
		$post = sanitize_post( $post, 'db' );
234
235
		unset( $post['filter'] );
236
237
		$exists = $wpdb->get_var( $wpdb->prepare( "SELECT EXISTS( SELECT 1 FROM $wpdb->posts WHERE ID = %d )", $post['ID'] ) );
238
239
		if ( $exists ) {
240
			$wpdb->update( $wpdb->posts, $post, array( 'ID' => $post['ID'] ) );
241
		} else {
242
			$wpdb->insert( $wpdb->posts, $post );
243
		}
244
245
		clean_post_cache( $post['ID'] );
246
	}
247
248
	/**
249
	 * Delete a post by the post ID.
250
	 *
251
	 * @access public
252
	 *
253
	 * @param int $post_id Post ID.
254
	 */
255
	public function delete_post( $post_id ) {
256
		wp_delete_post( $post_id, true );
257
	}
258
259
	/**
260
	 * Retrieve the checksum for posts within a range.
261
	 *
262
	 * @access public
263
	 *
264
	 * @param int $min_id Minimum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
265
	 * @param int $max_id Maximum post ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
266
	 * @return int The checksum.
267
	 */
268
	public function posts_checksum( $min_id = null, $max_id = null ) {
269
		global $wpdb;
270
		return $this->table_checksum( $wpdb->posts, Defaults::$default_post_checksum_columns, 'ID', Settings::get_blacklisted_post_types_sql(), $min_id, $max_id );
271
	}
272
273
	/**
274
	 * Retrieve the checksum for post meta within a range.
275
	 *
276
	 * @access public
277
	 *
278
	 * @param int $min_id Minimum post meta ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
279
	 * @param int $max_id Maximum post meta ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
280
	 * @return int The checksum.
281
	 */
282
	public function post_meta_checksum( $min_id = null, $max_id = null ) {
283
		global $wpdb;
284
		return $this->table_checksum( $wpdb->postmeta, Defaults::$default_post_meta_checksum_columns, 'meta_id', Settings::get_whitelisted_post_meta_sql(), $min_id, $max_id );
285
	}
286
287
	/**
288
	 * Retrieve the number of comments with a particular comment status within a certain range.
289
	 *
290
	 * @access public
291
	 *
292
	 * @todo Prepare the SQL query before executing it.
293
	 *
294
	 * @param string $status Comment status.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
295
	 * @param int    $min_id Minimum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
296
	 * @param int    $max_id Maximum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
297
	 * @return int Number of comments.
298
	 */
299 View Code Duplication
	public function comment_count( $status = null, $min_id = null, $max_id = null ) {
300
		global $wpdb;
301
302
		$comment_approved = $this->comment_status_to_approval_value( $status );
303
304
		if ( false !== $comment_approved ) {
305
			$where = "comment_approved = '" . esc_sql( $comment_approved ) . "'";
306
		} else {
307
			$where = '1=1';
308
		}
309
310
		if ( ! empty( $min_id ) ) {
311
			$where .= ' AND comment_ID >= ' . (int) $min_id;
312
		}
313
314
		if ( ! empty( $max_id ) ) {
315
			$where .= ' AND comment_ID <= ' . (int) $max_id;
316
		}
317
318
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
319
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE $where" );
320
	}
321
322
	/**
323
	 * Translate a comment status to a value of the comment_approved field.
324
	 *
325
	 * @access private
326
	 *
327
	 * @param string $status Comment status.
328
	 * @return string|bool New comment_approved value, false if the status doesn't affect it.
329
	 */
330
	private function comment_status_to_approval_value( $status ) {
331
		switch ( $status ) {
332
			case 'approve':
333
				return '1';
334
			case 'hold':
335
				return '0';
336
			case 'spam':
337
				return 'spam';
338
			case 'trash':
339
				return 'trash';
340
			case 'any':
341
				return false;
342
			case 'all':
343
				return false;
344
			default:
345
				return false;
346
		}
347
	}
348
349
	/**
350
	 * Retrieve the comments with a particular comment status.
351
	 *
352
	 * @access public
353
	 *
354
	 * @todo Implement range and actually use max_id/min_id arguments.
355
	 *
356
	 * @param string $status Comment status.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
357
	 * @param int    $min_id Minimum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
358
	 * @param int    $max_id Maximum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
359
	 * @return array Array of comments.
360
	 */
361
	public function get_comments( $status = null, $min_id = null, $max_id = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
362
		$args = array(
363
			'orderby' => 'ID',
364
			'status'  => 'all',
365
		);
366
367
		if ( $status ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $status of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
368
			$args['status'] = $status;
369
		}
370
371
		return get_comments( $args );
372
	}
373
374
	/**
375
	 * Retrieve a comment object by the comment ID.
376
	 *
377
	 * @access public
378
	 *
379
	 * @param int $id Comment ID.
380
	 * @return \WP_Comment Comment object.
381
	 */
382
	public function get_comment( $id ) {
383
		return \WP_Comment::get_instance( $id );
384
	}
385
386
	/**
387
	 * Update or insert a comment.
388
	 *
389
	 * @access public
390
	 *
391
	 * @param \WP_Comment $comment Comment object.
392
	 */
393
	public function upsert_comment( $comment ) {
394
		global $wpdb;
395
396
		$comment = $comment->to_array();
397
398
		// Filter by fields on comment table.
399
		$comment_fields_whitelist = array(
400
			'comment_ID',
401
			'comment_post_ID',
402
			'comment_author',
403
			'comment_author_email',
404
			'comment_author_url',
405
			'comment_author_IP',
406
			'comment_date',
407
			'comment_date_gmt',
408
			'comment_content',
409
			'comment_karma',
410
			'comment_approved',
411
			'comment_agent',
412
			'comment_type',
413
			'comment_parent',
414
			'user_id',
415
		);
416
417
		foreach ( $comment as $key => $value ) {
418
			if ( ! in_array( $key, $comment_fields_whitelist, true ) ) {
419
				unset( $comment[ $key ] );
420
			}
421
		}
422
423
		$exists = $wpdb->get_var(
424
			$wpdb->prepare(
425
				"SELECT EXISTS( SELECT 1 FROM $wpdb->comments WHERE comment_ID = %d )",
426
				$comment['comment_ID']
427
			)
428
		);
429
430
		if ( $exists ) {
431
			$wpdb->update( $wpdb->comments, $comment, array( 'comment_ID' => $comment['comment_ID'] ) );
432
		} else {
433
			$wpdb->insert( $wpdb->comments, $comment );
434
		}
435
		// Remove comment from cache.
436
		clean_comment_cache( $comment['comment_ID'] );
437
438
		wp_update_comment_count( $comment['comment_post_ID'] );
439
	}
440
441
	/**
442
	 * Trash a comment by the comment ID.
443
	 *
444
	 * @access public
445
	 *
446
	 * @param int $comment_id Comment ID.
447
	 */
448
	public function trash_comment( $comment_id ) {
449
		wp_delete_comment( $comment_id );
450
	}
451
452
	/**
453
	 * Delete a comment by the comment ID.
454
	 *
455
	 * @access public
456
	 *
457
	 * @param int $comment_id Comment ID.
458
	 */
459
	public function delete_comment( $comment_id ) {
460
		wp_delete_comment( $comment_id, true );
461
	}
462
463
	/**
464
	 * Mark a comment by the comment ID as spam.
465
	 *
466
	 * @access public
467
	 *
468
	 * @param int $comment_id Comment ID.
469
	 */
470
	public function spam_comment( $comment_id ) {
471
		wp_spam_comment( $comment_id );
472
	}
473
474
	/**
475
	 * Trash the comments of a post.
476
	 *
477
	 * @access public
478
	 *
479
	 * @param int   $post_id  Post ID.
480
	 * @param array $statuses Post statuses. Not used in this implementation.
481
	 */
482
	public function trashed_post_comments( $post_id, $statuses ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
483
		wp_trash_post_comments( $post_id );
484
	}
485
486
	/**
487
	 * Untrash the comments of a post.
488
	 *
489
	 * @access public
490
	 *
491
	 * @param int $post_id Post ID.
492
	 */
493
	public function untrashed_post_comments( $post_id ) {
494
		wp_untrash_post_comments( $post_id );
495
	}
496
497
	/**
498
	 * Retrieve the checksum for comments within a range.
499
	 *
500
	 * @access public
501
	 *
502
	 * @param int $min_id Minimum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
503
	 * @param int $max_id Maximum comment ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
504
	 * @return int The checksum.
505
	 */
506
	public function comments_checksum( $min_id = null, $max_id = null ) {
507
		global $wpdb;
508
		return $this->table_checksum( $wpdb->comments, Defaults::$default_comment_checksum_columns, 'comment_ID', Settings::get_comments_filter_sql(), $min_id, $max_id );
509
	}
510
511
	/**
512
	 * Retrieve the checksum for comment meta within a range.
513
	 *
514
	 * @access public
515
	 *
516
	 * @param int $min_id Minimum comment meta ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
517
	 * @param int $max_id Maximum comment meta ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
518
	 * @return int The checksum.
519
	 */
520
	public function comment_meta_checksum( $min_id = null, $max_id = null ) {
521
		global $wpdb;
522
		return $this->table_checksum( $wpdb->commentmeta, Defaults::$default_comment_meta_checksum_columns, 'meta_id', Settings::get_whitelisted_comment_meta_sql(), $min_id, $max_id );
523
	}
524
525
	/**
526
	 * Retrieve the checksum for all options.
527
	 *
528
	 * @access public
529
	 *
530
	 * @return int The checksum.
531
	 */
532
	public function options_checksum() {
533
		global $wpdb;
534
		$options_whitelist = "'" . implode( "', '", Defaults::$default_options_whitelist ) . "'";
535
		$where_sql         = "option_name IN ( $options_whitelist )";
536
537
		return $this->table_checksum( $wpdb->options, Defaults::$default_option_checksum_columns, null, $where_sql, null, null );
538
	}
539
540
	/**
541
	 * Update the value of an option.
542
	 *
543
	 * @access public
544
	 *
545
	 * @param string $option Option name.
546
	 * @param mixed  $value  Option value.
547
	 * @return bool False if value was not updated and true if value was updated.
548
	 */
549
	public function update_option( $option, $value ) {
550
		return update_option( $option, $value );
551
	}
552
553
	/**
554
	 * Retrieve an option value based on an option name.
555
	 *
556
	 * @access public
557
	 *
558
	 * @param string $option  Name of option to retrieve.
559
	 * @param mixed  $default Optional. Default value to return if the option does not exist.
560
	 * @return mixed Value set for the option.
561
	 */
562
	public function get_option( $option, $default = false ) {
563
		return get_option( $option, $default );
564
	}
565
566
	/**
567
	 * Remove an option by name.
568
	 *
569
	 * @access public
570
	 *
571
	 * @param string $option Name of option to remove.
572
	 * @return bool True, if option is successfully deleted. False on failure.
573
	 */
574
	public function delete_option( $option ) {
575
		return delete_option( $option );
576
	}
577
578
	/**
579
	 * Change the info of the current theme.
580
	 *
581
	 * @access public
582
	 *
583
	 * @param array $theme_info Theme info array.
584
	 */
585
	public function set_theme_info( $theme_info ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
586
		// Noop.
587
	}
588
589
	/**
590
	 * Whether the current theme supports a certain feature.
591
	 *
592
	 * @access public
593
	 *
594
	 * @param string $feature Name of the feature.
595
	 */
596
	public function current_theme_supports( $feature ) {
597
		return current_theme_supports( $feature );
598
	}
599
600
	/**
601
	 * Retrieve metadata for the specified object.
602
	 *
603
	 * @access public
604
	 *
605
	 * @param string $type       Meta type.
606
	 * @param int    $object_id  ID of the object.
607
	 * @param string $meta_key   Meta key.
608
	 * @param bool   $single     If true, return only the first value of the specified meta_key.
609
	 *
610
	 * @return mixed Single metadata value, or array of values.
611
	 */
612
	public function get_metadata( $type, $object_id, $meta_key = '', $single = false ) {
613
		return get_metadata( $type, $object_id, $meta_key, $single );
614
	}
615
616
	/**
617
	 * Stores remote meta key/values alongside an ID mapping key.
618
	 *
619
	 * @access public
620
	 *
621
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
622
	 *
623
	 * @param string $type       Meta type.
624
	 * @param int    $object_id  ID of the object.
625
	 * @param string $meta_key   Meta key.
626
	 * @param mixed  $meta_value Meta value.
627
	 * @param int    $meta_id    ID of the meta.
628
	 *
629
	 * @return bool False if meta table does not exist, true otherwise.
630
	 */
631
	public function upsert_metadata( $type, $object_id, $meta_key, $meta_value, $meta_id ) {
632
		$table = _get_meta_table( $type );
633
		if ( ! $table ) {
634
			return false;
635
		}
636
637
		global $wpdb;
638
639
		$exists = $wpdb->get_var(
640
			$wpdb->prepare(
641
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
642
				"SELECT EXISTS( SELECT 1 FROM $table WHERE meta_id = %d )",
643
				$meta_id
644
			)
645
		);
646
647
		if ( $exists ) {
648
			$wpdb->update(
649
				$table,
650
				array(
651
					'meta_key'   => $meta_key,
652
					'meta_value' => maybe_serialize( $meta_value ),
653
				),
654
				array( 'meta_id' => $meta_id )
655
			);
656
		} else {
657
			$object_id_field = $type . '_id';
658
			$wpdb->insert(
659
				$table,
660
				array(
661
					'meta_id'        => $meta_id,
662
					$object_id_field => $object_id,
663
					'meta_key'       => $meta_key,
664
					'meta_value'     => maybe_serialize( $meta_value ),
665
				)
666
			);
667
		}
668
669
		wp_cache_delete( $object_id, $type . '_meta' );
670
671
		return true;
672
	}
673
674
	/**
675
	 * Delete metadata for the specified object.
676
	 *
677
	 * @access public
678
	 *
679
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
680
	 *
681
	 * @param string $type      Meta type.
682
	 * @param int    $object_id ID of the object.
683
	 * @param array  $meta_ids  IDs of the meta objects to delete.
684
	 */
685
	public function delete_metadata( $type, $object_id, $meta_ids ) {
686
		global $wpdb;
687
688
		$table = _get_meta_table( $type );
689
		if ( ! $table ) {
690
			return false;
691
		}
692
693
		foreach ( $meta_ids as $meta_id ) {
694
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
695
			$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE meta_id = %d", $meta_id ) );
696
		}
697
698
		// If we don't have an object ID what do we do - invalidate ALL meta?
699
		if ( $object_id ) {
700
			wp_cache_delete( $object_id, $type . '_meta' );
701
		}
702
	}
703
704
	/**
705
	 * Delete metadata with a certain key for the specified objects.
706
	 *
707
	 * @access public
708
	 *
709
	 * @todo Test this out to make sure it works as expected.
710
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
711
	 *
712
	 * @param string $type       Meta type.
713
	 * @param array  $object_ids IDs of the objects.
714
	 * @param string $meta_key   Meta key.
715
	 */
716
	public function delete_batch_metadata( $type, $object_ids, $meta_key ) {
717
		global $wpdb;
718
719
		$table = _get_meta_table( $type );
720
		if ( ! $table ) {
721
			return false;
722
		}
723
		$column = sanitize_key( $type . '_id' );
724
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
725
		$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE $column IN (%s) && meta_key = %s", implode( ',', $object_ids ), $meta_key ) );
726
727
		// If we don't have an object ID what do we do - invalidate ALL meta?
728
		foreach ( $object_ids as $object_id ) {
729
			wp_cache_delete( $object_id, $type . '_meta' );
730
		}
731
	}
732
733
	/**
734
	 * Retrieve value of a constant based on the constant name.
735
	 *
736
	 * @access public
737
	 *
738
	 * @param string $constant Name of constant to retrieve.
739
	 * @return mixed Value set for the constant.
740
	 */
741
	public function get_constant( $constant ) {
742
		$value = get_option( 'jetpack_constant_' . $constant );
743
744
		if ( $value ) {
745
			return $value;
746
		}
747
748
		return null;
749
	}
750
751
	/**
752
	 * Set the value of a constant.
753
	 *
754
	 * @access public
755
	 *
756
	 * @param string $constant Name of constant to retrieve.
757
	 * @param mixed  $value    Value set for the constant.
758
	 */
759
	public function set_constant( $constant, $value ) {
760
		update_option( 'jetpack_constant_' . $constant, $value );
761
	}
762
763
	/**
764
	 * Retrieve the number of the available updates of a certain type.
765
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
766
	 *
767
	 * @access public
768
	 *
769
	 * @param string $type Type of updates to retrieve.
770
	 * @return int|null Number of updates available, `null` if type is invalid or missing.
771
	 */
772
	public function get_updates( $type ) {
773
		$all_updates = get_option( 'jetpack_updates', array() );
774
775
		if ( isset( $all_updates[ $type ] ) ) {
776
			return $all_updates[ $type ];
777
		} else {
778
			return null;
779
		}
780
	}
781
782
	/**
783
	 * Set the available updates of a certain type.
784
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
785
	 *
786
	 * @access public
787
	 *
788
	 * @param string $type    Type of updates to set.
789
	 * @param int    $updates Total number of updates.
790
	 */
791
	public function set_updates( $type, $updates ) {
792
		$all_updates          = get_option( 'jetpack_updates', array() );
793
		$all_updates[ $type ] = $updates;
794
		update_option( 'jetpack_updates', $all_updates );
795
	}
796
797
	/**
798
	 * Retrieve a callable value based on its name.
799
	 *
800
	 * @access public
801
	 *
802
	 * @param string $name Name of the callable to retrieve.
803
	 * @return mixed Value of the callable.
804
	 */
805
	public function get_callable( $name ) {
806
		$value = get_option( 'jetpack_' . $name );
807
808
		if ( $value ) {
809
			return $value;
810
		}
811
812
		return null;
813
	}
814
815
	/**
816
	 * Update the value of a callable.
817
	 *
818
	 * @access public
819
	 *
820
	 * @param string $name  Callable name.
821
	 * @param mixed  $value Callable value.
822
	 */
823
	public function set_callable( $name, $value ) {
824
		update_option( 'jetpack_' . $name, $value );
825
	}
826
827
	/**
828
	 * Retrieve a network option value based on a network option name.
829
	 *
830
	 * @access public
831
	 *
832
	 * @param string $option Name of network option to retrieve.
833
	 * @return mixed Value set for the network option.
834
	 */
835
	public function get_site_option( $option ) {
836
		return get_option( 'jetpack_network_' . $option );
837
	}
838
839
	/**
840
	 * Update the value of a network option.
841
	 *
842
	 * @access public
843
	 *
844
	 * @param string $option Network option name.
845
	 * @param mixed  $value  Network option value.
846
	 * @return bool False if value was not updated and true if value was updated.
847
	 */
848
	public function update_site_option( $option, $value ) {
849
		return update_option( 'jetpack_network_' . $option, $value );
850
	}
851
852
	/**
853
	 * Remove a network option by name.
854
	 *
855
	 * @access public
856
	 *
857
	 * @param string $option Name of option to remove.
858
	 * @return bool True, if option is successfully deleted. False on failure.
859
	 */
860
	public function delete_site_option( $option ) {
861
		return delete_option( 'jetpack_network_' . $option );
862
	}
863
864
	/**
865
	 * Retrieve the terms from a particular taxonomy.
866
	 *
867
	 * @access public
868
	 *
869
	 * @param string $taxonomy Taxonomy slug.
870
	 * @return array Array of terms.
871
	 */
872
	public function get_terms( $taxonomy ) {
873
		return get_terms( $taxonomy );
874
	}
875
876
	/**
877
	 * Retrieve a particular term.
878
	 *
879
	 * @access public
880
	 *
881
	 * @param string $taxonomy   Taxonomy slug.
882
	 * @param int    $term_id    ID of the term.
883
	 * @param bool   $is_term_id Whether this is a `term_id` or a `term_taxonomy_id`.
884
	 * @return \WP_Term|\WP_Error Term object on success, \WP_Error object on failure.
885
	 */
886
	public function get_term( $taxonomy, $term_id, $is_term_id = true ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
887
		$t = $this->ensure_taxonomy( $taxonomy );
888
		if ( ! $t || is_wp_error( $t ) ) {
889
			return $t;
890
		}
891
892
		return get_term( $term_id, $taxonomy );
893
	}
894
895
	/**
896
	 * Verify a taxonomy is legitimate and register it if necessary.
897
	 *
898
	 * @access private
899
	 *
900
	 * @param string $taxonomy Taxonomy slug.
901
	 * @return bool|void|\WP_Error True if already exists; void if it was registered; \WP_Error on error.
902
	 */
903
	private function ensure_taxonomy( $taxonomy ) {
904
		if ( ! taxonomy_exists( $taxonomy ) ) {
905
			// Try re-registering synced taxonomies.
906
			$taxonomies = $this->get_callable( 'taxonomies' );
907
			if ( ! isset( $taxonomies[ $taxonomy ] ) ) {
908
				// Doesn't exist, or somehow hasn't been synced.
909
				return new \WP_Error( 'invalid_taxonomy', "The taxonomy '$taxonomy' doesn't exist" );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_taxonomy'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
910
			}
911
			$t = $taxonomies[ $taxonomy ];
912
913
			return register_taxonomy(
914
				$taxonomy,
915
				$t->object_type,
916
				(array) $t
917
			);
918
		}
919
920
		return true;
921
	}
922
923
	/**
924
	 * Retrieve all terms from a taxonomy that are related to an object with a particular ID.
925
	 *
926
	 * @access public
927
	 *
928
	 * @param int    $object_id Object ID.
929
	 * @param string $taxonomy  Taxonomy slug.
930
	 * @return array|bool|\WP_Error Array of terms on success, `false` if no terms or post doesn't exist, \WP_Error on failure.
931
	 */
932
	public function get_the_terms( $object_id, $taxonomy ) {
933
		return get_the_terms( $object_id, $taxonomy );
934
	}
935
936
	/**
937
	 * Insert or update a term.
938
	 *
939
	 * @access public
940
	 *
941
	 * @param \WP_Term $term_object Term object.
942
	 * @return array|bool|\WP_Error Array of term_id and term_taxonomy_id if updated, true if inserted, \WP_Error on failure.
943
	 */
944
	public function update_term( $term_object ) {
945
		$taxonomy = $term_object->taxonomy;
946
		global $wpdb;
947
		$exists = $wpdb->get_var(
948
			$wpdb->prepare(
949
				"SELECT EXISTS( SELECT 1 FROM $wpdb->terms WHERE term_id = %d )",
950
				$term_object->term_id
951
			)
952
		);
953
		if ( ! $exists ) {
954
			$term_object   = sanitize_term( clone( $term_object ), $taxonomy, 'db' );
955
			$term          = array(
956
				'term_id'    => $term_object->term_id,
957
				'name'       => $term_object->name,
958
				'slug'       => $term_object->slug,
959
				'term_group' => $term_object->term_group,
960
			);
961
			$term_taxonomy = array(
962
				'term_taxonomy_id' => $term_object->term_taxonomy_id,
963
				'term_id'          => $term_object->term_id,
964
				'taxonomy'         => $term_object->taxonomy,
965
				'description'      => $term_object->description,
966
				'parent'           => (int) $term_object->parent,
967
				'count'            => (int) $term_object->count,
968
			);
969
			$wpdb->insert( $wpdb->terms, $term );
970
			$wpdb->insert( $wpdb->term_taxonomy, $term_taxonomy );
971
972
			return true;
973
		}
974
975
		return wp_update_term( $term_object->term_id, $taxonomy, (array) $term_object );
976
	}
977
978
	/**
979
	 * Delete a term by the term ID and its corresponding taxonomy.
980
	 *
981
	 * @access public
982
	 *
983
	 * @param int    $term_id  Term ID.
984
	 * @param string $taxonomy Taxonomy slug.
985
	 * @return bool|int|\WP_Error True on success, false if term doesn't exist. Zero if trying with default category. \WP_Error on invalid taxonomy.
986
	 */
987
	public function delete_term( $term_id, $taxonomy ) {
988
		return wp_delete_term( $term_id, $taxonomy );
989
	}
990
991
	/**
992
	 * Add/update terms of a particular taxonomy of an object with the specified ID.
993
	 *
994
	 * @access public
995
	 *
996
	 * @param int              $object_id The object to relate to.
997
	 * @param string           $taxonomy  The context in which to relate the term to the object.
998
	 * @param string|int|array $terms     A single term slug, single term id, or array of either term slugs or ids.
999
	 * @param bool             $append    Optional. If false will delete difference of terms. Default false.
1000
	 */
1001
	public function update_object_terms( $object_id, $taxonomy, $terms, $append ) {
1002
		wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
1003
	}
1004
1005
	/**
1006
	 * Remove certain term relationships from the specified object.
1007
	 *
1008
	 * @access public
1009
	 *
1010
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
1011
	 *
1012
	 * @param int   $object_id ID of the object.
1013
	 * @param array $tt_ids    Term taxonomy IDs.
1014
	 * @return bool True on success, false on failure.
1015
	 */
1016
	public function delete_object_terms( $object_id, $tt_ids ) {
1017
		global $wpdb;
1018
1019
		if ( is_array( $tt_ids ) && ! empty( $tt_ids ) ) {
1020
			// Escape.
1021
			$tt_ids_sanitized = array_map( 'intval', $tt_ids );
1022
1023
			$taxonomies = array();
1024
			foreach ( $tt_ids_sanitized as $tt_id ) {
1025
				$term                            = get_term_by( 'term_taxonomy_id', $tt_id );
1026
				$taxonomies[ $term->taxonomy ][] = $tt_id;
1027
			}
1028
			$in_tt_ids = implode( ', ', $tt_ids_sanitized );
1029
1030
			/**
1031
			 * Fires immediately before an object-term relationship is deleted.
1032
			 *
1033
			 * @since 2.9.0
1034
			 *
1035
			 * @param int   $object_id Object ID.
1036
			 * @param array $tt_ids    An array of term taxonomy IDs.
1037
			 */
1038
			do_action( 'delete_term_relationships', $object_id, $tt_ids_sanitized );
1039
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1040
			$deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
1041
			foreach ( $taxonomies as $taxonomy => $taxonomy_tt_ids ) {
1042
				$this->ensure_taxonomy( $taxonomy );
1043
				wp_cache_delete( $object_id, $taxonomy . '_relationships' );
1044
				/**
1045
				 * Fires immediately after an object-term relationship is deleted.
1046
				 *
1047
				 * @since 2.9.0
1048
				 *
1049
				 * @param int   $object_id Object ID.
1050
				 * @param array $tt_ids    An array of term taxonomy IDs.
1051
				 */
1052
				do_action( 'deleted_term_relationships', $object_id, $taxonomy_tt_ids );
1053
				wp_update_term_count( $taxonomy_tt_ids, $taxonomy );
1054
			}
1055
1056
			return (bool) $deleted;
1057
		}
1058
1059
		return false;
1060
	}
1061
1062
	/**
1063
	 * Retrieve the number of users.
1064
	 * Not supported in this replicastore.
1065
	 *
1066
	 * @access public
1067
	 */
1068
	public function user_count() {
1069
		// Noop.
1070
	}
1071
1072
	/**
1073
	 * Retrieve a user object by the user ID.
1074
	 *
1075
	 * @access public
1076
	 *
1077
	 * @param int $user_id User ID.
1078
	 * @return \WP_User User object.
1079
	 */
1080
	public function get_user( $user_id ) {
1081
		return \WP_User::get_instance( $user_id );
1082
	}
1083
1084
	/**
1085
	 * Insert or update a user.
1086
	 * Not supported in this replicastore.
1087
	 *
1088
	 * @access public
1089
	 * @throws \Exception If this method is invoked.
1090
	 *
1091
	 * @param \WP_User $user User object.
1092
	 */
1093
	public function upsert_user( $user ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1094
		$this->invalid_call();
1095
	}
1096
1097
	/**
1098
	 * Delete a user.
1099
	 * Not supported in this replicastore.
1100
	 *
1101
	 * @access public
1102
	 * @throws \Exception If this method is invoked.
1103
	 *
1104
	 * @param int $user_id User ID.
1105
	 */
1106
	public function delete_user( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1107
		$this->invalid_call();
1108
	}
1109
1110
	/**
1111
	 * Update/insert user locale.
1112
	 * Not supported in this replicastore.
1113
	 *
1114
	 * @access public
1115
	 * @throws \Exception If this method is invoked.
1116
	 *
1117
	 * @param int    $user_id User ID.
1118
	 * @param string $local   The user locale.
1119
	 */
1120
	public function upsert_user_locale( $user_id, $local ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1121
		$this->invalid_call();
1122
	}
1123
1124
	/**
1125
	 * Delete user locale.
1126
	 * Not supported in this replicastore.
1127
	 *
1128
	 * @access public
1129
	 * @throws \Exception If this method is invoked.
1130
	 *
1131
	 * @param int $user_id User ID.
1132
	 */
1133
	public function delete_user_locale( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1134
		$this->invalid_call();
1135
	}
1136
1137
	/**
1138
	 * Retrieve the user locale.
1139
	 *
1140
	 * @access public
1141
	 *
1142
	 * @param int $user_id User ID.
1143
	 * @return string The user locale.
1144
	 */
1145
	public function get_user_locale( $user_id ) {
1146
		return get_user_locale( $user_id );
1147
	}
1148
1149
	/**
1150
	 * Retrieve the allowed mime types for the user.
1151
	 * Not supported in this replicastore.
1152
	 *
1153
	 * @access public
1154
	 *
1155
	 * @param int $user_id User ID.
1156
	 */
1157
	public function get_allowed_mime_types( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1158
		// Noop.
1159
	}
1160
1161
	/**
1162
	 * Retrieve all the checksums we are interested in.
1163
	 * Currently that is posts, comments, post meta and comment meta.
1164
	 *
1165
	 * @access public
1166
	 *
1167
	 * @return array Checksums.
1168
	 */
1169
	public function checksum_all() {
1170
		$post_meta_checksum    = $this->checksum_histogram( 'post_meta', 1 );
1171
		$comment_meta_checksum = $this->checksum_histogram( 'comment_meta', 1 );
1172
1173
		return array(
1174
			'posts'        => $this->posts_checksum(),
1175
			'comments'     => $this->comments_checksum(),
1176
			'post_meta'    => reset( $post_meta_checksum ),
1177
			'comment_meta' => reset( $comment_meta_checksum ),
1178
		);
1179
	}
1180
1181
	/**
1182
	 * Retrieve the columns that are needed to calculate a checksum for an object type.
1183
	 *
1184
	 * @access public
1185
	 *
1186
	 * @todo Refactor to not use interpolated values and prepare the SQL query.
1187
	 *
1188
	 * @param string $object_type Object type.
1189
	 * @return array|bool Columns, or false if invalid object type is specified.
1190
	 */
1191
	public function get_checksum_columns_for_object_type( $object_type ) {
1192
		switch ( $object_type ) {
1193
			case 'posts':
1194
				return Defaults::$default_post_checksum_columns;
1195
			case 'post_meta':
1196
				return Defaults::$default_post_meta_checksum_columns;
1197
			case 'comments':
1198
				return Defaults::$default_comment_checksum_columns;
1199
			case 'comment_meta':
1200
				return Defaults::$default_post_meta_checksum_columns;
1201
			case 'terms':
1202
				return Defaults::$default_term_checksum_columns;
1203
			case 'term_taxonomy':
1204
				return Defaults::$default_term_taxonomy_checksum_columns;
1205
			case 'term_relationships':
1206
				return Defaults::$default_term_relationships_checksum_columns;
1207
			default:
1208
				return false;
1209
		}
1210
	}
1211
1212
	/**
1213
	 * Grabs the minimum and maximum object ids for the given parameters.
1214
	 *
1215
	 * @access public
1216
	 *
1217
	 * @param string $id_field     The id column in the table to query.
1218
	 * @param string $object_table The table to query.
1219
	 * @param string $where        A sql where clause without 'WHERE'.
1220
	 * @param int    $bucket_size  The maximum amount of objects to include in the query.
1221
	 *                             For `term_relationships` table, the bucket size will refer to the amount
1222
	 *                             of distinct object ids. This will likely include more database rows than
1223
	 *                             the bucket size implies.
1224
	 *
1225
	 * @return object An object with min_id and max_id properties.
1226
	 */
1227
	public function get_min_max_object_id( $id_field, $object_table, $where, $bucket_size ) {
1228
		global $wpdb;
1229
1230
		// The term relationship table's unique key is a combination of 2 columns. `DISTINCT` helps us get a more acurate query.
1231
		$distinct_sql = ( $wpdb->term_relationships === $object_table ) ? 'DISTINCT' : '';
1232
		$where_sql    = $where ? "WHERE $where" : '';
1233
1234
		// Since MIN() and MAX() do not work with LIMIT, we'll need to adjust the dataset we query if a limit is present.
1235
		// With a limit present, we'll look at a dataset consisting of object_ids that meet the constructs of the $where clause.
1236
		// Without a limit, we can use the actual table as a dataset.
1237
		$from = $bucket_size ?
1238
			"( SELECT $distinct_sql $id_field FROM $object_table $where_sql ORDER BY $id_field ASC LIMIT $bucket_size ) as ids" :
1239
			"$object_table $where_sql ORDER BY $id_field ASC";
1240
1241
		return $wpdb->get_row(
1242
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1243
			"SELECT MIN($id_field) as min, MAX($id_field) as max FROM $from"
1244
		);
1245
	}
1246
1247
	/**
1248
	 * Retrieve the checksum histogram for a specific object type.
1249
	 *
1250
	 * @access public
1251
	 *
1252
	 * @todo Refactor to not use interpolated values and properly prepare the SQL query.
1253
	 *
1254
	 * @param string $object_type     Object type.
1255
	 * @param int    $buckets         Number of buckets to split the objects to.
1256
	 * @param int    $start_id        Minimum object ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $start_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1257
	 * @param int    $end_id          Maximum object ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $end_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1258
	 * @param array  $columns         Table columns to calculate the checksum from.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $columns not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1259
	 * @param bool   $strip_non_ascii Whether to strip non-ASCII characters.
1260
	 * @param string $salt            Salt, used for $wpdb->prepare()'s args.
1261
	 * @return array The checksum histogram.
1262
	 */
1263
	public function checksum_histogram( $object_type, $buckets, $start_id = null, $end_id = null, $columns = null, $strip_non_ascii = true, $salt = '' ) {
1264
		global $wpdb;
1265
1266
		$wpdb->queries = array();
1267
1268
		if ( empty( $columns ) ) {
1269
			$columns = $this->get_checksum_columns_for_object_type( $object_type );
1270
		}
1271
1272
		switch ( $object_type ) {
1273
			case 'posts':
1274
				$object_count = $this->post_count( null, $start_id, $end_id );
1275
				$object_table = $wpdb->posts;
1276
				$id_field     = 'ID';
1277
				$where_sql    = Settings::get_blacklisted_post_types_sql();
1278
				break;
1279
			case 'post_meta':
1280
				$object_table = $wpdb->postmeta;
1281
				$where_sql    = Settings::get_whitelisted_post_meta_sql();
1282
				$object_count = $this->meta_count( $object_table, $where_sql, $start_id, $end_id );
1283
				$id_field     = 'meta_id';
1284
				break;
1285
			case 'comments':
1286
				$object_count = $this->comment_count( null, $start_id, $end_id );
1287
				$object_table = $wpdb->comments;
1288
				$id_field     = 'comment_ID';
1289
				$where_sql    = Settings::get_comments_filter_sql();
1290
				break;
1291
			case 'comment_meta':
1292
				$object_table = $wpdb->commentmeta;
1293
				$where_sql    = Settings::get_whitelisted_comment_meta_sql();
1294
				$object_count = $this->meta_count( $object_table, $where_sql, $start_id, $end_id );
1295
				$id_field     = 'meta_id';
1296
				break;
1297
			case 'terms':
1298
				$object_table = $wpdb->terms;
1299
				$object_count = $this->term_count();
1300
				$id_field     = 'term_id';
1301
				$where_sql    = '1=1';
1302
				break;
1303
			case 'term_taxonomy':
1304
				$object_table = $wpdb->term_taxonomy;
1305
				$object_count = $this->term_taxonomy_count();
1306
				$id_field     = 'term_taxonomy_id';
1307
				$where_sql    = '1=1';
1308
				break;
1309
			case 'term_relationships':
1310
				$object_table = $wpdb->term_relationships;
1311
				$object_count = $this->term_relationship_count();
1312
				$id_field     = 'object_id';
1313
				$where_sql    = '1=1';
1314
				break;
1315
			default:
1316
				return false;
1317
		}
1318
1319
		$bucket_size     = (int) ceil( $object_count / $buckets );
1320
		$previous_max_id = 0;
1321
		$histogram       = array();
1322
1323
		// This is used for the min / max query, while $where_sql is used for the checksum query.
1324
		$where = $where_sql;
1325
1326
		if ( $start_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $start_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1327
			$where .= " AND $id_field >= " . (int) $start_id;
1328
		}
1329
1330
		if ( $end_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $end_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1331
			$where .= " AND $id_field <= " . (int) $end_id;
1332
		}
1333
1334
		do {
1335
			$result = $this->get_min_max_object_id(
1336
				$id_field,
1337
				$object_table,
1338
				$where . " AND $id_field > $previous_max_id",
1339
				$bucket_size
1340
			);
1341
1342
			if ( null === $result->min || null === $result->max ) {
1343
				// Nothing to checksum here...
1344
				break;
1345
			}
1346
1347
			// Get the checksum value.
1348
			$value = $this->table_checksum( $object_table, $columns, $id_field, $where_sql, $result->min, $result->max, $strip_non_ascii, $salt );
0 ignored issues
show
Security Bug introduced by
It seems like $columns can also be of type false; however, Automattic\Jetpack\Sync\...store::table_checksum() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
1349
1350
			if ( is_wp_error( $value ) ) {
1351
				return $value;
1352
			}
1353
1354
			if ( null === $result->min || null === $result->max ) {
1355
				break;
1356
			} elseif ( $result->min === $result->max ) {
1357
				$histogram[ $result->min ] = $value;
1358
			} else {
1359
				$histogram[ "{$result->min}-{$result->max}" ] = $value;
1360
			}
1361
1362
			$previous_max_id = $result->max;
1363
		} while ( true );
1364
1365
		return $histogram;
1366
	}
1367
1368
	/**
1369
	 * Retrieve the checksum for a specific database table.
1370
	 *
1371
	 * @access private
1372
	 *
1373
	 * @todo Refactor to properly prepare the SQL query.
1374
	 *
1375
	 * @param string $table           Table name.
1376
	 * @param array  $columns         Table columns to calculate the checksum from.
1377
	 * @param int    $id_column       Name of the unique ID column.
1378
	 * @param string $where_sql       Additional WHERE clause SQL.
1379
	 * @param int    $min_id          Minimum object ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $min_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1380
	 * @param int    $max_id          Maximum object ID.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $max_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1381
	 * @param bool   $strip_non_ascii Whether to strip non-ASCII characters.
1382
	 * @param string $salt            Salt, used for $wpdb->prepare()'s args.
1383
	 * @return int|\WP_Error The table histogram, or \WP_Error on failure.
1384
	 */
1385
	private function table_checksum( $table, $columns, $id_column, $where_sql = '1=1', $min_id = null, $max_id = null, $strip_non_ascii = true, $salt = '' ) {
1386
		global $wpdb;
1387
1388
		// Sanitize to just valid MySQL column names.
1389
		$sanitized_columns = preg_grep( '/^[0-9,a-z,A-Z$_]+$/i', $columns );
1390
1391
		if ( $strip_non_ascii ) {
1392
			$columns_sql = implode( ',', array_map( array( $this, 'strip_non_ascii_sql' ), $sanitized_columns ) );
1393
		} else {
1394
			$columns_sql = implode( ',', $sanitized_columns );
1395
		}
1396
1397
		if ( null !== $min_id && null !== $max_id ) {
1398
			if ( $min_id === $max_id ) {
1399
				$min_id     = (int) $min_id;
1400
				$where_sql .= " AND $id_column = $min_id LIMIT 1";
1401
			} else {
1402
				$min_id     = (int) $min_id;
1403
				$max_id     = (int) $max_id;
1404
				$size       = $max_id - $min_id;
1405
				$where_sql .= " AND $id_column >= $min_id AND $id_column <= $max_id LIMIT $size";
1406
			}
1407
		} else {
1408
			if ( null !== $min_id ) {
1409
				$min_id     = (int) $min_id;
1410
				$where_sql .= " AND $id_column >= $min_id";
1411
			}
1412
1413
			if ( null !== $max_id ) {
1414
				$max_id     = (int) $max_id;
1415
				$where_sql .= " AND $id_column <= $max_id";
1416
			}
1417
		}
1418
1419
		$query = <<<ENDSQL
1420
			SELECT CAST( SUM( CRC32( CONCAT_WS( '#', '%s', {$columns_sql} ) ) ) AS UNSIGNED INT )
1421
			FROM $table
1422
			WHERE $where_sql;
1423
ENDSQL;
1424
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1425
		$result = $wpdb->get_var( $wpdb->prepare( $query, $salt ) );
1426
		if ( $wpdb->last_error ) {
1427
			return new \WP_Error( 'database_error', $wpdb->last_error );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'database_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1428
		}
1429
1430
		return $result;
1431
	}
1432
1433
	/**
1434
	 * Retrieve the type of the checksum.
1435
	 *
1436
	 * @access public
1437
	 *
1438
	 * @return string Type of the checksum.
1439
	 */
1440
	public function get_checksum_type() {
1441
		return 'sum';
1442
	}
1443
1444
	/**
1445
	 * Count the meta values in a table, within a specified range.
1446
	 *
1447
	 * @access private
1448
	 *
1449
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
1450
	 *
1451
	 * @param string $table     Table name.
1452
	 * @param string $where_sql Additional WHERE SQL.
1453
	 * @param int    $min_id    Minimum meta ID.
1454
	 * @param int    $max_id    Maximum meta ID.
1455
	 * @return int Number of meta values.
1456
	 */
1457
	private function meta_count( $table, $where_sql, $min_id, $max_id ) {
1458
		global $wpdb;
1459
1460
		if ( ! empty( $min_id ) ) {
1461
			$where_sql .= ' AND meta_id >= ' . (int) $min_id;
1462
		}
1463
1464
		if ( ! empty( $max_id ) ) {
1465
			$where_sql .= ' AND meta_id <= ' . (int) $max_id;
1466
		}
1467
1468
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1469
		return $wpdb->get_var( "SELECT COUNT(*) FROM $table WHERE $where_sql" );
1470
	}
1471
1472
	/**
1473
	 * Wraps a column name in SQL which strips non-ASCII chars.
1474
	 * This helps normalize data to avoid checksum differences caused by
1475
	 * badly encoded data in the DB.
1476
	 *
1477
	 * @param string $column_name Name of the column.
1478
	 * @return string Column name, without the non-ASCII chars.
1479
	 */
1480
	public function strip_non_ascii_sql( $column_name ) {
1481
		return "REPLACE( CONVERT( $column_name USING ascii ), '?', '' )";
1482
	}
1483
1484
	/**
1485
	 * Used in methods that are not implemented and shouldn't be invoked.
1486
	 *
1487
	 * @access private
1488
	 * @throws \Exception If this method is invoked.
1489
	 */
1490
	private function invalid_call() {
1491
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
1492
		$backtrace = debug_backtrace();
1493
		$caller    = $backtrace[1]['function'];
1494
		throw new \Exception( "This function $caller is not supported on the WP Replicastore" );
1495
	}
1496
}
1497