Completed
Pull Request — fix/706-generic-operators-logi... (#715)
by
unknown
74:28 queued 71:13
created

UsersModule::delete_users_from_query()   B

Complexity

Conditions 9
Paths 16

Size

Total Lines 43
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9.3752

Importance

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