Completed
Push — try/jetpack-stories-block-mobi... ( 5d409e...2fea66 )
by
unknown
116:16 queued 106:28
created

Replicastore::spam_comment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
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 ( (string) $status ) {
332
			case 'approve':
333
			case '1':
334
				return '1';
335
			case 'hold':
336
			case '0':
337
				return '0';
338
			case 'spam':
339
				return 'spam';
340
			case 'trash':
341
				return 'trash';
342
			case 'post-trashed':
343
				return 'post-trashed';
344
			case 'any':
345
			case 'all':
346
			default:
347
				return false;
348
		}
349
	}
350
351
	/**
352
	 * Retrieve the comments with a particular comment status.
353
	 *
354
	 * @access public
355
	 *
356
	 * @todo Implement range and actually use max_id/min_id arguments.
357
	 *
358
	 * @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...
359
	 * @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...
360
	 * @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...
361
	 * @return array Array of comments.
362
	 */
363
	public function get_comments( $status = null, $min_id = null, $max_id = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
364
		$args = array(
365
			'orderby' => 'ID',
366
			'status'  => 'all',
367
		);
368
369
		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...
370
			$args['status'] = $status;
371
		}
372
373
		return get_comments( $args );
374
	}
375
376
	/**
377
	 * Retrieve a comment object by the comment ID.
378
	 *
379
	 * @access public
380
	 *
381
	 * @param int $id Comment ID.
382
	 * @return \WP_Comment Comment object.
383
	 */
384
	public function get_comment( $id ) {
385
		return \WP_Comment::get_instance( $id );
386
	}
387
388
	/**
389
	 * Update or insert a comment.
390
	 *
391
	 * @access public
392
	 *
393
	 * @param \WP_Comment $comment Comment object.
394
	 */
395
	public function upsert_comment( $comment ) {
396
		global $wpdb;
397
398
		$comment = $comment->to_array();
399
400
		// Filter by fields on comment table.
401
		$comment_fields_whitelist = array(
402
			'comment_ID',
403
			'comment_post_ID',
404
			'comment_author',
405
			'comment_author_email',
406
			'comment_author_url',
407
			'comment_author_IP',
408
			'comment_date',
409
			'comment_date_gmt',
410
			'comment_content',
411
			'comment_karma',
412
			'comment_approved',
413
			'comment_agent',
414
			'comment_type',
415
			'comment_parent',
416
			'user_id',
417
		);
418
419
		foreach ( $comment as $key => $value ) {
420
			if ( ! in_array( $key, $comment_fields_whitelist, true ) ) {
421
				unset( $comment[ $key ] );
422
			}
423
		}
424
425
		$exists = $wpdb->get_var(
426
			$wpdb->prepare(
427
				"SELECT EXISTS( SELECT 1 FROM $wpdb->comments WHERE comment_ID = %d )",
428
				$comment['comment_ID']
429
			)
430
		);
431
432
		if ( $exists ) {
433
			$wpdb->update( $wpdb->comments, $comment, array( 'comment_ID' => $comment['comment_ID'] ) );
434
		} else {
435
			$wpdb->insert( $wpdb->comments, $comment );
436
		}
437
		// Remove comment from cache.
438
		clean_comment_cache( $comment['comment_ID'] );
439
440
		wp_update_comment_count( $comment['comment_post_ID'] );
441
	}
442
443
	/**
444
	 * Trash a comment by the comment ID.
445
	 *
446
	 * @access public
447
	 *
448
	 * @param int $comment_id Comment ID.
449
	 */
450
	public function trash_comment( $comment_id ) {
451
		wp_delete_comment( $comment_id );
452
	}
453
454
	/**
455
	 * Delete a comment by the comment ID.
456
	 *
457
	 * @access public
458
	 *
459
	 * @param int $comment_id Comment ID.
460
	 */
461
	public function delete_comment( $comment_id ) {
462
		wp_delete_comment( $comment_id, true );
463
	}
464
465
	/**
466
	 * Mark a comment by the comment ID as spam.
467
	 *
468
	 * @access public
469
	 *
470
	 * @param int $comment_id Comment ID.
471
	 */
472
	public function spam_comment( $comment_id ) {
473
		wp_spam_comment( $comment_id );
474
	}
475
476
	/**
477
	 * Trash the comments of a post.
478
	 *
479
	 * @access public
480
	 *
481
	 * @param int   $post_id  Post ID.
482
	 * @param array $statuses Post statuses. Not used in this implementation.
483
	 */
484
	public function trashed_post_comments( $post_id, $statuses ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
485
		wp_trash_post_comments( $post_id );
486
	}
487
488
	/**
489
	 * Untrash the comments of a post.
490
	 *
491
	 * @access public
492
	 *
493
	 * @param int $post_id Post ID.
494
	 */
495
	public function untrashed_post_comments( $post_id ) {
496
		wp_untrash_post_comments( $post_id );
497
	}
498
499
	/**
500
	 * Retrieve the checksum for comments within a range.
501
	 *
502
	 * @access public
503
	 *
504
	 * @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...
505
	 * @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...
506
	 * @return int The checksum.
507
	 */
508
	public function comments_checksum( $min_id = null, $max_id = null ) {
509
		global $wpdb;
510
		return $this->table_checksum( $wpdb->comments, Defaults::$default_comment_checksum_columns, 'comment_ID', Settings::get_comments_filter_sql(), $min_id, $max_id );
511
	}
512
513
	/**
514
	 * Retrieve the checksum for comment meta within a range.
515
	 *
516
	 * @access public
517
	 *
518
	 * @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...
519
	 * @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...
520
	 * @return int The checksum.
521
	 */
522
	public function comment_meta_checksum( $min_id = null, $max_id = null ) {
523
		global $wpdb;
524
		return $this->table_checksum( $wpdb->commentmeta, Defaults::$default_comment_meta_checksum_columns, 'meta_id', Settings::get_whitelisted_comment_meta_sql(), $min_id, $max_id );
525
	}
526
527
	/**
528
	 * Retrieve the checksum for all options.
529
	 *
530
	 * @access public
531
	 *
532
	 * @return int The checksum.
533
	 */
534
	public function options_checksum() {
535
		global $wpdb;
536
		$options_whitelist = "'" . implode( "', '", Defaults::$default_options_whitelist ) . "'";
537
		$where_sql         = "option_name IN ( $options_whitelist )";
538
539
		return $this->table_checksum( $wpdb->options, Defaults::$default_option_checksum_columns, null, $where_sql, null, null );
540
	}
541
542
	/**
543
	 * Update the value of an option.
544
	 *
545
	 * @access public
546
	 *
547
	 * @param string $option Option name.
548
	 * @param mixed  $value  Option value.
549
	 * @return bool False if value was not updated and true if value was updated.
550
	 */
551
	public function update_option( $option, $value ) {
552
		return update_option( $option, $value );
553
	}
554
555
	/**
556
	 * Retrieve an option value based on an option name.
557
	 *
558
	 * @access public
559
	 *
560
	 * @param string $option  Name of option to retrieve.
561
	 * @param mixed  $default Optional. Default value to return if the option does not exist.
562
	 * @return mixed Value set for the option.
563
	 */
564
	public function get_option( $option, $default = false ) {
565
		return get_option( $option, $default );
566
	}
567
568
	/**
569
	 * Remove an option by name.
570
	 *
571
	 * @access public
572
	 *
573
	 * @param string $option Name of option to remove.
574
	 * @return bool True, if option is successfully deleted. False on failure.
575
	 */
576
	public function delete_option( $option ) {
577
		return delete_option( $option );
578
	}
579
580
	/**
581
	 * Change the info of the current theme.
582
	 *
583
	 * @access public
584
	 *
585
	 * @param array $theme_info Theme info array.
586
	 */
587
	public function set_theme_info( $theme_info ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
588
		// Noop.
589
	}
590
591
	/**
592
	 * Whether the current theme supports a certain feature.
593
	 *
594
	 * @access public
595
	 *
596
	 * @param string $feature Name of the feature.
597
	 */
598
	public function current_theme_supports( $feature ) {
599
		return current_theme_supports( $feature );
600
	}
601
602
	/**
603
	 * Retrieve metadata for the specified object.
604
	 *
605
	 * @access public
606
	 *
607
	 * @param string $type       Meta type.
608
	 * @param int    $object_id  ID of the object.
609
	 * @param string $meta_key   Meta key.
610
	 * @param bool   $single     If true, return only the first value of the specified meta_key.
611
	 *
612
	 * @return mixed Single metadata value, or array of values.
613
	 */
614
	public function get_metadata( $type, $object_id, $meta_key = '', $single = false ) {
615
		return get_metadata( $type, $object_id, $meta_key, $single );
616
	}
617
618
	/**
619
	 * Stores remote meta key/values alongside an ID mapping key.
620
	 *
621
	 * @access public
622
	 *
623
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
624
	 *
625
	 * @param string $type       Meta type.
626
	 * @param int    $object_id  ID of the object.
627
	 * @param string $meta_key   Meta key.
628
	 * @param mixed  $meta_value Meta value.
629
	 * @param int    $meta_id    ID of the meta.
630
	 *
631
	 * @return bool False if meta table does not exist, true otherwise.
632
	 */
633
	public function upsert_metadata( $type, $object_id, $meta_key, $meta_value, $meta_id ) {
634
		$table = _get_meta_table( $type );
635
		if ( ! $table ) {
636
			return false;
637
		}
638
639
		global $wpdb;
640
641
		$exists = $wpdb->get_var(
642
			$wpdb->prepare(
643
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
644
				"SELECT EXISTS( SELECT 1 FROM $table WHERE meta_id = %d )",
645
				$meta_id
646
			)
647
		);
648
649
		if ( $exists ) {
650
			$wpdb->update(
651
				$table,
652
				array(
653
					'meta_key'   => $meta_key,
654
					'meta_value' => maybe_serialize( $meta_value ),
655
				),
656
				array( 'meta_id' => $meta_id )
657
			);
658
		} else {
659
			$object_id_field = $type . '_id';
660
			$wpdb->insert(
661
				$table,
662
				array(
663
					'meta_id'        => $meta_id,
664
					$object_id_field => $object_id,
665
					'meta_key'       => $meta_key,
666
					'meta_value'     => maybe_serialize( $meta_value ),
667
				)
668
			);
669
		}
670
671
		wp_cache_delete( $object_id, $type . '_meta' );
672
673
		return true;
674
	}
675
676
	/**
677
	 * Delete metadata for the specified object.
678
	 *
679
	 * @access public
680
	 *
681
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
682
	 *
683
	 * @param string $type      Meta type.
684
	 * @param int    $object_id ID of the object.
685
	 * @param array  $meta_ids  IDs of the meta objects to delete.
686
	 */
687
	public function delete_metadata( $type, $object_id, $meta_ids ) {
688
		global $wpdb;
689
690
		$table = _get_meta_table( $type );
691
		if ( ! $table ) {
692
			return false;
693
		}
694
695
		foreach ( $meta_ids as $meta_id ) {
696
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
697
			$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE meta_id = %d", $meta_id ) );
698
		}
699
700
		// If we don't have an object ID what do we do - invalidate ALL meta?
701
		if ( $object_id ) {
702
			wp_cache_delete( $object_id, $type . '_meta' );
703
		}
704
	}
705
706
	/**
707
	 * Delete metadata with a certain key for the specified objects.
708
	 *
709
	 * @access public
710
	 *
711
	 * @todo Test this out to make sure it works as expected.
712
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
713
	 *
714
	 * @param string $type       Meta type.
715
	 * @param array  $object_ids IDs of the objects.
716
	 * @param string $meta_key   Meta key.
717
	 */
718
	public function delete_batch_metadata( $type, $object_ids, $meta_key ) {
719
		global $wpdb;
720
721
		$table = _get_meta_table( $type );
722
		if ( ! $table ) {
723
			return false;
724
		}
725
		$column = sanitize_key( $type . '_id' );
726
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
727
		$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE $column IN (%s) && meta_key = %s", implode( ',', $object_ids ), $meta_key ) );
728
729
		// If we don't have an object ID what do we do - invalidate ALL meta?
730
		foreach ( $object_ids as $object_id ) {
731
			wp_cache_delete( $object_id, $type . '_meta' );
732
		}
733
	}
734
735
	/**
736
	 * Retrieve value of a constant based on the constant name.
737
	 *
738
	 * We explicitly return null instead of false if the constant doesn't exist.
739
	 *
740
	 * @access public
741
	 *
742
	 * @param string $constant Name of constant to retrieve.
743
	 * @return mixed Value set for the constant.
744
	 */
745
	public function get_constant( $constant ) {
746
		$value = get_option( 'jetpack_constant_' . $constant );
747
748
		if ( $value ) {
749
			return $value;
750
		}
751
752
		return null;
753
	}
754
755
	/**
756
	 * Set the value of a constant.
757
	 *
758
	 * @access public
759
	 *
760
	 * @param string $constant Name of constant to retrieve.
761
	 * @param mixed  $value    Value set for the constant.
762
	 */
763
	public function set_constant( $constant, $value ) {
764
		update_option( 'jetpack_constant_' . $constant, $value );
765
	}
766
767
	/**
768
	 * Retrieve the number of the available updates of a certain type.
769
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
770
	 *
771
	 * @access public
772
	 *
773
	 * @param string $type Type of updates to retrieve.
774
	 * @return int|null Number of updates available, `null` if type is invalid or missing.
775
	 */
776
	public function get_updates( $type ) {
777
		$all_updates = get_option( 'jetpack_updates', array() );
778
779
		if ( isset( $all_updates[ $type ] ) ) {
780
			return $all_updates[ $type ];
781
		} else {
782
			return null;
783
		}
784
	}
785
786
	/**
787
	 * Set the available updates of a certain type.
788
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
789
	 *
790
	 * @access public
791
	 *
792
	 * @param string $type    Type of updates to set.
793
	 * @param int    $updates Total number of updates.
794
	 */
795
	public function set_updates( $type, $updates ) {
796
		$all_updates          = get_option( 'jetpack_updates', array() );
797
		$all_updates[ $type ] = $updates;
798
		update_option( 'jetpack_updates', $all_updates );
799
	}
800
801
	/**
802
	 * Retrieve a callable value based on its name.
803
	 *
804
	 * @access public
805
	 *
806
	 * @param string $name Name of the callable to retrieve.
807
	 * @return mixed Value of the callable.
808
	 */
809
	public function get_callable( $name ) {
810
		$value = get_option( 'jetpack_' . $name );
811
812
		if ( $value ) {
813
			return $value;
814
		}
815
816
		return null;
817
	}
818
819
	/**
820
	 * Update the value of a callable.
821
	 *
822
	 * @access public
823
	 *
824
	 * @param string $name  Callable name.
825
	 * @param mixed  $value Callable value.
826
	 */
827
	public function set_callable( $name, $value ) {
828
		update_option( 'jetpack_' . $name, $value );
829
	}
830
831
	/**
832
	 * Retrieve a network option value based on a network option name.
833
	 *
834
	 * @access public
835
	 *
836
	 * @param string $option Name of network option to retrieve.
837
	 * @return mixed Value set for the network option.
838
	 */
839
	public function get_site_option( $option ) {
840
		return get_option( 'jetpack_network_' . $option );
841
	}
842
843
	/**
844
	 * Update the value of a network option.
845
	 *
846
	 * @access public
847
	 *
848
	 * @param string $option Network option name.
849
	 * @param mixed  $value  Network option value.
850
	 * @return bool False if value was not updated and true if value was updated.
851
	 */
852
	public function update_site_option( $option, $value ) {
853
		return update_option( 'jetpack_network_' . $option, $value );
854
	}
855
856
	/**
857
	 * Remove a network option by name.
858
	 *
859
	 * @access public
860
	 *
861
	 * @param string $option Name of option to remove.
862
	 * @return bool True, if option is successfully deleted. False on failure.
863
	 */
864
	public function delete_site_option( $option ) {
865
		return delete_option( 'jetpack_network_' . $option );
866
	}
867
868
	/**
869
	 * Retrieve the terms from a particular taxonomy.
870
	 *
871
	 * @access public
872
	 *
873
	 * @param string $taxonomy Taxonomy slug.
874
	 * @return array|\WP_Error Array of terms or WP_Error object on failure.
875
	 */
876
	public function get_terms( $taxonomy ) {
877
		$t = $this->ensure_taxonomy( $taxonomy );
878
		if ( ! $t || is_wp_error( $t ) ) {
879
			return $t;
880
		}
881
		return get_terms( $taxonomy );
882
	}
883
884
	/**
885
	 * Retrieve a particular term.
886
	 *
887
	 * @access public
888
	 *
889
	 * @param string $taxonomy   Taxonomy slug.
890
	 * @param int    $term_id    ID of the term.
891
	 * @param bool   $is_term_id Whether this is a `term_id` or a `term_taxonomy_id`.
892
	 * @return \WP_Term|\WP_Error Term object on success, \WP_Error object on failure.
893
	 */
894
	public function get_term( $taxonomy, $term_id, $is_term_id = true ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
895
		$t = $this->ensure_taxonomy( $taxonomy );
896
		if ( ! $t || is_wp_error( $t ) ) {
897
			return $t;
898
		}
899
900
		return get_term( $term_id, $taxonomy );
901
	}
902
903
	/**
904
	 * Verify a taxonomy is legitimate and register it if necessary.
905
	 *
906
	 * @access private
907
	 *
908
	 * @param string $taxonomy Taxonomy slug.
909
	 * @return bool|void|\WP_Error True if already exists; void if it was registered; \WP_Error on error.
910
	 */
911
	private function ensure_taxonomy( $taxonomy ) {
912
		if ( ! taxonomy_exists( $taxonomy ) ) {
913
			// Try re-registering synced taxonomies.
914
			$taxonomies = $this->get_callable( 'taxonomies' );
915
			if ( ! isset( $taxonomies[ $taxonomy ] ) ) {
916
				// Doesn't exist, or somehow hasn't been synced.
917
				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...
918
			}
919
			$t = $taxonomies[ $taxonomy ];
920
921
			return register_taxonomy(
922
				$taxonomy,
923
				$t->object_type,
924
				(array) $t
925
			);
926
		}
927
928
		return true;
929
	}
930
931
	/**
932
	 * Retrieve all terms from a taxonomy that are related to an object with a particular ID.
933
	 *
934
	 * @access public
935
	 *
936
	 * @param int    $object_id Object ID.
937
	 * @param string $taxonomy  Taxonomy slug.
938
	 * @return array|bool|\WP_Error Array of terms on success, `false` if no terms or post doesn't exist, \WP_Error on failure.
939
	 */
940
	public function get_the_terms( $object_id, $taxonomy ) {
941
		return get_the_terms( $object_id, $taxonomy );
942
	}
943
944
	/**
945
	 * Insert or update a term.
946
	 *
947
	 * @access public
948
	 *
949
	 * @param \WP_Term $term_object Term object.
950
	 * @return array|bool|\WP_Error Array of term_id and term_taxonomy_id if updated, true if inserted, \WP_Error on failure.
951
	 */
952
	public function update_term( $term_object ) {
953
		$taxonomy = $term_object->taxonomy;
954
		global $wpdb;
955
		$exists = $wpdb->get_var(
956
			$wpdb->prepare(
957
				"SELECT EXISTS( SELECT 1 FROM $wpdb->terms WHERE term_id = %d )",
958
				$term_object->term_id
959
			)
960
		);
961
		if ( ! $exists ) {
962
			$term_object   = sanitize_term( clone $term_object, $taxonomy, 'db' );
963
			$term          = array(
964
				'term_id'    => $term_object->term_id,
965
				'name'       => $term_object->name,
966
				'slug'       => $term_object->slug,
967
				'term_group' => $term_object->term_group,
968
			);
969
			$term_taxonomy = array(
970
				'term_taxonomy_id' => $term_object->term_taxonomy_id,
971
				'term_id'          => $term_object->term_id,
972
				'taxonomy'         => $term_object->taxonomy,
973
				'description'      => $term_object->description,
974
				'parent'           => (int) $term_object->parent,
975
				'count'            => (int) $term_object->count,
976
			);
977
			$wpdb->insert( $wpdb->terms, $term );
978
			$wpdb->insert( $wpdb->term_taxonomy, $term_taxonomy );
979
980
			return true;
981
		}
982
983
		return wp_update_term( $term_object->term_id, $taxonomy, (array) $term_object );
984
	}
985
986
	/**
987
	 * Delete a term by the term ID and its corresponding taxonomy.
988
	 *
989
	 * @access public
990
	 *
991
	 * @param int    $term_id  Term ID.
992
	 * @param string $taxonomy Taxonomy slug.
993
	 * @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.
994
	 */
995
	public function delete_term( $term_id, $taxonomy ) {
996
		$this->ensure_taxonomy( $taxonomy );
997
		return wp_delete_term( $term_id, $taxonomy );
998
	}
999
1000
	/**
1001
	 * Add/update terms of a particular taxonomy of an object with the specified ID.
1002
	 *
1003
	 * @access public
1004
	 *
1005
	 * @param int              $object_id The object to relate to.
1006
	 * @param string           $taxonomy  The context in which to relate the term to the object.
1007
	 * @param string|int|array $terms     A single term slug, single term id, or array of either term slugs or ids.
1008
	 * @param bool             $append    Optional. If false will delete difference of terms. Default false.
1009
	 */
1010
	public function update_object_terms( $object_id, $taxonomy, $terms, $append ) {
1011
		$this->ensure_taxonomy( $taxonomy );
1012
		wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
1013
	}
1014
1015
	/**
1016
	 * Remove certain term relationships from the specified object.
1017
	 *
1018
	 * @access public
1019
	 *
1020
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
1021
	 *
1022
	 * @param int   $object_id ID of the object.
1023
	 * @param array $tt_ids    Term taxonomy IDs.
1024
	 * @return bool True on success, false on failure.
1025
	 */
1026
	public function delete_object_terms( $object_id, $tt_ids ) {
1027
		global $wpdb;
1028
1029
		if ( is_array( $tt_ids ) && ! empty( $tt_ids ) ) {
1030
			// Escape.
1031
			$tt_ids_sanitized = array_map( 'intval', $tt_ids );
1032
1033
			$taxonomies = array();
1034
			foreach ( $tt_ids_sanitized as $tt_id ) {
1035
				$term                            = get_term_by( 'term_taxonomy_id', $tt_id );
1036
				$taxonomies[ $term->taxonomy ][] = $tt_id;
1037
			}
1038
			$in_tt_ids = implode( ', ', $tt_ids_sanitized );
1039
1040
			/**
1041
			 * Fires immediately before an object-term relationship is deleted.
1042
			 *
1043
			 * @since 2.9.0
1044
			 *
1045
			 * @param int   $object_id Object ID.
1046
			 * @param array $tt_ids    An array of term taxonomy IDs.
1047
			 */
1048
			do_action( 'delete_term_relationships', $object_id, $tt_ids_sanitized );
1049
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1050
			$deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
1051
			foreach ( $taxonomies as $taxonomy => $taxonomy_tt_ids ) {
1052
				$this->ensure_taxonomy( $taxonomy );
1053
				wp_cache_delete( $object_id, $taxonomy . '_relationships' );
1054
				/**
1055
				 * Fires immediately after an object-term relationship is deleted.
1056
				 *
1057
				 * @since 2.9.0
1058
				 *
1059
				 * @param int   $object_id Object ID.
1060
				 * @param array $tt_ids    An array of term taxonomy IDs.
1061
				 */
1062
				do_action( 'deleted_term_relationships', $object_id, $taxonomy_tt_ids );
1063
				wp_update_term_count( $taxonomy_tt_ids, $taxonomy );
1064
			}
1065
1066
			return (bool) $deleted;
1067
		}
1068
1069
		return false;
1070
	}
1071
1072
	/**
1073
	 * Retrieve the number of users.
1074
	 * Not supported in this replicastore.
1075
	 *
1076
	 * @access public
1077
	 */
1078
	public function user_count() {
1079
		// Noop.
1080
	}
1081
1082
	/**
1083
	 * Retrieve a user object by the user ID.
1084
	 *
1085
	 * @access public
1086
	 *
1087
	 * @param int $user_id User ID.
1088
	 * @return \WP_User User object.
1089
	 */
1090
	public function get_user( $user_id ) {
1091
		return \WP_User::get_instance( $user_id );
1092
	}
1093
1094
	/**
1095
	 * Insert or update a user.
1096
	 * Not supported in this replicastore.
1097
	 *
1098
	 * @access public
1099
	 * @throws \Exception If this method is invoked.
1100
	 *
1101
	 * @param \WP_User $user User object.
1102
	 */
1103
	public function upsert_user( $user ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1104
		$this->invalid_call();
1105
	}
1106
1107
	/**
1108
	 * Delete a user.
1109
	 * Not supported in this replicastore.
1110
	 *
1111
	 * @access public
1112
	 * @throws \Exception If this method is invoked.
1113
	 *
1114
	 * @param int $user_id User ID.
1115
	 */
1116
	public function delete_user( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1117
		$this->invalid_call();
1118
	}
1119
1120
	/**
1121
	 * Update/insert user locale.
1122
	 * Not supported in this replicastore.
1123
	 *
1124
	 * @access public
1125
	 * @throws \Exception If this method is invoked.
1126
	 *
1127
	 * @param int    $user_id User ID.
1128
	 * @param string $local   The user locale.
1129
	 */
1130
	public function upsert_user_locale( $user_id, $local ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1131
		$this->invalid_call();
1132
	}
1133
1134
	/**
1135
	 * Delete user locale.
1136
	 * Not supported in this replicastore.
1137
	 *
1138
	 * @access public
1139
	 * @throws \Exception If this method is invoked.
1140
	 *
1141
	 * @param int $user_id User ID.
1142
	 */
1143
	public function delete_user_locale( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1144
		$this->invalid_call();
1145
	}
1146
1147
	/**
1148
	 * Retrieve the user locale.
1149
	 *
1150
	 * @access public
1151
	 *
1152
	 * @param int $user_id User ID.
1153
	 * @return string The user locale.
1154
	 */
1155
	public function get_user_locale( $user_id ) {
1156
		return get_user_locale( $user_id );
1157
	}
1158
1159
	/**
1160
	 * Retrieve the allowed mime types for the user.
1161
	 * Not supported in this replicastore.
1162
	 *
1163
	 * @access public
1164
	 *
1165
	 * @param int $user_id User ID.
1166
	 */
1167
	public function get_allowed_mime_types( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1168
		// Noop.
1169
	}
1170
1171
	/**
1172
	 * Retrieve all the checksums we are interested in.
1173
	 * Currently that is posts, comments, post meta and comment meta.
1174
	 *
1175
	 * @access public
1176
	 *
1177
	 * @return array Checksums.
1178
	 */
1179
	public function checksum_all() {
1180
		$post_meta_checksum    = $this->checksum_histogram( 'post_meta', 1 );
1181
		$comment_meta_checksum = $this->checksum_histogram( 'comment_meta', 1 );
1182
1183
		return array(
1184
			'posts'        => $this->posts_checksum(),
1185
			'comments'     => $this->comments_checksum(),
1186
			'post_meta'    => reset( $post_meta_checksum ),
1187
			'comment_meta' => reset( $comment_meta_checksum ),
1188
		);
1189
	}
1190
1191
	/**
1192
	 * Retrieve the columns that are needed to calculate a checksum for an object type.
1193
	 *
1194
	 * @access public
1195
	 *
1196
	 * @todo Refactor to not use interpolated values and prepare the SQL query.
1197
	 *
1198
	 * @param string $object_type Object type.
1199
	 * @return array|bool Columns, or false if invalid object type is specified.
1200
	 */
1201
	public function get_checksum_columns_for_object_type( $object_type ) {
1202
		switch ( $object_type ) {
1203
			case 'posts':
1204
				return Defaults::$default_post_checksum_columns;
1205
			case 'post_meta':
1206
				return Defaults::$default_post_meta_checksum_columns;
1207
			case 'comments':
1208
				return Defaults::$default_comment_checksum_columns;
1209
			case 'comment_meta':
1210
				return Defaults::$default_post_meta_checksum_columns;
1211
			case 'terms':
1212
				return Defaults::$default_term_checksum_columns;
1213
			case 'term_taxonomy':
1214
				return Defaults::$default_term_taxonomy_checksum_columns;
1215
			case 'term_relationships':
1216
				return Defaults::$default_term_relationships_checksum_columns;
1217
			default:
1218
				return false;
1219
		}
1220
	}
1221
1222
	/**
1223
	 * Grabs the minimum and maximum object ids for the given parameters.
1224
	 *
1225
	 * @access public
1226
	 *
1227
	 * @param string $id_field     The id column in the table to query.
1228
	 * @param string $object_table The table to query.
1229
	 * @param string $where        A sql where clause without 'WHERE'.
1230
	 * @param int    $bucket_size  The maximum amount of objects to include in the query.
1231
	 *                             For `term_relationships` table, the bucket size will refer to the amount
1232
	 *                             of distinct object ids. This will likely include more database rows than
1233
	 *                             the bucket size implies.
1234
	 *
1235
	 * @return object An object with min_id and max_id properties.
1236
	 */
1237
	public function get_min_max_object_id( $id_field, $object_table, $where, $bucket_size ) {
1238
		global $wpdb;
1239
1240
		// The term relationship table's unique key is a combination of 2 columns. `DISTINCT` helps us get a more acurate query.
1241
		$distinct_sql = ( $wpdb->term_relationships === $object_table ) ? 'DISTINCT' : '';
1242
		$where_sql    = $where ? "WHERE $where" : '';
1243
1244
		// Since MIN() and MAX() do not work with LIMIT, we'll need to adjust the dataset we query if a limit is present.
1245
		// With a limit present, we'll look at a dataset consisting of object_ids that meet the constructs of the $where clause.
1246
		// Without a limit, we can use the actual table as a dataset.
1247
		$from = $bucket_size ?
1248
			"( SELECT $distinct_sql $id_field FROM $object_table $where_sql ORDER BY $id_field ASC LIMIT $bucket_size ) as ids" :
1249
			"$object_table $where_sql ORDER BY $id_field ASC";
1250
1251
		return $wpdb->get_row(
1252
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1253
			"SELECT MIN($id_field) as min, MAX($id_field) as max FROM $from"
1254
		);
1255
	}
1256
1257
	/**
1258
	 * Retrieve the checksum histogram for a specific object type.
1259
	 *
1260
	 * @access public
1261
	 *
1262
	 * @todo Refactor to not use interpolated values and properly prepare the SQL query.
1263
	 *
1264
	 * @param string $object_type     Object type.
1265
	 * @param int    $buckets         Number of buckets to split the objects to.
1266
	 * @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...
1267
	 * @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...
1268
	 * @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...
1269
	 * @param bool   $strip_non_ascii Whether to strip non-ASCII characters.
1270
	 * @param string $salt            Salt, used for $wpdb->prepare()'s args.
1271
	 * @return array The checksum histogram.
1272
	 */
1273
	public function checksum_histogram( $object_type, $buckets, $start_id = null, $end_id = null, $columns = null, $strip_non_ascii = true, $salt = '' ) {
1274
		global $wpdb;
1275
1276
		$wpdb->queries = array();
1277
1278
		if ( empty( $columns ) ) {
1279
			$columns = $this->get_checksum_columns_for_object_type( $object_type );
1280
		}
1281
1282
		switch ( $object_type ) {
1283
			case 'posts':
1284
				$object_count = $this->post_count( null, $start_id, $end_id );
1285
				$object_table = $wpdb->posts;
1286
				$id_field     = 'ID';
1287
				$where_sql    = Settings::get_blacklisted_post_types_sql();
1288
				break;
1289
			case 'post_meta':
1290
				$object_table = $wpdb->postmeta;
1291
				$where_sql    = Settings::get_whitelisted_post_meta_sql();
1292
				$object_count = $this->meta_count( $object_table, $where_sql, $start_id, $end_id );
1293
				$id_field     = 'meta_id';
1294
				break;
1295
			case 'comments':
1296
				$object_count = $this->comment_count( null, $start_id, $end_id );
1297
				$object_table = $wpdb->comments;
1298
				$id_field     = 'comment_ID';
1299
				$where_sql    = Settings::get_comments_filter_sql();
1300
				break;
1301
			case 'comment_meta':
1302
				$object_table = $wpdb->commentmeta;
1303
				$where_sql    = Settings::get_whitelisted_comment_meta_sql();
1304
				$object_count = $this->meta_count( $object_table, $where_sql, $start_id, $end_id );
1305
				$id_field     = 'meta_id';
1306
				break;
1307
			case 'terms':
1308
				$object_table = $wpdb->terms;
1309
				$object_count = $this->term_count();
1310
				$id_field     = 'term_id';
1311
				$where_sql    = '1=1';
1312
				break;
1313
			case 'term_taxonomy':
1314
				$object_table = $wpdb->term_taxonomy;
1315
				$object_count = $this->term_taxonomy_count();
1316
				$id_field     = 'term_taxonomy_id';
1317
				$where_sql    = '1=1';
1318
				break;
1319
			case 'term_relationships':
1320
				$object_table = $wpdb->term_relationships;
1321
				$object_count = $this->term_relationship_count();
1322
				$id_field     = 'object_id';
1323
				$where_sql    = '1=1';
1324
				break;
1325
			default:
1326
				return false;
1327
		}
1328
1329
		$bucket_size     = (int) ceil( $object_count / $buckets );
1330
		$previous_max_id = 0;
1331
		$histogram       = array();
1332
1333
		// This is used for the min / max query, while $where_sql is used for the checksum query.
1334
		$where = $where_sql;
1335
1336
		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...
1337
			$where .= " AND $id_field >= " . (int) $start_id;
1338
		}
1339
1340
		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...
1341
			$where .= " AND $id_field <= " . (int) $end_id;
1342
		}
1343
1344
		do {
1345
			$result = $this->get_min_max_object_id(
1346
				$id_field,
1347
				$object_table,
1348
				$where . " AND $id_field > $previous_max_id",
1349
				$bucket_size
1350
			);
1351
1352
			if ( null === $result->min || null === $result->max ) {
1353
				// Nothing to checksum here...
1354
				break;
1355
			}
1356
1357
			// Get the checksum value.
1358
			$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...
1359
1360
			if ( is_wp_error( $value ) ) {
1361
				return $value;
1362
			}
1363
1364
			if ( null === $result->min || null === $result->max ) {
1365
				break;
1366
			} elseif ( $result->min === $result->max ) {
1367
				$histogram[ $result->min ] = $value;
1368
			} else {
1369
				$histogram[ "{$result->min}-{$result->max}" ] = $value;
1370
			}
1371
1372
			$previous_max_id = $result->max;
1373
		} while ( true );
1374
1375
		return $histogram;
1376
	}
1377
1378
	/**
1379
	 * Retrieve the checksum for a specific database table.
1380
	 *
1381
	 * @access private
1382
	 *
1383
	 * @todo Refactor to properly prepare the SQL query.
1384
	 *
1385
	 * @param string $table           Table name.
1386
	 * @param array  $columns         Table columns to calculate the checksum from.
1387
	 * @param int    $id_column       Name of the unique ID column.
1388
	 * @param string $where_sql       Additional WHERE clause SQL.
1389
	 * @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...
1390
	 * @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...
1391
	 * @param bool   $strip_non_ascii Whether to strip non-ASCII characters.
1392
	 * @param string $salt            Salt, used for $wpdb->prepare()'s args.
1393
	 * @return int|\WP_Error The table histogram, or \WP_Error on failure.
1394
	 */
1395
	private function table_checksum( $table, $columns, $id_column, $where_sql = '1=1', $min_id = null, $max_id = null, $strip_non_ascii = true, $salt = '' ) {
1396
		global $wpdb;
1397
1398
		// Sanitize to just valid MySQL column names.
1399
		$sanitized_columns = preg_grep( '/^[0-9,a-z,A-Z$_]+$/i', $columns );
1400
1401
		if ( $strip_non_ascii ) {
1402
			$columns_sql = implode( ',', array_map( array( $this, 'strip_non_ascii_sql' ), $sanitized_columns ) );
1403
		} else {
1404
			$columns_sql = implode( ',', $sanitized_columns );
1405
		}
1406
1407
		if ( null !== $min_id && null !== $max_id ) {
1408
			if ( $min_id === $max_id ) {
1409
				$min_id     = (int) $min_id;
1410
				$where_sql .= " AND $id_column = $min_id LIMIT 1";
1411
			} else {
1412
				$min_id     = (int) $min_id;
1413
				$max_id     = (int) $max_id;
1414
				$size       = $max_id - $min_id;
1415
				$where_sql .= " AND $id_column >= $min_id AND $id_column <= $max_id LIMIT $size";
1416
			}
1417
		} else {
1418
			if ( null !== $min_id ) {
1419
				$min_id     = (int) $min_id;
1420
				$where_sql .= " AND $id_column >= $min_id";
1421
			}
1422
1423
			if ( null !== $max_id ) {
1424
				$max_id     = (int) $max_id;
1425
				$where_sql .= " AND $id_column <= $max_id";
1426
			}
1427
		}
1428
1429
		$query = <<<ENDSQL
1430
			SELECT CAST( SUM( CRC32( CONCAT_WS( '#', '%s', {$columns_sql} ) ) ) AS UNSIGNED INT )
1431
			FROM $table
1432
			WHERE $where_sql;
1433
ENDSQL;
1434
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1435
		$result = $wpdb->get_var( $wpdb->prepare( $query, $salt ) );
1436
		if ( $wpdb->last_error ) {
1437
			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...
1438
		}
1439
1440
		return $result;
1441
	}
1442
1443
	/**
1444
	 * Retrieve the type of the checksum.
1445
	 *
1446
	 * @access public
1447
	 *
1448
	 * @return string Type of the checksum.
1449
	 */
1450
	public function get_checksum_type() {
1451
		return 'sum';
1452
	}
1453
1454
	/**
1455
	 * Count the meta values in a table, within a specified range.
1456
	 *
1457
	 * @access private
1458
	 *
1459
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
1460
	 *
1461
	 * @param string $table     Table name.
1462
	 * @param string $where_sql Additional WHERE SQL.
1463
	 * @param int    $min_id    Minimum meta ID.
1464
	 * @param int    $max_id    Maximum meta ID.
1465
	 * @return int Number of meta values.
1466
	 */
1467
	private function meta_count( $table, $where_sql, $min_id, $max_id ) {
1468
		global $wpdb;
1469
1470
		if ( ! empty( $min_id ) ) {
1471
			$where_sql .= ' AND meta_id >= ' . (int) $min_id;
1472
		}
1473
1474
		if ( ! empty( $max_id ) ) {
1475
			$where_sql .= ' AND meta_id <= ' . (int) $max_id;
1476
		}
1477
1478
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1479
		return $wpdb->get_var( "SELECT COUNT(*) FROM $table WHERE $where_sql" );
1480
	}
1481
1482
	/**
1483
	 * Wraps a column name in SQL which strips non-ASCII chars.
1484
	 * This helps normalize data to avoid checksum differences caused by
1485
	 * badly encoded data in the DB.
1486
	 *
1487
	 * @param string $column_name Name of the column.
1488
	 * @return string Column name, without the non-ASCII chars.
1489
	 */
1490
	public function strip_non_ascii_sql( $column_name ) {
1491
		return "REPLACE( CONVERT( $column_name USING ascii ), '?', '' )";
1492
	}
1493
1494
	/**
1495
	 * Used in methods that are not implemented and shouldn't be invoked.
1496
	 *
1497
	 * @access private
1498
	 * @throws \Exception If this method is invoked.
1499
	 */
1500
	private function invalid_call() {
1501
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
1502
		$backtrace = debug_backtrace();
1503
		$caller    = $backtrace[1]['function'];
1504
		throw new \Exception( "This function $caller is not supported on the WP Replicastore" );
1505
	}
1506
}
1507