Passed
Push — dependabot/npm_and_yarn/websoc... ( 8590a4...96b769 )
by
unknown
69:06
created

UsersModule::query_users()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 31
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1.0013

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
nc 1
nop 1
dl 0
loc 31
ccs 8
cts 9
cp 0.8889
crap 1.0013
rs 9.9666
c 4
b 0
f 0
1
<?php
2
3
namespace BulkWP\BulkDelete\Core\Users;
4
5
use BulkWP\BulkDelete\Core\Base\BaseModule;
6
7 1
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
8
9
/**
10
 * Encapsulates the Bulk Delete User Meta box Module Logic.
11
 * All Bulk Delete User Meta box Modules should extend this class.
12
 *
13
 * @see BaseModule
14
 * @since 5.5.2
15
 * @since 6.0.0 Renamed to UsersModule.
16
 */
17
abstract class UsersModule extends BaseModule {
18
	/**
19
	 * Build query params for WP_User_Query by using delete options.
20
	 *
21
	 * Return an empty query array to short-circuit deletion.
22
	 *
23
	 * @since 6.0.0
24
	 *
25
	 * @param array $options Delete options.
26
	 *
27
	 * @return array Query.
28
	 */
29
	abstract protected function build_query( $options );
30
31
	protected function parse_common_filters( $request ) {
32
		$options = array();
33
34
		$options['login_restrict'] = bd_array_get_bool( $request, "smbd_{$this->field_slug}_login_restrict", false );
35
		$options['login_days']     = absint( bd_array_get( $request, "smbd_{$this->field_slug}_login_days", 0 ) );
36
37
		$options['registered_restrict'] = bd_array_get_bool( $request, "smbd_{$this->field_slug}_registered_restrict", false );
38
		$options['registered_date_op']  = bd_array_get( $request, 'smbd_' . $this->field_slug . '_op' );
39
		$options['registered_days']     = absint( bd_array_get( $request, "smbd_{$this->field_slug}_registered_days", 0 ) );
40
41
		$options['no_posts']            = bd_array_get_bool( $request, "smbd_{$this->field_slug}_no_posts", false );
42
		$options['no_posts_post_types'] = bd_array_get( $request, "smbd_{$this->field_slug}_no_post_post_types", array() );
43
44
		$options['reassign_user']    = bd_array_get_bool( $request, "smbd_{$this->field_slug}_post_reassign", false );
45
		$options['reassign_user_id'] = absint( bd_array_get( $request, "smbd_{$this->field_slug}_reassign_user_id", 0 ) );
46
		$options['limit_to']         = absint( bd_array_get( $request, "smbd_{$this->field_slug}_limit_to", 0 ) );
47
48
		return $options;
49
	}
50
51 69
	protected function do_delete( $options ) {
52 69
		$query = $this->build_query( $options );
53
54 69
		if ( empty( $query ) ) {
55
			// Short circuit deletion, if nothing needs to be deleted.
56 2
			return 0;
57
		}
58
59 67
		$query = $this->exclude_users_from_deletion( $query );
60 67
		$query = $this->exclude_current_user( $query );
61 67
62 17
		return $this->delete_users_from_query( $query, $options );
63
	}
64
65 50
	/**
66
	 * Query and Delete users.
67
	 *
68
	 * @since  5.5.2
69
	 * @since  6.1.0 Query only user ids instead of user objects.
70
	 * @access protected
71
	 *
72
	 * @param array $query   Options to query users.
73
	 * @param array $options Delete options.
74
	 *
75
	 * @return int Number of users who were deleted.
76 50
	 */
77 50
	protected function delete_users_from_query( $query, $options ) {
78 50
		$count     = 0;
79 50
		$users_ids = $this->query_users( $query );
80
81 50
		if ( ! function_exists( 'wp_delete_user' ) ) {
82
			require_once ABSPATH . 'wp-admin/includes/user.php';
83
		}
84 50
85 44
		foreach ( $users_ids as $users_id ) {
86
			if ( ! $this->can_delete_by_logged_date( $options, $users_id ) ) {
87
				continue;
88 44
			}
89
90
			if ( ! $this->can_delete_by_post_count( $options, $users_id ) ) {
91 44
				continue;
92 44
			}
93
94
			/**
95
			 * Can a user be deleted.
96 50
			 *
97
			 * @since 6.0.0
98
			 * @since 6.1.0 Changed second parameter to user id instead of user object.
99
			 *
100
			 * @param bool                                    $delete   Can Delete the User. (Default true)
101
			 * @param int                                     $users_id User ID of the user who is about to be deleted.
102
			 * @param array                                   $options  Delete options.
103
			 * @param \BulkWP\BulkDelete\Core\Base\BaseModule $this     Module that is triggering deletion.
104
			 */
105
			if ( ! apply_filters( 'bd_can_delete_user', true, $users_id, $options, $this ) ) {
106
				continue;
107
			}
108
109
			if ( isset( $options['reassign_user'] ) && $options['reassign_user'] ) {
110 26
				$deleted = wp_delete_user( $users_id, $options['reassign_user_id'] );
111 26
			} else {
112 26
				$deleted = wp_delete_user( $users_id );
113
			}
114 26
115
			if ( $deleted ) {
116
				$count ++;
117
			}
118 26
		}
119 25
120
		return $count;
121
	}
122
123 25
	/**
124 13
	 * Query users using options.
125
	 *
126
	 * @since 6.1.0 Retrieve only user ids.
127
	 *
128
	 * @param array $options Query options.
129
	 *
130
	 * @return int[] List of user ids.
131
	 */
132
	protected function query_users( $options ) {
133
		$defaults = array(
134
			'count_total' => false,
135
			'fields'      => 'ids',
136
		);
137 23
138
		$options = wp_parse_args( $options, $defaults );
139
140
		$wp_user_query = new \WP_User_Query( $options );
141 23
142 1
		/**
143
		 * This action before the query happens.
144 22
		 *
145
		 * @since 6.0.0
146
		 *
147 23
		 * @param \WP_User_Query $wp_user_query Query object.
148 23
		 */
149
		do_action( 'bd_before_query', $wp_user_query );
150
151
		$user_ids = $wp_user_query->get_results();
152 26
153
		/**
154
		 * This action runs after the query happens.
155
		 *
156
		 * @since 6.0.0
157
		 *
158
		 * @param \WP_User_Query $wp_user_query Query object.
159
		 */
160
		do_action( 'bd_after_query', $wp_user_query );
161
162 75
		return $user_ids;
163
	}
164 75
165
	/**
166
	 * Can the user be deleted based on the 'post count' option?
167 75
	 *
168
	 * This doesn't work well in batches.
169 75
	 *
170
	 * @link   https://github.com/sudar/bulk-delete/issues/511 Github issue.
171
	 * @since  5.5.2
172
	 * @since  6.1.0 Changed second parameter to user id instead of user object.
173
	 * @access protected
174
	 *
175
	 * @param array $delete_options Delete Options.
176
	 * @param int   $user_id        User id that needs to be deleted.
177
	 *
178 75
	 * @return bool True if the user can be deleted, false otherwise.
179
	 */
180 75
	protected function can_delete_by_post_count( $delete_options, $user_id ) {
181
		return ! (
182
			$delete_options['no_posts'] &&
183
			count_user_posts( $user_id, $delete_options['no_posts_post_types'] ) > 0
184
		);
185
	}
186
187
	/**
188
	 * Get the date query part for WP_User_Query.
189 75
	 *
190
	 * Date query corresponds to user registered date.
191 75
	 *
192
	 * @since 6.0.0
193
	 *
194
	 * @param array $options Delete options.
195
	 *
196
	 * @return array Date Query.
197
	 */
198
	protected function get_date_query( $options ) {
199
		if ( ! $options['registered_restrict'] ) {
200
			return array();
201
		}
202
203
		if ( $options['registered_days'] <= 0 ) {
204
			return array();
205
		}
206
207
		if ( ! isset( $options['registered_date_op'] ) ) {
208 25
			return array(
209
				'before' => $options['registered_days'] . ' days ago',
210 25
			);
211 25
		}
212
213
		if ( 'before' === $options['registered_date_op'] || 'after' === $options['registered_date_op'] ) {
214
			return array(
215
				$options['registered_date_op'] => $options['registered_days'] . ' days ago',
216
			);
217
		}
218
219
		return array();
220
	}
221
222
	/**
223
	 * Can the user be deleted based on the 'logged in date' option?
224
	 *
225
	 * This doesn't work well in batches.
226 70
	 *
227 70
	 * @link   https://github.com/sudar/bulk-delete/issues/511 Github issue.
228 41
	 * @since  5.5.2
229
	 * @since  6.1.0 Changed second parameter to user id instead of user object.
230
	 * @access protected
231 29
	 *
232 1
	 * @param array $delete_options Delete Options.
233
	 * @param int   $user_id        User id that needs to be deleted.
234
	 *
235 28
	 * @return bool True if the user can be deleted, false otherwise.
236
	 */
237 24
	protected function can_delete_by_logged_date( $delete_options, $user_id ) {
238
		if ( $delete_options['login_restrict'] ) {
239
			$login_days = $delete_options['login_days'];
240
			$last_login = bd_get_last_login( $user_id );
241 4
242
			if ( null !== $last_login ) {
0 ignored issues
show
introduced by
The condition null !== $last_login is always true.
Loading history...
243 4
				// we have a logged-in entry for the user in simple login log plugin.
244
				if ( strtotime( $last_login ) > strtotime( '-' . $login_days . 'days' ) ) {
245
					return false;
246
				}
247
			} else {
248
				// we don't have a logged-in entry for the user in simple login log plugin.
249
				if ( $login_days > 0 ) {
250
					// non-zero value for login date. So don't delete this user.
251
					return false;
252
				}
253
			}
254
		}
255
256
		return true;
257
	}
258
259
	/**
260
	 * Render User Login restrict settings.
261
	 *
262
	 * @since 5.5
263
	 * @since 6.2.0 Added $show_login_filter param.
264 25
	 *
265 25
	 * @param bool $show_login_filter True/False.
266
	 */
267
	protected function render_user_login_restrict_settings( $show_login_filter = true ) {
268
		?>
269
		<tr>
270
			<td scope="row" colspan="2">
271
				<label for="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_restrict">
272
					<input name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_restrict" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_restrict" value="true" type="checkbox">
273
					<?php _e( 'Restrict to users who are registered in the site ', 'bulk-delete' ); ?>
274
				</label>
275
				<select name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_op" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_op" disabled>
276
					<option value="before"><?php _e( 'for at least', 'bulk-delete' ); ?></option>
277
					<option value="after"><?php _e( 'in the last', 'bulk-delete' ); ?></option>
278
				</select>
279
				<input type="number" name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_days" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_days" class="screen-per-page" disabled value="0" min="0"><?php _e( ' days.', 'bulk-delete' ); ?>
280
			</td>
281
		</tr>
282
		<?php if ( $show_login_filter ) : ?>
283 25
		<tr>
284
			<td scope="row" colspan="2">
285
				<label>
286
					<input name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_restrict" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_restrict"
287
							value="true" type="checkbox" <?php disabled( false, bd_is_simple_login_log_present() ); ?>>
288
					<?php _e( 'Restrict to users who have not logged in the last ', 'bulk-delete' ); ?>
289
				</label>
290
				<input type="number" name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_days" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_days" class="screen-per-page" value="0" min="0" disabled> <?php _e( 'days', 'bulk-delete' ); ?>.
291
292
				<?php if ( ! bd_is_simple_login_log_present() ) : ?>
293
					<span style = "color:red">
294
						<?php _e( 'Need the free "Simple Login Log" Plugin', 'bulk-delete' ); ?> <a href = "https://wordpress.org/plugins/simple-login-log/">Install now</a>
295
					</span>
296
				<?php endif; ?>
297
			</td>
298
		</tr>
299
300
			<?php if ( bd_is_simple_login_log_present() ) : ?>
301
			<tr>
302
				<td scope="row" colspan="2">
303
					<?php _e( 'Enter "0 days" to delete users who have never logged in after the "Simple Login Log" plugin has been installed.', 'bulk-delete' ); ?>
304
			</tr>
305
			<?php endif; ?>
306
		<?php endif; ?>
307
		<?php
308
	}
309
310
	/**
311
	 * Render delete user with no posts settings.
312
	 *
313
	 * @since 5.5
314
	 */
315
	protected function render_user_with_no_posts_settings() {
316
	?>
317
		<tr>
318
			<td scope="row" colspan="2">
319
				<input type="checkbox" value="true"
320
						name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts"
321
						id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts" class="user_restrict_to_no_posts_filter">
322
				<label for="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts">
323
					<?php _e( "Restrict to users who don't have any posts.", 'bulk-delete' ); ?>
324
				</label>
325
			</td>
326
		</tr>
327
328
		<tr class="user_restrict_to_no_posts_filter_items visually-hidden">
329
			<td scope="row" colspan="2">
330
				<table class="filter-items">
331
					<tr>
332
						<td scope="row">
333
							<?php _e( 'Select the post types. By default all post types are considered.', 'bulk-delete' ); ?>
334
						</td>
335
					</tr>
336
337
					<?php $this->render_post_type_checkboxes( "smbd_{$this->field_slug}_no_post_post_types" ); ?>
338
				</table>
339
			</td>
340
		</tr>
341
342
	<?php
343
	}
344
345
	/**
346
	 * Get unique user meta keys.
347
	 *
348
	 * @since 5.5
349
	 *
350
	 * @return array List of unique meta keys.
351
	 */
352
	protected function get_unique_user_meta_keys() {
353
		global $wpdb;
354
355
		return $wpdb->get_col( "SELECT DISTINCT(meta_key) FROM {$wpdb->prefix}usermeta ORDER BY meta_key" );
356
	}
357
358
	/**
359
	 * Exclude current user from being deleted.
360
	 *
361
	 * @param array $query WP_User_Query args.
362
	 *
363
	 * @return array Modified query args.
364
	 */
365
	protected function exclude_current_user( $query ) {
366
		$current_user_id = get_current_user_id();
367
368
		if ( $current_user_id <= 0 ) {
369
			return $query;
370
		}
371
372
		if ( isset( $query['exclude'] ) ) {
373
			$query['exclude'] = array_merge( $query['exclude'], array( $current_user_id ) );
374
		} else {
375
			$query['exclude'] = array( $current_user_id );
376
		}
377
378
		if ( isset( $query['include'] ) ) {
379
			$query['include'] = array_diff( $query['include'], $query['exclude'] );
380
			unset( $query['exclude'] );
381
		}
382
383
		return $query;
384
	}
385
386
	/**
387
	 * Exclude users from deletion.
388
	 *
389
	 * @since 6.0.0
390
	 *
391
	 * @param array $query Pre-built query.
392 68
	 *
393 68
	 * @return array Modified query.
394
	 */
395 68
	protected function exclude_users_from_deletion( array $query ) {
396 66
		/**
397
		 * Filter the list of user ids that will be excluded from deletion.
398
		 *
399 2
		 * @since 6.0.0
400
		 *
401
		 * @param array $excluded_ids User IDs to be excluded during deletion.
402 2
		 */
403
		$excluded_user_ids = apply_filters( 'bd_excluded_user_ids', array() );
404
405 2
		if ( is_array( $excluded_user_ids ) && ! empty( $excluded_user_ids ) ) {
406
			if ( isset( $query['exclude'] ) ) {
407
				$query['exclude'] = array_merge( $query['exclude'], $excluded_user_ids );
408
			} else {
409
				$query['exclude'] = $excluded_user_ids;
410 2
			}
411
		}
412
413
		if ( isset( $query['include'] ) ) {
414
			$query['include'] = array_diff( $query['include'], $query['exclude'] );
415
			unset( $query['exclude'] );
416
		}
417
418
		return $query;
419
	}
420
421
	/**
422 68
	 * Get Users ids from User logins.
423
	 *
424
	 * @param array $user_logins User Logins.
425
	 *
426
	 * @return array User ids.
427
	 */
428
	protected function get_user_ids_from_logins( $user_logins ) {
429
		$args = array(
430 68
			'fields'    => 'ID',
431
			'login__in' => $user_logins,
432 68
		);
433
434
		return get_users( $args );
435
	}
436
437
	/**
438
	 * Get Users ids from User emails.
439
	 *
440 68
	 * This is done in a batch of 500 since it involves a IN query.
441
	 *
442
	 * @param array $user_emails User emails.
443
	 *
444
	 * @return array User ids.
445 68
	 */
446
	protected function get_user_ids_from_emails( $user_emails ) {
447
		global $wpdb;
448
449
		$user_email_chunks = array_chunk( $user_emails, 500 );
450
451
		$user_ids = array();
452
453
		foreach ( $user_email_chunks as $user_email_chunk ) {
454
			$placeholders = array_fill( 0, count( $user_email_chunk ), '%s' );
455
			$format       = implode( ',', $placeholders );
456
457
			$query      = "SELECT ID FROM $wpdb->users WHERE user_email in ($format)";
458
			$user_ids[] = $wpdb->get_col( $wpdb->prepare( $query, $user_email_chunk ) );
459
		}
460
461
		return $user_ids;
462
	}
463
}
464