Passed
Pull Request — dev/6.1.0 (#725)
by Sudar
03:51
created

UsersModule::delete_users()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 34
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.392

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
c 2
b 0
f 0
nc 12
nop 2
dl 0
loc 34
ccs 12
cts 15
cp 0.8
crap 7.392
rs 8.8333
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
		if ( $options['login_restrict'] || $options['no_posts'] ) {
62 17
			return $this->delete_users_from_query( $query, $options );
63
		}
64
65 50
		return $this->delete_users( $query, $options );
66
	}
67
68
	/**
69
	 * Optimised delete users.
70
	 *
71
	 * @param array $query   Query options.
72
	 * @param array $options Delete options.
73
	 *
74
	 * @return int $count Deleted users count.
75
	 */
76 50
	protected function delete_users( $query, $options ) {
77 50
		$count           = 0;
78 50
		$query['fields'] = 'ID';
79 50
		$user_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
		foreach ( $user_ids as $user_id ) {
85
			/**
86
			 * Can a user be deleted.
87
			 *
88
			 * @since 6.0.0
89
			 *
90
			 * @param bool                                             Can Delete the User. (Default true)
91
			 * @param int                                     $user_id User ID of the user who is about to be deleted.
92
			 * @param array                                   $options Delete options.
93
			 * @param \BulkWP\BulkDelete\Core\Base\BaseModule $this    Module that is triggering deletion.
94
			 */
95 44
			if ( ! apply_filters( 'bd_can_delete_user', true, $user_id, $options, $this ) ) {
96
				continue;
97
			}
98 44
			if ( isset( $options['reassign_user'] ) && $options['reassign_user'] ) {
99
				$deleted = wp_delete_user( $user_id, $options['reassign_user_id'] );
0 ignored issues
show
Bug introduced by
$user_id of type WP_User is incompatible with the type integer expected by parameter $id of wp_delete_user(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

99
				$deleted = wp_delete_user( /** @scrutinizer ignore-type */ $user_id, $options['reassign_user_id'] );
Loading history...
100
			} else {
101 44
				$deleted = wp_delete_user( $user_id );
102
			}
103
104 44
			if ( $deleted ) {
105 44
				$count ++;
106
			}
107
		}
108
109 50
		return $count;
110
	}
111
112
	/**
113
	 * Query and Delete users.
114
	 *
115
	 * @since  5.5.2
116
	 * @access protected
117
	 *
118
	 * @param array $query   Options to query users.
119
	 * @param array $options Delete options.
120
	 *
121
	 * @return int Number of users who were deleted.
122
	 */
123 26
	protected function delete_users_from_query( $query, $options ) {
124 26
		$count = 0;
125 26
		$users = $this->query_users( $query );
126
127 26
		if ( ! function_exists( 'wp_delete_user' ) ) {
128
			require_once ABSPATH . 'wp-admin/includes/user.php';
129
		}
130
131 26
		foreach ( $users as $user ) {
132 25
			if ( ! $this->can_delete_by_logged_date( $options, $user ) ) {
133
				continue;
134
			}
135
136 25
			if ( ! $this->can_delete_by_post_count( $options, $user ) ) {
137 13
				continue;
138
			}
139
140
			/**
141
			 * Can a user be deleted.
142
			 *
143
			 * @since 6.0.0
144
			 *
145
			 * @param bool                                             Can Delete the User. (Default true)
146
			 * @param int                                     $user    User ID of the user who is about to be deleted.
147
			 * @param array                                   $options Delete options.
148
			 * @param \BulkWP\BulkDelete\Core\Base\BaseModule $this    Module that is triggering deletion.
149
			 */
150 23
			if ( ! apply_filters( 'bd_can_delete_user', true, $user->ID, $options, $this ) ) {
151
				continue;
152
			}
153
154 23
			if ( isset( $options['reassign_user'] ) && $options['reassign_user'] ) {
155 1
				$deleted = wp_delete_user( $user->ID, $options['reassign_user_id'] );
156
			} else {
157 22
				$deleted = wp_delete_user( $user->ID );
158
			}
159
160 23
			if ( $deleted ) {
161 23
				$count ++;
162
			}
163
		}
164
165 26
		return $count;
166
	}
167
168
	/**
169
	 * Query users using options.
170
	 *
171
	 * @param array $options Query options.
172
	 *
173
	 * @return \WP_User[] List of users.
174
	 */
175 75
	protected function query_users( $options ) {
176
		$defaults = array(
177 75
			'count_total' => false,
178
		);
179
180 75
		$options = wp_parse_args( $options, $defaults );
181
182 75
		$wp_user_query = new \WP_User_Query( $options );
183
184
		/**
185
		 * This action before the query happens.
186
		 *
187
		 * @since 6.0.0
188
		 *
189
		 * @param \WP_User_Query $wp_user_query Query object.
190
		 */
191 75
		do_action( 'bd_before_query', $wp_user_query );
192
193 75
		$users = (array) $wp_user_query->get_results();
194
195
		/**
196
		 * This action runs after the query happens.
197
		 *
198
		 * @since 6.0.0
199
		 *
200
		 * @param \WP_User_Query $wp_user_query Query object.
201
		 */
202 75
		do_action( 'bd_after_query', $wp_user_query );
203
204 75
		return $users;
205
	}
206
207
	/**
208
	 * Can the user be deleted based on the 'post count' option?
209
	 *
210
	 * This doesn't work well in batches.
211
	 *
212
	 * @link https://github.com/sudar/bulk-delete/issues/511 Github issue.
213
	 * @since  5.5.2
214
	 * @access protected
215
	 *
216
	 * @param array    $delete_options Delete Options.
217
	 * @param \WP_User $user           User object that needs to be deleted.
218
	 *
219
	 * @return bool True if the user can be deleted, false otherwise.
220
	 */
221 25
	protected function can_delete_by_post_count( $delete_options, $user ) {
222
		return ! (
223 25
			$delete_options['no_posts'] &&
224 25
			count_user_posts( $user->ID, $delete_options['no_posts_post_types'] ) > 0
225
		);
226
	}
227
228
	/**
229
	 * Get the date query part for WP_User_Query.
230
	 *
231
	 * Date query corresponds to user registered date.
232
	 *
233
	 * @since 6.0.0
234
	 *
235
	 * @param array $options Delete options.
236
	 *
237
	 * @return array Date Query.
238
	 */
239 70
	protected function get_date_query( $options ) {
240 70
		if ( ! $options['registered_restrict'] ) {
241 41
			return array();
242
		}
243
244 29
		if ( $options['registered_days'] <= 0 ) {
245 1
			return array();
246
		}
247
248 28
		if ( ! isset( $options['registered_date_op'] ) ) {
249
			return array(
250 24
				'before' => $options['registered_days'] . ' days ago',
251
			);
252
		}
253
254 4
		if ( 'before' === $options['registered_date_op'] || 'after' === $options['registered_date_op'] ) {
255
			return array(
256 4
				$options['registered_date_op'] => $options['registered_days'] . ' days ago',
257
			);
258
		}
259
260
		return array();
261
	}
262
263
	/**
264
	 * Can the user be deleted based on the 'logged in date' option?
265
	 *
266
	 * This doesn't work well in batches.
267
	 *
268
	 * @link https://github.com/sudar/bulk-delete/issues/511 Github issue.
269
	 * @since  5.5.2
270
	 * @access protected
271
	 *
272
	 * @param array    $delete_options Delete Options.
273
	 * @param \WP_User $user           User object that needs to be deleted.
274
	 *
275
	 * @return bool True if the user can be deleted, false otherwise.
276
	 */
277 25
	protected function can_delete_by_logged_date( $delete_options, $user ) {
278 25
		if ( $delete_options['login_restrict'] ) {
279
			$login_days = $delete_options['login_days'];
280
			$last_login = bd_get_last_login( $user->ID );
281
282
			if ( null !== $last_login ) {
0 ignored issues
show
introduced by
The condition null !== $last_login is always true.
Loading history...
283
				// we have a logged-in entry for the user in simple login log plugin.
284
				if ( strtotime( $last_login ) > strtotime( '-' . $login_days . 'days' ) ) {
285
					return false;
286
				}
287
			} else {
288
				// we don't have a logged-in entry for the user in simple login log plugin.
289
				if ( $login_days > 0 ) {
290
					// non-zero value for login date. So don't delete this user.
291
					return false;
292
				}
293
			}
294
		}
295
296 25
		return true;
297
	}
298
299
	/**
300
	 * Render User Login restrict settings.
301
	 *
302
	 * @since 5.5
303
	 * @since 6.2.0 Added $show_login_filter param.
304
	 *
305
	 * @param bool $show_login_filter True/False.
306
	 */
307
	protected function render_user_login_restrict_settings( $show_login_filter = true ) {
308
		?>
309
		<tr>
310
			<td scope="row" colspan="2">
311
				<label for="smbd_<?php echo esc_attr( $this->field_slug ); ?>_registered_restrict">
312
					<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">
313
					<?php _e( 'Restrict to users who are registered in the site ', 'bulk-delete' ); ?>
314
				</label>
315
				<select name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_op" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_op" disabled>
316
					<option value="before"><?php _e( 'for at least', 'bulk-delete' ); ?></option>
317
					<option value="after"><?php _e( 'in the last', 'bulk-delete' ); ?></option>
318
				</select>
319
				<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' ); ?>
320
			</td>
321
		</tr>
322
		<?php if ( $show_login_filter ) : ?>
323
		<tr>
324
			<td scope="row" colspan="2">
325
				<label>
326
					<input name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_restrict" id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_login_restrict"
327
							value="true" type="checkbox" <?php disabled( false, bd_is_simple_login_log_present() ); ?>>
328
					<?php _e( 'Restrict to users who have not logged in the last ', 'bulk-delete' ); ?>
329
				</label>
330
				<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' ); ?>.
331
332
				<?php if ( ! bd_is_simple_login_log_present() ) : ?>
333
					<span style = "color:red">
334
						<?php _e( 'Need the free "Simple Login Log" Plugin', 'bulk-delete' ); ?> <a href = "https://wordpress.org/plugins/simple-login-log/">Install now</a>
335
					</span>
336
				<?php endif; ?>
337
			</td>
338
		</tr>
339
340
			<?php if ( bd_is_simple_login_log_present() ) : ?>
341
			<tr>
342
				<td scope="row" colspan="2">
343
					<?php _e( 'Enter "0 days" to delete users who have never logged in after the "Simple Login Log" plugin has been installed.', 'bulk-delete' ); ?>
344
			</tr>
345
			<?php endif; ?>
346
		<?php endif; ?>
347
		<?php
348
	}
349
350
	/**
351
	 * Render delete user with no posts settings.
352
	 *
353
	 * @since 5.5
354
	 */
355
	protected function render_user_with_no_posts_settings() {
356
	?>
357
		<tr>
358
			<td scope="row" colspan="2">
359
				<input type="checkbox" value="true"
360
						name="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts"
361
						id="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts" class="user_restrict_to_no_posts_filter">
362
				<label for="smbd_<?php echo esc_attr( $this->field_slug ); ?>_no_posts">
363
					<?php _e( "Restrict to users who don't have any posts.", 'bulk-delete' ); ?>
364
				</label>
365
			</td>
366
		</tr>
367
368
		<tr class="user_restrict_to_no_posts_filter_items visually-hidden">
369
			<td scope="row" colspan="2">
370
				<table class="filter-items">
371
					<tr>
372
						<td scope="row">
373
							<?php _e( 'Select the post types. By default all post types are considered.', 'bulk-delete' ); ?>
374
						</td>
375
					</tr>
376
377
					<?php $this->render_post_type_checkboxes( "smbd_{$this->field_slug}_no_post_post_types" ); ?>
378
				</table>
379
			</td>
380
		</tr>
381
382
	<?php
383
	}
384
385
	/**
386
	 * Get unique user meta keys.
387
	 *
388
	 * @since 5.5
389
	 *
390
	 * @return array List of unique meta keys.
391
	 */
392
	protected function get_unique_user_meta_keys() {
393
		global $wpdb;
394
395
		return $wpdb->get_col( "SELECT DISTINCT(meta_key) FROM {$wpdb->prefix}usermeta ORDER BY meta_key" );
396
	}
397
398
	/**
399
	 * Exclude current user from being deleted.
400
	 *
401
	 * @param array $query WP_User_Query args.
402
	 *
403
	 * @return array Modified query args.
404
	 */
405 68
	protected function exclude_current_user( $query ) {
406 68
		$current_user_id = get_current_user_id();
407
408 68
		if ( $current_user_id <= 0 ) {
409 66
			return $query;
410
		}
411
412 2
		if ( isset( $query['exclude'] ) ) {
413
			$query['exclude'] = array_merge( $query['exclude'], array( $current_user_id ) );
414
		} else {
415 2
			$query['exclude'] = array( $current_user_id );
416
		}
417
418 2
		if ( isset( $query['include'] ) ) {
419
			$query['include'] = array_diff( $query['include'], $query['exclude'] );
420
			unset( $query['exclude'] );
421
		}
422
423 2
		return $query;
424
	}
425
426
	/**
427
	 * Exclude users from deletion.
428
	 *
429
	 * @since 6.0.0
430
	 *
431
	 * @param array $query Pre-built query.
432
	 *
433
	 * @return array Modified query.
434
	 */
435 68
	protected function exclude_users_from_deletion( array $query ) {
436
		/**
437
		 * Filter the list of user ids that will be excluded from deletion.
438
		 *
439
		 * @since 6.0.0
440
		 *
441
		 * @param array $excluded_ids User IDs to be excluded during deletion.
442
		 */
443 68
		$excluded_user_ids = apply_filters( 'bd_excluded_user_ids', array() );
444
445 68
		if ( is_array( $excluded_user_ids ) && ! empty( $excluded_user_ids ) ) {
446
			if ( isset( $query['exclude'] ) ) {
447
				$query['exclude'] = array_merge( $query['exclude'], $excluded_user_ids );
448
			} else {
449
				$query['exclude'] = $excluded_user_ids;
450
			}
451
		}
452
453 68
		if ( isset( $query['include'] ) ) {
454
			$query['include'] = array_diff( $query['include'], $query['exclude'] );
455
			unset( $query['exclude'] );
456
		}
457
458 68
		return $query;
459
	}
460
461
	/**
462
	 * Get Users ids from User logins.
463
	 *
464
	 * @param array $user_logins User Logins.
465
	 *
466
	 * @return array User ids.
467
	 */
468
	protected function get_user_ids_from_logins( $user_logins ) {
469
		$args = array(
470
			'fields'    => 'ID',
471
			'login__in' => $user_logins,
472
		);
473
474
		return get_users( $args );
475
	}
476
477
	/**
478
	 * Get Users ids from User emails.
479
	 *
480
	 * This is done in a batch of 500 since it involves a IN query.
481
	 *
482
	 * @param array $user_emails User emails.
483
	 *
484
	 * @return array User ids.
485
	 */
486
	protected function get_user_ids_from_emails( $user_emails ) {
487
		global $wpdb;
488
489
		$user_email_chunks = array_chunk( $user_emails, 500 );
490
491
		$user_ids = array();
492
493
		foreach ( $user_email_chunks as $user_email_chunk ) {
494
			$placeholders = array_fill( 0, count( $user_email_chunk ), '%s' );
495
			$format       = implode( ',', $placeholders );
496
497
			$query      = "SELECT ID FROM $wpdb->users WHERE user_email in ($format)";
498
			$user_ids[] = $wpdb->get_col( $wpdb->prepare( $query, $user_email_chunk ) );
499
		}
500
501
		return $user_ids;
502
	}
503
}
504