Completed
Push — 717-fix/add-tests-for-posts-de... ( 41a87a...780d20 )
by Sudar
09:45 queued 06:22
created

UsersModule::delete_users()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.1308

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 1
b 0
f 0
nc 10
nop 2
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
crap 6.1308
rs 9.2222
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 44
			if ( isset( $options['reassign_user'] ) && $options['reassign_user'] ) {
86
				$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

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