Completed
Push — add/sync-partial-sync-checksum... ( b214f6...f71524 )
by
unknown
08:04
created

Replicastore::table_checksum()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 24
nop 8
dl 0
loc 47
rs 7.9119
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * Sync replicastore.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
use Automattic\Jetpack\Sync\Replicastore\Table_Checksum;
11
12
/**
13
 * An implementation of Replicastore Interface which returns data stored in a WordPress.org DB.
14
 * This is useful to compare values in the local WP DB to values in the synced replica store
15
 */
16
class Replicastore implements Replicastore_Interface {
17
	/**
18
	 * Empty and reset the replicastore.
19
	 *
20
	 * @access public
21
	 */
22
	public function reset() {
23
		global $wpdb;
24
25
		$wpdb->query( "DELETE FROM $wpdb->posts" );
26
27
		// Delete comments from cache.
28
		$comment_ids = $wpdb->get_col( "SELECT comment_ID FROM $wpdb->comments" );
29
		if ( ! empty( $comment_ids ) ) {
30
			clean_comment_cache( $comment_ids );
31
		}
32
		$wpdb->query( "DELETE FROM $wpdb->comments" );
33
34
		// Also need to delete terms from cache.
35
		$term_ids = $wpdb->get_col( "SELECT term_id FROM $wpdb->terms" );
36
		foreach ( $term_ids as $term_id ) {
37
			wp_cache_delete( $term_id, 'terms' );
38
		}
39
40
		$wpdb->query( "DELETE FROM $wpdb->terms" );
41
42
		$wpdb->query( "DELETE FROM $wpdb->term_taxonomy" );
43
		$wpdb->query( "DELETE FROM $wpdb->term_relationships" );
44
45
		// Callables and constants.
46
		$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'jetpack_%'" );
47
		$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key NOT LIKE '\_%'" );
48
	}
49
50
	/**
51
	 * Ran when full sync has just started.
52
	 *
53
	 * @access public
54
	 *
55
	 * @param array $config Full sync configuration for this sync module.
56
	 */
57
	public function full_sync_start( $config ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
58
		$this->reset();
59
	}
60
61
	/**
62
	 * Ran when full sync has just finished.
63
	 *
64
	 * @access public
65
	 *
66
	 * @param string $checksum Deprecated since 7.3.0.
67
	 */
68
	public function full_sync_end( $checksum ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
69
		// Noop right now.
70
	}
71
72
	/**
73
	 * Retrieve the number of terms.
74
	 *
75
	 * @access public
76
	 *
77
	 * @return int Number of terms.
78
	 */
79
	public function term_count() {
80
		global $wpdb;
81
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->terms" );
82
	}
83
84
	/**
85
	 * Retrieve the number of rows in the `term_taxonomy` table.
86
	 *
87
	 * @access public
88
	 *
89
	 * @return int Number of terms.
90
	 */
91
	public function term_taxonomy_count() {
92
		global $wpdb;
93
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->term_taxonomy" );
94
	}
95
96
	/**
97
	 * Retrieve the number of term relationships.
98
	 *
99
	 * @access public
100
	 *
101
	 * @return int Number of rows in the term relationships table.
102
	 */
103
	public function term_relationship_count() {
104
		global $wpdb;
105
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->term_relationships" );
106
	}
107
108
	/**
109
	 * Retrieve the number of posts with a particular post status within a certain range.
110
	 *
111
	 * @access public
112
	 *
113
	 * @todo Prepare the SQL query before executing it.
114
	 *
115
	 * @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...
116
	 * @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...
117
	 * @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...
118
	 * @return int Number of posts.
119
	 */
120 View Code Duplication
	public function post_count( $status = null, $min_id = null, $max_id = null ) {
121
		global $wpdb;
122
123
		$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...
124
125
		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...
126
			$where = "post_status = '" . esc_sql( $status ) . "'";
127
		} else {
128
			$where = '1=1';
129
		}
130
131
		if ( ! empty( $min_id ) ) {
132
			$where .= ' AND ID >= ' . (int) $min_id;
133
		}
134
135
		if ( ! empty( $max_id ) ) {
136
			$where .= ' AND ID <= ' . (int) $max_id;
137
		}
138
139
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
140
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE $where" );
141
	}
142
143
	/**
144
	 * Retrieve the posts with a particular post status.
145
	 *
146
	 * @access public
147
	 *
148
	 * @todo Implement range and actually use max_id/min_id arguments.
149
	 *
150
	 * @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...
151
	 * @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...
152
	 * @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...
153
	 * @return array Array of posts.
154
	 */
155
	public function get_posts( $status = null, $min_id = null, $max_id = null ) {
156
		$args = array(
157
			'orderby'        => 'ID',
158
			'posts_per_page' => -1,
159
		);
160
161
		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...
162
			$args['post_status'] = $status;
163
		} else {
164
			$args['post_status'] = 'any';
165
		}
166
167
		return get_posts( $args );
168
	}
169
170
	/**
171
	 * Retrieve a post object by the post ID.
172
	 *
173
	 * @access public
174
	 *
175
	 * @param int $id Post ID.
176
	 * @return \WP_Post Post object.
177
	 */
178
	public function get_post( $id ) {
179
		return get_post( $id );
180
	}
181
182
	/**
183
	 * Update or insert a post.
184
	 *
185
	 * @access public
186
	 *
187
	 * @param \WP_Post $post   Post object.
188
	 * @param bool     $silent Whether to perform a silent action. Not used in this implementation.
189
	 */
190
	public function upsert_post( $post, $silent = false ) {
191
		global $wpdb;
192
193
		// Reject the post if it's not a \WP_Post.
194
		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...
195
			return;
196
		}
197
198
		$post = $post->to_array();
199
200
		// Reject posts without an ID.
201
		if ( ! isset( $post['ID'] ) ) {
202
			return;
203
		}
204
205
		$now     = current_time( 'mysql' );
206
		$now_gmt = get_gmt_from_date( $now );
207
208
		$defaults = array(
209
			'ID'                    => 0,
210
			'post_author'           => '0',
211
			'post_content'          => '',
212
			'post_content_filtered' => '',
213
			'post_title'            => '',
214
			'post_name'             => '',
215
			'post_excerpt'          => '',
216
			'post_status'           => 'draft',
217
			'post_type'             => 'post',
218
			'comment_status'        => 'closed',
219
			'comment_count'         => '0',
220
			'ping_status'           => '',
221
			'post_password'         => '',
222
			'to_ping'               => '',
223
			'pinged'                => '',
224
			'post_parent'           => 0,
225
			'menu_order'            => 0,
226
			'guid'                  => '',
227
			'post_date'             => $now,
228
			'post_date_gmt'         => $now_gmt,
229
			'post_modified'         => $now,
230
			'post_modified_gmt'     => $now_gmt,
231
		);
232
233
		$post = array_intersect_key( $post, $defaults );
234
235
		$post = sanitize_post( $post, 'db' );
236
237
		unset( $post['filter'] );
238
239
		$exists = $wpdb->get_var( $wpdb->prepare( "SELECT EXISTS( SELECT 1 FROM $wpdb->posts WHERE ID = %d )", $post['ID'] ) );
240
241
		if ( $exists ) {
242
			$wpdb->update( $wpdb->posts, $post, array( 'ID' => $post['ID'] ) );
243
		} else {
244
			$wpdb->insert( $wpdb->posts, $post );
245
		}
246
247
		clean_post_cache( $post['ID'] );
248
	}
249
250
	/**
251
	 * Delete a post by the post ID.
252
	 *
253
	 * @access public
254
	 *
255
	 * @param int $post_id Post ID.
256
	 */
257
	public function delete_post( $post_id ) {
258
		wp_delete_post( $post_id, true );
259
	}
260
261
	/**
262
	 * Retrieve the checksum for posts within a range.
263
	 *
264
	 * @access public
265
	 *
266
	 * @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...
267
	 * @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...
268
	 * @return int The checksum.
269
	 */
270
	public function posts_checksum( $min_id = null, $max_id = null ) {
271
		$checksum_table = new Table_Checksum( 'posts' );
272
		return $checksum_table->calculate_checksum( $min_id, $max_id );
273
	}
274
275
	/**
276
	 * Retrieve the checksum for post meta within a range.
277
	 *
278
	 * @access public
279
	 *
280
	 * @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...
281
	 * @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...
282
	 * @return int The checksum.
283
	 */
284
	public function post_meta_checksum( $min_id = null, $max_id = null ) {
285
		$checksum_table = new Table_Checksum( 'postmeta' );
286
		return $checksum_table->calculate_checksum( $min_id, $max_id );
287
	}
288
289
	/**
290
	 * Retrieve the number of comments with a particular comment status within a certain range.
291
	 *
292
	 * @access public
293
	 *
294
	 * @todo Prepare the SQL query before executing it.
295
	 *
296
	 * @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...
297
	 * @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...
298
	 * @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...
299
	 * @return int Number of comments.
300
	 */
301 View Code Duplication
	public function comment_count( $status = null, $min_id = null, $max_id = null ) {
302
		global $wpdb;
303
304
		$comment_approved = $this->comment_status_to_approval_value( $status );
305
306
		if ( false !== $comment_approved ) {
307
			$where = "comment_approved = '" . esc_sql( $comment_approved ) . "'";
308
		} else {
309
			$where = '1=1';
310
		}
311
312
		if ( ! empty( $min_id ) ) {
313
			$where .= ' AND comment_ID >= ' . (int) $min_id;
314
		}
315
316
		if ( ! empty( $max_id ) ) {
317
			$where .= ' AND comment_ID <= ' . (int) $max_id;
318
		}
319
320
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
321
		return $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE $where" );
322
	}
323
324
	/**
325
	 * Translate a comment status to a value of the comment_approved field.
326
	 *
327
	 * @access private
328
	 *
329
	 * @param string $status Comment status.
330
	 * @return string|bool New comment_approved value, false if the status doesn't affect it.
331
	 */
332
	private function comment_status_to_approval_value( $status ) {
333
		switch ( $status ) {
334
			case 'approve':
335
				return '1';
336
			case 'hold':
337
				return '0';
338
			case 'spam':
339
				return 'spam';
340
			case 'trash':
341
				return 'trash';
342
			case 'any':
343
				return false;
344
			case 'all':
345
				return false;
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 ) {
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
		$checksum_table = new Table_Checksum( 'comments' );
510
		return $checksum_table->calculate_checksum( $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
		$checksum_table = new Table_Checksum( 'commentmeta' );
524
		return $checksum_table->calculate_checksum( $min_id, $max_id );
525
	}
526
527
	/**
528
	 * Update the value of an option.
529
	 *
530
	 * @access public
531
	 *
532
	 * @param string $option Option name.
533
	 * @param mixed  $value  Option value.
534
	 * @return bool False if value was not updated and true if value was updated.
535
	 */
536
	public function update_option( $option, $value ) {
537
		return update_option( $option, $value );
538
	}
539
540
	/**
541
	 * Retrieve an option value based on an option name.
542
	 *
543
	 * @access public
544
	 *
545
	 * @param string $option  Name of option to retrieve.
546
	 * @param mixed  $default Optional. Default value to return if the option does not exist.
547
	 * @return mixed Value set for the option.
548
	 */
549
	public function get_option( $option, $default = false ) {
550
		return get_option( $option, $default );
551
	}
552
553
	/**
554
	 * Remove an option by name.
555
	 *
556
	 * @access public
557
	 *
558
	 * @param string $option Name of option to remove.
559
	 * @return bool True, if option is successfully deleted. False on failure.
560
	 */
561
	public function delete_option( $option ) {
562
		return delete_option( $option );
563
	}
564
565
	/**
566
	 * Change the features that the current theme supports.
567
	 * Intentionally not implemented in this replicastore.
568
	 *
569
	 * @access public
570
	 *
571
	 * @param array $theme_support Features that the theme supports.
572
	 */
573
	public function set_theme_support( $theme_support ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
574
		// Noop.
575
	}
576
577
	/**
578
	 * Whether the current theme supports a certain feature.
579
	 *
580
	 * @access public
581
	 *
582
	 * @param string $feature Name of the feature.
583
	 */
584
	public function current_theme_supports( $feature ) {
585
		return current_theme_supports( $feature );
586
	}
587
588
	/**
589
	 * Retrieve metadata for the specified object.
590
	 *
591
	 * @access public
592
	 *
593
	 * @param string $type       Meta type.
594
	 * @param int    $object_id  ID of the object.
595
	 * @param string $meta_key   Meta key.
596
	 * @param bool   $single     If true, return only the first value of the specified meta_key.
597
	 *
598
	 * @return mixed Single metadata value, or array of values.
599
	 */
600
	public function get_metadata( $type, $object_id, $meta_key = '', $single = false ) {
601
		return get_metadata( $type, $object_id, $meta_key, $single );
602
	}
603
604
	/**
605
	 * Stores remote meta key/values alongside an ID mapping key.
606
	 *
607
	 * @access public
608
	 *
609
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
610
	 *
611
	 * @param string $type       Meta type.
612
	 * @param int    $object_id  ID of the object.
613
	 * @param string $meta_key   Meta key.
614
	 * @param mixed  $meta_value Meta value.
615
	 * @param int    $meta_id    ID of the meta.
616
	 *
617
	 * @return bool False if meta table does not exist, true otherwise.
618
	 */
619
	public function upsert_metadata( $type, $object_id, $meta_key, $meta_value, $meta_id ) {
620
		$table = _get_meta_table( $type );
621
		if ( ! $table ) {
622
			return false;
623
		}
624
625
		global $wpdb;
626
627
		$exists = $wpdb->get_var(
628
			$wpdb->prepare(
629
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
630
				"SELECT EXISTS( SELECT 1 FROM $table WHERE meta_id = %d )",
631
				$meta_id
632
			)
633
		);
634
635
		if ( $exists ) {
636
			$wpdb->update(
637
				$table,
638
				array(
639
					'meta_key'   => $meta_key,
640
					'meta_value' => maybe_serialize( $meta_value ),
641
				),
642
				array( 'meta_id' => $meta_id )
643
			);
644
		} else {
645
			$object_id_field = $type . '_id';
646
			$wpdb->insert(
647
				$table,
648
				array(
649
					'meta_id'        => $meta_id,
650
					$object_id_field => $object_id,
651
					'meta_key'       => $meta_key,
652
					'meta_value'     => maybe_serialize( $meta_value ),
653
				)
654
			);
655
		}
656
657
		wp_cache_delete( $object_id, $type . '_meta' );
658
659
		return true;
660
	}
661
662
	/**
663
	 * Delete metadata for the specified object.
664
	 *
665
	 * @access public
666
	 *
667
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
668
	 *
669
	 * @param string $type      Meta type.
670
	 * @param int    $object_id ID of the object.
671
	 * @param array  $meta_ids  IDs of the meta objects to delete.
672
	 */
673
	public function delete_metadata( $type, $object_id, $meta_ids ) {
674
		global $wpdb;
675
676
		$table = _get_meta_table( $type );
677
		if ( ! $table ) {
678
			return false;
679
		}
680
681
		foreach ( $meta_ids as $meta_id ) {
682
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
683
			$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE meta_id = %d", $meta_id ) );
684
		}
685
686
		// If we don't have an object ID what do we do - invalidate ALL meta?
687
		if ( $object_id ) {
688
			wp_cache_delete( $object_id, $type . '_meta' );
689
		}
690
	}
691
692
	/**
693
	 * Delete metadata with a certain key for the specified objects.
694
	 *
695
	 * @access public
696
	 *
697
	 * @todo Test this out to make sure it works as expected.
698
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
699
	 *
700
	 * @param string $type       Meta type.
701
	 * @param array  $object_ids IDs of the objects.
702
	 * @param string $meta_key   Meta key.
703
	 */
704
	public function delete_batch_metadata( $type, $object_ids, $meta_key ) {
705
		global $wpdb;
706
707
		$table = _get_meta_table( $type );
708
		if ( ! $table ) {
709
			return false;
710
		}
711
		$column = sanitize_key( $type . '_id' );
712
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
713
		$wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE $column IN (%s) && meta_key = %s", implode( ',', $object_ids ), $meta_key ) );
714
715
		// If we don't have an object ID what do we do - invalidate ALL meta?
716
		foreach ( $object_ids as $object_id ) {
717
			wp_cache_delete( $object_id, $type . '_meta' );
718
		}
719
	}
720
721
	/**
722
	 * Retrieve value of a constant based on the constant name.
723
	 *
724
	 * @access public
725
	 *
726
	 * @param string $constant Name of constant to retrieve.
727
	 * @return mixed Value set for the constant.
728
	 */
729
	public function get_constant( $constant ) {
730
		$value = get_option( 'jetpack_constant_' . $constant );
731
732
		if ( $value ) {
733
			return $value;
734
		}
735
736
		return null;
737
	}
738
739
	/**
740
	 * Set the value of a constant.
741
	 *
742
	 * @access public
743
	 *
744
	 * @param string $constant Name of constant to retrieve.
745
	 * @param mixed  $value    Value set for the constant.
746
	 */
747
	public function set_constant( $constant, $value ) {
748
		update_option( 'jetpack_constant_' . $constant, $value );
749
	}
750
751
	/**
752
	 * Retrieve the number of the available updates of a certain type.
753
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
754
	 *
755
	 * @access public
756
	 *
757
	 * @param string $type Type of updates to retrieve.
758
	 * @return int|null Number of updates available, `null` if type is invalid or missing.
759
	 */
760
	public function get_updates( $type ) {
761
		$all_updates = get_option( 'jetpack_updates', array() );
762
763
		if ( isset( $all_updates[ $type ] ) ) {
764
			return $all_updates[ $type ];
765
		} else {
766
			return null;
767
		}
768
	}
769
770
	/**
771
	 * Set the available updates of a certain type.
772
	 * Type is one of: `plugins`, `themes`, `wordpress`, `translations`, `total`, `wp_update_version`.
773
	 *
774
	 * @access public
775
	 *
776
	 * @param string $type    Type of updates to set.
777
	 * @param int    $updates Total number of updates.
778
	 */
779
	public function set_updates( $type, $updates ) {
780
		$all_updates          = get_option( 'jetpack_updates', array() );
781
		$all_updates[ $type ] = $updates;
782
		update_option( 'jetpack_updates', $all_updates );
783
	}
784
785
	/**
786
	 * Retrieve a callable value based on its name.
787
	 *
788
	 * @access public
789
	 *
790
	 * @param string $name Name of the callable to retrieve.
791
	 * @return mixed Value of the callable.
792
	 */
793
	public function get_callable( $name ) {
794
		$value = get_option( 'jetpack_' . $name );
795
796
		if ( $value ) {
797
			return $value;
798
		}
799
800
		return null;
801
	}
802
803
	/**
804
	 * Update the value of a callable.
805
	 *
806
	 * @access public
807
	 *
808
	 * @param string $name  Callable name.
809
	 * @param mixed  $value Callable value.
810
	 */
811
	public function set_callable( $name, $value ) {
812
		update_option( 'jetpack_' . $name, $value );
813
	}
814
815
	/**
816
	 * Retrieve a network option value based on a network option name.
817
	 *
818
	 * @access public
819
	 *
820
	 * @param string $option Name of network option to retrieve.
821
	 * @return mixed Value set for the network option.
822
	 */
823
	public function get_site_option( $option ) {
824
		return get_option( 'jetpack_network_' . $option );
825
	}
826
827
	/**
828
	 * Update the value of a network option.
829
	 *
830
	 * @access public
831
	 *
832
	 * @param string $option Network option name.
833
	 * @param mixed  $value  Network option value.
834
	 * @return bool False if value was not updated and true if value was updated.
835
	 */
836
	public function update_site_option( $option, $value ) {
837
		return update_option( 'jetpack_network_' . $option, $value );
838
	}
839
840
	/**
841
	 * Remove a network option by name.
842
	 *
843
	 * @access public
844
	 *
845
	 * @param string $option Name of option to remove.
846
	 * @return bool True, if option is successfully deleted. False on failure.
847
	 */
848
	public function delete_site_option( $option ) {
849
		return delete_option( 'jetpack_network_' . $option );
850
	}
851
852
	/**
853
	 * Retrieve the terms from a particular taxonomy.
854
	 *
855
	 * @access public
856
	 *
857
	 * @param string $taxonomy Taxonomy slug.
858
	 * @return array Array of terms.
859
	 */
860
	public function get_terms( $taxonomy ) {
861
		return get_terms( $taxonomy );
862
	}
863
864
	/**
865
	 * Retrieve a particular term.
866
	 *
867
	 * @access public
868
	 *
869
	 * @param string $taxonomy   Taxonomy slug.
870
	 * @param int    $term_id    ID of the term.
871
	 * @param bool   $is_term_id Whether this is a `term_id` or a `term_taxonomy_id`.
872
	 * @return \WP_Term|\WP_Error Term object on success, \WP_Error object on failure.
873
	 */
874
	public function get_term( $taxonomy, $term_id, $is_term_id = true ) {
875
		$t = $this->ensure_taxonomy( $taxonomy );
876
		if ( ! $t || is_wp_error( $t ) ) {
877
			return $t;
878
		}
879
880
		return get_term( $term_id, $taxonomy );
881
	}
882
883
	/**
884
	 * Verify a taxonomy is legitimate and register it if necessary.
885
	 *
886
	 * @access private
887
	 *
888
	 * @param string $taxonomy Taxonomy slug.
889
	 * @return bool|void|\WP_Error True if already exists; void if it was registered; \WP_Error on error.
890
	 */
891
	private function ensure_taxonomy( $taxonomy ) {
892
		if ( ! taxonomy_exists( $taxonomy ) ) {
893
			// Try re-registering synced taxonomies.
894
			$taxonomies = $this->get_callable( 'taxonomies' );
895
			if ( ! isset( $taxonomies[ $taxonomy ] ) ) {
896
				// Doesn't exist, or somehow hasn't been synced.
897
				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...
898
			}
899
			$t = $taxonomies[ $taxonomy ];
900
901
			return register_taxonomy(
902
				$taxonomy,
903
				$t->object_type,
904
				(array) $t
905
			);
906
		}
907
908
		return true;
909
	}
910
911
	/**
912
	 * Retrieve all terms from a taxonomy that are related to an object with a particular ID.
913
	 *
914
	 * @access public
915
	 *
916
	 * @param int    $object_id Object ID.
917
	 * @param string $taxonomy  Taxonomy slug.
918
	 * @return array|bool|\WP_Error Array of terms on success, `false` if no terms or post doesn't exist, \WP_Error on failure.
919
	 */
920
	public function get_the_terms( $object_id, $taxonomy ) {
921
		return get_the_terms( $object_id, $taxonomy );
922
	}
923
924
	/**
925
	 * Insert or update a term.
926
	 *
927
	 * @access public
928
	 *
929
	 * @param \WP_Term $term_object Term object.
930
	 * @return array|bool|\WP_Error Array of term_id and term_taxonomy_id if updated, true if inserted, \WP_Error on failure.
931
	 */
932
	public function update_term( $term_object ) {
933
		$taxonomy = $term_object->taxonomy;
934
		global $wpdb;
935
		$exists = $wpdb->get_var(
936
			$wpdb->prepare(
937
				"SELECT EXISTS( SELECT 1 FROM $wpdb->terms WHERE term_id = %d )",
938
				$term_object->term_id
939
			)
940
		);
941
		if ( ! $exists ) {
942
			$term_object   = sanitize_term( clone( $term_object ), $taxonomy, 'db' );
943
			$term          = array(
944
				'term_id'    => $term_object->term_id,
945
				'name'       => $term_object->name,
946
				'slug'       => $term_object->slug,
947
				'term_group' => $term_object->term_group,
948
			);
949
			$term_taxonomy = array(
950
				'term_taxonomy_id' => $term_object->term_taxonomy_id,
951
				'term_id'          => $term_object->term_id,
952
				'taxonomy'         => $term_object->taxonomy,
953
				'description'      => $term_object->description,
954
				'parent'           => (int) $term_object->parent,
955
				'count'            => (int) $term_object->count,
956
			);
957
			$wpdb->insert( $wpdb->terms, $term );
958
			$wpdb->insert( $wpdb->term_taxonomy, $term_taxonomy );
959
960
			return true;
961
		}
962
963
		return wp_update_term( $term_object->term_id, $taxonomy, (array) $term_object );
964
	}
965
966
	/**
967
	 * Delete a term by the term ID and its corresponding taxonomy.
968
	 *
969
	 * @access public
970
	 *
971
	 * @param int    $term_id  Term ID.
972
	 * @param string $taxonomy Taxonomy slug.
973
	 * @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.
974
	 */
975
	public function delete_term( $term_id, $taxonomy ) {
976
		return wp_delete_term( $term_id, $taxonomy );
977
	}
978
979
	/**
980
	 * Add/update terms of a particular taxonomy of an object with the specified ID.
981
	 *
982
	 * @access public
983
	 *
984
	 * @param int              $object_id The object to relate to.
985
	 * @param string           $taxonomy  The context in which to relate the term to the object.
986
	 * @param string|int|array $terms     A single term slug, single term id, or array of either term slugs or ids.
987
	 * @param bool             $append    Optional. If false will delete difference of terms. Default false.
988
	 */
989
	public function update_object_terms( $object_id, $taxonomy, $terms, $append ) {
990
		wp_set_object_terms( $object_id, $terms, $taxonomy, $append );
991
	}
992
993
	/**
994
	 * Remove certain term relationships from the specified object.
995
	 *
996
	 * @access public
997
	 *
998
	 * @todo Refactor to not use interpolated values when preparing the SQL query.
999
	 *
1000
	 * @param int   $object_id ID of the object.
1001
	 * @param array $tt_ids    Term taxonomy IDs.
1002
	 * @return bool True on success, false on failure.
1003
	 */
1004
	public function delete_object_terms( $object_id, $tt_ids ) {
1005
		global $wpdb;
1006
1007
		if ( is_array( $tt_ids ) && ! empty( $tt_ids ) ) {
1008
			// Escape.
1009
			$tt_ids_sanitized = array_map( 'intval', $tt_ids );
1010
1011
			$taxonomies = array();
1012
			foreach ( $tt_ids_sanitized as $tt_id ) {
1013
				$term                            = get_term_by( 'term_taxonomy_id', $tt_id );
1014
				$taxonomies[ $term->taxonomy ][] = $tt_id;
1015
			}
1016
			$in_tt_ids = implode( ', ', $tt_ids_sanitized );
1017
1018
			/**
1019
			 * Fires immediately before an object-term relationship is deleted.
1020
			 *
1021
			 * @since 2.9.0
1022
			 *
1023
			 * @param int   $object_id Object ID.
1024
			 * @param array $tt_ids    An array of term taxonomy IDs.
1025
			 */
1026
			do_action( 'delete_term_relationships', $object_id, $tt_ids_sanitized );
1027
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1028
			$deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
1029
			foreach ( $taxonomies as $taxonomy => $taxonomy_tt_ids ) {
1030
				$this->ensure_taxonomy( $taxonomy );
1031
				wp_cache_delete( $object_id, $taxonomy . '_relationships' );
1032
				/**
1033
				 * Fires immediately after an object-term relationship is deleted.
1034
				 *
1035
				 * @since 2.9.0
1036
				 *
1037
				 * @param int   $object_id Object ID.
1038
				 * @param array $tt_ids    An array of term taxonomy IDs.
1039
				 */
1040
				do_action( 'deleted_term_relationships', $object_id, $taxonomy_tt_ids );
1041
				wp_update_term_count( $taxonomy_tt_ids, $taxonomy );
1042
			}
1043
1044
			return (bool) $deleted;
1045
		}
1046
1047
		return false;
1048
	}
1049
1050
	/**
1051
	 * Retrieve the number of users.
1052
	 * Not supported in this replicastore.
1053
	 *
1054
	 * @access public
1055
	 */
1056
	public function user_count() {
1057
		// Noop.
1058
	}
1059
1060
	/**
1061
	 * Retrieve a user object by the user ID.
1062
	 *
1063
	 * @access public
1064
	 *
1065
	 * @param int $user_id User ID.
1066
	 * @return \WP_User User object.
1067
	 */
1068
	public function get_user( $user_id ) {
1069
		return \WP_User::get_instance( $user_id );
1070
	}
1071
1072
	/**
1073
	 * Insert or update a user.
1074
	 * Not supported in this replicastore.
1075
	 *
1076
	 * @access public
1077
	 * @throws \Exception If this method is invoked.
1078
	 *
1079
	 * @param \WP_User $user User object.
1080
	 */
1081
	public function upsert_user( $user ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1082
		$this->invalid_call();
1083
	}
1084
1085
	/**
1086
	 * Delete a user.
1087
	 * Not supported in this replicastore.
1088
	 *
1089
	 * @access public
1090
	 * @throws \Exception If this method is invoked.
1091
	 *
1092
	 * @param int $user_id User ID.
1093
	 */
1094
	public function delete_user( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1095
		$this->invalid_call();
1096
	}
1097
1098
	/**
1099
	 * Update/insert user locale.
1100
	 * Not supported in this replicastore.
1101
	 *
1102
	 * @access public
1103
	 * @throws \Exception If this method is invoked.
1104
	 *
1105
	 * @param int    $user_id User ID.
1106
	 * @param string $local   The user locale.
1107
	 */
1108
	public function upsert_user_locale( $user_id, $local ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1109
		$this->invalid_call();
1110
	}
1111
1112
	/**
1113
	 * Delete user locale.
1114
	 * Not supported in this replicastore.
1115
	 *
1116
	 * @access public
1117
	 * @throws \Exception If this method is invoked.
1118
	 *
1119
	 * @param int $user_id User ID.
1120
	 */
1121
	public function delete_user_locale( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1122
		$this->invalid_call();
1123
	}
1124
1125
	/**
1126
	 * Retrieve the user locale.
1127
	 *
1128
	 * @access public
1129
	 *
1130
	 * @param int $user_id User ID.
1131
	 * @return string The user locale.
1132
	 */
1133
	public function get_user_locale( $user_id ) {
1134
		return get_user_locale( $user_id );
1135
	}
1136
1137
	/**
1138
	 * Retrieve the allowed mime types for the user.
1139
	 * Not supported in this replicastore.
1140
	 *
1141
	 * @access public
1142
	 *
1143
	 * @param int $user_id User ID.
1144
	 */
1145
	public function get_allowed_mime_types( $user_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1146
		// Noop.
1147
	}
1148
1149
	/**
1150
	 * Retrieve all the checksums we are interested in.
1151
	 * Currently that is posts, comments, post meta and comment meta.
1152
	 *
1153
	 * @access public
1154
	 *
1155
	 * @return array Checksums.
1156
	 */
1157
	public function checksum_all() {
1158
		$post_meta_checksum    = $this->checksum_histogram( 'post_meta', 1 );
1159
		$comment_meta_checksum = $this->checksum_histogram( 'comment_meta', 1 );
1160
1161
		return array(
1162
			'posts'        => $this->posts_checksum(),
1163
			'comments'     => $this->comments_checksum(),
1164
			'post_meta'    => reset( $post_meta_checksum ),
1165
			'comment_meta' => reset( $comment_meta_checksum ),
1166
		);
1167
	}
1168
1169
	/**
1170
	 * Grabs the minimum and maximum object ids for the given parameters.
1171
	 *
1172
	 * @access public
1173
	 *
1174
	 * @param string $id_field     The id column in the table to query.
1175
	 * @param string $object_table The table to query.
1176
	 * @param string $where        A sql where clause without 'WHERE'.
1177
	 * @param int    $bucket_size  The maximum amount of objects to include in the query.
1178
	 *                             For `term_relationships` table, the bucket size will refer to the amount
1179
	 *                             of distinct object ids. This will likely include more database rows than
1180
	 *                             the bucket size implies.
1181
	 *
1182
	 * @return object An object with min_id and max_id properties.
1183
	 */
1184
	public function get_min_max_object_id( $id_field, $object_table, $where, $bucket_size ) {
1185
		global $wpdb;
1186
1187
		// The term relationship table's unique key is a combination of 2 columns. `DISTINCT` helps us get a more acurate query.
1188
		$distinct_sql = ( $wpdb->term_relationships === $object_table ) ? 'DISTINCT' : '';
1189
		$where_sql    = $where ? "WHERE $where" : '';
1190
1191
		// Since MIN() and MAX() do not work with LIMIT, we'll need to adjust the dataset we query if a limit is present.
1192
		// With a limit present, we'll look at a dataset consisting of object_ids that meet the constructs of the $where clause.
1193
		// Without a limit, we can use the actual table as a dataset.
1194
		$from = $bucket_size ?
1195
			"( SELECT $distinct_sql $id_field FROM $object_table $where_sql ORDER BY $id_field ASC LIMIT $bucket_size ) as ids" :
1196
			"$object_table $where_sql ORDER BY $id_field ASC";
1197
1198
		return $wpdb->get_row(
1199
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1200
			"SELECT MIN($id_field) as min, MAX($id_field) as max FROM $from"
1201
		);
1202
	}
1203
1204
	/**
1205
	 * Retrieve the checksum histogram for a specific object type.
1206
	 *
1207
	 * @access public
1208
	 *
1209
	 * @todo Refactor to not use interpolated values and properly prepare the SQL query.
1210
	 *
1211
	 * @param string $object_type     Object type.
1212
	 * @param int    $buckets         Number of buckets to split the objects to.
1213
	 * @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...
1214
	 * @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...
1215
	 * @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...
1216
	 * @param bool   $strip_non_ascii Whether to strip non-ASCII characters.
1217
	 * @param string $salt            Salt, used for $wpdb->prepare()'s args.
1218
	 * @return array The checksum histogram.
1219
	 */
1220
	public function checksum_histogram( $object_type, $buckets, $start_id = null, $end_id = null, $columns = null, $strip_non_ascii = true, $salt = '' ) {
1221
		global $wpdb;
1222
1223
		$wpdb->queries = array();
1224
1225
		/**
1226
		 * TODO TEMPORARY!
1227
		 *
1228
		 * Translate $object_type to $table
1229
		 */
1230
1231
		switch ( $object_type ) {
1232
			case 'posts':
1233
			case 'term_taxonomy':
1234
			case 'comments':
1235
			case 'terms':
1236
			case 'term_relationships':
1237
				$table = $object_type;
1238
				break;
1239
			case 'post_meta':
1240
				$table = 'postmeta';
1241
				break;
1242
			case 'comment_meta':
1243
				$table = 'commentmeta';
1244
				break;
1245
			default:
1246
				return false;
1247
		}
1248
1249
		$checksum_table = new Table_Checksum( $table, $salt );
1250
		$range_edges    = $checksum_table->get_range_edges();
1251
1252
		$object_count = $range_edges['item_count'];
1253
1254
		$bucket_size     = (int) ceil( $object_count / $buckets );
1255
		$previous_max_id = 0;
1256
		$histogram       = array();
1257
1258
		do {
1259
			$ids_range = $checksum_table->get_range_edges( $previous_max_id, null, $bucket_size );
1260
1261
			if ( empty( $ids_range['min_range'] ) || empty( $ids_range['max_range'] ) ) {
1262
				// Nothing to checksum here...
1263
				break;
1264
			}
1265
1266
			// Get the checksum value.
1267
			$batch_checksum = $checksum_table->calculate_checksum( $ids_range['min_range'], $ids_range['max_range'] );
1268
1269
			if ( is_wp_error( $batch_checksum ) ) {
1270
				return $batch_checksum;
1271
			}
1272
1273
			if ( $ids_range['min_range'] === $ids_range['max_range'] ) {
1274
				$histogram[ $ids_range['min_range'] ] = $batch_checksum;
1275
			} else {
1276
				$histogram[ "{$ids_range[ 'min_range' ]}-{$ids_range[ 'max_range' ]}" ] = $batch_checksum;
1277
			}
1278
1279
			$previous_max_id = $ids_range['max_range'];
1280
		} while ( true );
1281
1282
		return $histogram;
1283
	}
1284
1285
	/**
1286
	 * Retrieve the type of the checksum.
1287
	 *
1288
	 * @access public
1289
	 *
1290
	 * @return string Type of the checksum.
1291
	 */
1292
	public function get_checksum_type() {
1293
		return 'sum';
1294
	}
1295
1296
	/**
1297
	 * Used in methods that are not implemented and shouldn't be invoked.
1298
	 *
1299
	 * @access private
1300
	 * @throws \Exception If this method is invoked.
1301
	 */
1302
	private function invalid_call() {
1303
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
1304
		$backtrace = debug_backtrace();
1305
		$caller    = $backtrace[1]['function'];
1306
		throw new \Exception( "This function $caller is not supported on the WP Replicastore" );
1307
	}
1308
}
1309