CoreSetting::get_user_roles()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 11
ccs 0
cts 9
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php namespace EmailLog\Core\UI\Setting;
2
3
use  \EmailLog\Core\UI\Page\SettingsPage;
0 ignored issues
show
Bug introduced by
The type \EmailLog\Core\UI\Page\SettingsPage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
4
5
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
6
7
/**
8
 * All Email Log Core settings.
9
 *
10
 * @since 2.1.0
11
 */
12
class CoreSetting extends Setting {
13
14
	protected function initialize() {
15
		$this->section->id          = 'email-log-core';
16
		$this->section->title       = __( 'Core Email Log Settings', 'email-log' );
17
		$this->section->option_name = 'email-log-core';
18
19
		$this->section->field_labels = array(
20
			'allowed_user_roles'    => __( 'Allowed User Roles', 'email-log' ),
21
			'remove_on_uninstall'   => __( 'Remove Data on Uninstall?', 'email-log' ),
22
			'hide_dashboard_widget' => __( 'Disable Dashboard Widget', 'email-log' ),
23
			'db_size_notification'  => __( 'Database Size Notification', 'email-log' ),
24
		);
25
26
		$this->section->default_value = array(
27
			'allowed_user_roles'    => array(),
28
			'remove_on_uninstall'   => '',
29
			'hide_dashboard_widget' => false,
30
			'db_size_notification'  => array(
31
				'notify'                    => false,
32
				'admin_email'               => '',
33
				'logs_threshold'            => '',
34
				'log_threshold_met'         => false,
35
				'threshold_email_last_sent' => false,
36
			),
37
		);
38
39
		$this->load();
40
	}
41
42
	/**
43
	 * Override `load` method so that the core settings are displayed first.
44
	 *
45
	 * @inheritdoc
46
	 */
47
	public function load() {
48
		add_filter( 'el_setting_sections', array( $this, 'register' ), 9 );
49
50
		add_action( 'add_option_' . $this->section->option_name, array( $this, 'allowed_user_roles_added' ), 10, 2 );
51
		add_action( 'update_option_' . $this->section->option_name, array( $this, 'allowed_user_roles_changed' ), 10, 2 );
52
53
		add_action( 'el_email_log_inserted', array( $this, 'verify_email_log_threshold' ) );
54
		add_action( 'el_trigger_notify_email_when_log_threshold_met', array( $this, 'trigger_threshold_met_notification_email' ) );
55
	}
56
57
	/**
58
	 * Renders the Email Log `Allowed User Roles` settings.
59
	 *
60
	 * @param array $args Arguments.
61
	 */
62
	public function render_allowed_user_roles_settings( $args ) {
63
		$option         = $this->get_value();
64
		$selected_roles = $option[ $args['id'] ];
65
66
		$field_name = $this->section->option_name . '[' . $args['id'] . '][]';
67
68
		$available_roles = get_editable_roles();
69
		unset( $available_roles['administrator'] );
70
		?>
71
72
		<p>
73
			<input type="checkbox" checked disabled><?php _e( 'Administrator', 'email-log' ); ?>
74
		</p>
75
76
		<?php foreach ( $available_roles as $role_id => $role ) : ?>
77
			<p>
78
				<input type="checkbox" name="<?php echo esc_attr( $field_name ); ?>" value="<?php echo esc_attr( $role_id ); ?>"
79
					<?php \EmailLog\Util\checked_array( $selected_roles, $role_id ); ?>>
80
81
				<?php echo $role['name']; ?>
82
			</p>
83
		<?php endforeach; ?>
84
85
		<p>
86
			<em>
87
				<?php _e( '<strong>Note:</strong> Users with the above User Roles can view Email Logs.', 'email-log' ); ?>
88
				<?php _e( 'Administrator role always has access and cannot be disabled.', 'email-log' ); ?>
89
			</em>
90
		</p>
91
92
		<?php
93
	}
94
95
	/**
96
	 * Sanitize allowed user roles setting.
97
	 *
98
	 * @param array $roles User selected user roles.
99
	 *
100
	 * @return array Sanitized user roles.
101
	 */
102
	public function sanitize_allowed_user_roles( $roles ) {
103
		if ( ! is_array( $roles ) ) {
0 ignored issues
show
introduced by
The condition is_array($roles) is always true.
Loading history...
104
			return array();
105
		}
106
107
		return array_map( 'sanitize_text_field', $roles );
108
	}
109
110
	/**
111
	 * Renders the Email Log `Remove Data on Uninstall?` settings.
112
	 *
113
	 * @param array $args
114
	 */
115
	public function render_remove_on_uninstall_settings( $args ) {
116
		$option      = $this->get_value();
117
		$remove_data = $option[ $args['id'] ];
118
119
		$field_name = $this->section->option_name . '[' . $args['id'] . ']';
120
		?>
121
122
		<input type="checkbox" name="<?php echo esc_attr( $field_name ); ?>" value="true" <?php checked( 'true', $remove_data ); ?>>
123
		<?php _e( 'Check this box if you would like to completely remove all of its data when the plugin is deleted.', 'email-log' ) ?>
124
125
		<p>
126
			<em>
127
				<?php printf(
128
					__( '<strong>Note:</strong> You can also export the Email Logs using our <a href="%s" rel="noopener noreferrer" target="_blank">Export Logs</a> add-on.', 'email-log' ),
129
					'https://wpemaillog.com/addons/export-logs/?utm_campaign=Upsell&utm_medium=wpadmin&utm_source=settings&utm_content=el'
130
				); ?>
131
			</em>
132
		</p>
133
134
		<?php
135
	}
136
137
	/**
138
	 * Sanitize Remove on uninstall value.
139
	 *
140
	 * @param string $value User entered value.
141
	 *
142
	 * @return string Sanitized value.
143
	 */
144
	public function sanitize_remove_on_uninstall( $value ) {
145
		return sanitize_text_field( $value );
146
	}
147
148
	/**
149
	 * Allowed user role list option is added.
150
	 *
151
	 * @param string $option Option name.
152
	 * @param array  $value  Option value.
153
	 */
154
	public function allowed_user_roles_added( $option, $value ) {
155
		$this->allowed_user_roles_changed( array(), $value );
156
	}
157
158
	/**
159
	 * Allowed user role list option was update.
160
	 *
161
	 * Change user role capabilities when the allowed user role list is changed.
162
	 *
163
	 * @param array $old_value Old Value.
164
	 * @param array $new_value New Value.
165
	 */
166
	public function allowed_user_roles_changed( $old_value, $new_value ) {
167
		$old_roles = $this->get_user_roles( $old_value );
168
		$new_roles = $this->get_user_roles( $new_value );
169
170
		/**
171
		 * The user roles who can manage email log list is changed.
172
		 *
173
		 * @since 2.1.0
174
		 *
175
		 * @param array $old_roles Old user roles.
176
		 * @param array $new_roles New user roles.
177
		 */
178
		do_action( 'el-log-list-manage-user-roles-changed', $old_roles, $new_roles );
179
	}
180
181
	/**
182
	 * Get User roles from option value.
183
	 *
184
	 * @access protected
185
	 *
186
	 * @param array $option Option value
187
	 *
188
	 * @return array User roles.
189
	 */
190
	protected function get_user_roles( $option ) {
191
		if ( ! array_key_exists( 'allowed_user_roles', $option ) ) {
192
			return array();
193
		}
194
195
		$user_roles = $option['allowed_user_roles'];
196
		if ( ! is_array( $user_roles ) ) {
197
			$user_roles = array( $user_roles );
198
		}
199
200
		return $user_roles;
201
	}
202
203
	/**
204
	 * Renders the Email Log `Remove Data on Uninstall?` settings.
205
	 *
206
	 * @param array $args
207
	 */
208
	public function render_hide_dashboard_widget_settings( $args ) {
209
		$option                = $this->get_value();
210
		$hide_dashboard_widget = $option[ $args['id'] ];
211
212
		$field_name = $this->section->option_name . '[' . $args['id'] . ']';
213
		?>
214
215
		<input type="checkbox" name="<?php echo esc_attr( $field_name ); ?>" value="true" <?php checked( 'true', $hide_dashboard_widget ); ?>>
216
		<?php _e( 'Check this box if you would like to disable dashboard widget.', 'email-log' ) ?>
217
218
		<p>
219
			<em>
220
				<?php printf(
221
					__( '<strong>Note:</strong> Each users can also disable dashboard widget using screen options', 'email-log' )
222
				); ?>
223
			</em>
224
		</p>
225
226
		<?php
227
	}
228
229
	/**
230
	 * Renders the Email Log `Database Size Notification` settings.
231
	 *
232
	 * @since 2.3.0
233
	 *
234
	 * @param array $args
235
	 */
236
	public function render_db_size_notification_settings( $args ) {
237
		$option                    = $this->get_value();
238
		$db_size_notification_data = $option[ $args['id'] ];
239
240
		$field_name = $this->section->option_name . '[' . $args['id'] . ']';
241
		// Since we store three different fields, give each field a unique name.
242
		$db_size_notification_field_name = $field_name . '[notify]';
243
		$admin_email_field_name          = $field_name . '[admin_email]';
244
		$logs_threshold_field_name       = $field_name . '[logs_threshold]';
245
246
		$email_log  = email_log();
247
		$logs_count = $email_log->table_manager->get_logs_count();
248
249
		$admin_email_input_field = sprintf(
250
			'<input type="email" name="%1$s" value="%2$s" size="35" />', esc_attr( $admin_email_field_name ), empty( $db_size_notification_data['admin_email'] ) ? get_option( 'admin_email', '' ) : esc_attr( $db_size_notification_data['admin_email'] ) );
0 ignored issues
show
Bug introduced by
It seems like empty($db_size_notificat...on_data['admin_email']) can also be of type false; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

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

250
			'<input type="email" name="%1$s" value="%2$s" size="35" />', esc_attr( $admin_email_field_name ), /** @scrutinizer ignore-type */ empty( $db_size_notification_data['admin_email'] ) ? get_option( 'admin_email', '' ) : esc_attr( $db_size_notification_data['admin_email'] ) );
Loading history...
251
252
		$logs_threshold_input_field = sprintf( '<input type="number" name="%1$s" placeholder="5000" value="%2$s" min="0" max="99999999" />',
253
			esc_attr( $logs_threshold_field_name ),
254
			empty( $db_size_notification_data['logs_threshold'] ) ? '' : esc_attr( $db_size_notification_data['logs_threshold'] )
255
		);
256
		?>
257
258
        <input type="checkbox" name="<?php echo esc_attr( $db_size_notification_field_name ); ?>" value="true" <?php
259
		checked( true, $db_size_notification_data['notify'] ); ?> />
260
		<?php
261
		// The values within each field are already escaped.
262
		printf( __( 'Notify %1$s if there are more than %2$s logs.', 'email-log' ),
263
			$admin_email_input_field,
264
			$logs_threshold_input_field
265
		);
266
		?>
267
        <p>
268
            <em>
269
				<?php printf(
270
					__( '%1$s There are %2$s email logs currently logged in the database.', 'email-log' ),
271
					'<strong>Note:</strong>',
272
					'<strong>' . esc_attr( $logs_count ) . '</strong>'
273
				); ?>
274
            </em>
275
        </p>
276
		<?php if ( ! empty( $db_size_notification_data['threshold_email_last_sent'] ) ) : ?>
277
            <p>
278
				<?php printf(
279
					__( 'Last notification email was sent on %1$s. Click %2$s button to reset sending the notification.', 'email-log' ),
280
					'<strong>' . get_date_from_gmt( date( 'Y-m-d H:i:s', $db_size_notification_data['threshold_email_last_sent'] ), \EmailLog\Util\get_user_defined_date_time_format() ) . '</strong>',
281
					'<b>Save</b>'
282
				); ?>
283
            </p>
284
		<?php
285
		endif;
286
		/**
287
		 * After DB size notification setting in Settings page.
288
		 *
289
		 * @since 2.4.0
290
		 */
291
		do_action( 'el_after_db_size_notification_setting' );
292
	}
293
294
	/**
295
	 * Removes any additional keys set other than the ones in db_size_notification array.
296
	 *
297
	 * @since 2.3.0
298
	 *
299
	 * @param array $arr `db_size_notification` option array.
300
	 *
301
	 * @return array `db_size_notification` option array with keys removed other than the allowed.
302
	 */
303
	protected function restrict_array_to_db_size_notification_setting_keys( $arr ) {
304
		$allowed_keys = array_keys( $this->section->default_value['db_size_notification'] );
305
		$arr_keys     = array_keys( $arr );
306
307
		// Return the array when only the allowed keys exist.
308
		$intersecting_keys = array_intersect( $allowed_keys, $arr_keys );
309
		if ( count( $allowed_keys ) === count( $intersecting_keys ) ) {
310
			return $arr;
311
		}
312
313
		// Otherwise remove keys that aren't expected.
314
		$diff_keys = array_diff_key( $arr, $allowed_keys );
315
		foreach ( $diff_keys as $key ) {
316
			unset( $arr[ $key ] );
317
		}
318
319
		return $arr;
320
	}
321
322
	/**
323
	 * Sanitizes the db_size_notification option.
324
	 *
325
	 * @since 2.3.0
326
	 *
327
	 * @param array $db_size_notification_data
328
	 *
329
	 * @return array $db_size_notification_data
330
	 */
331
	public function sanitize_db_size_notification( $db_size_notification_data ) {
332
		$db_size_notification_data = $this->restrict_array_to_db_size_notification_setting_keys( $db_size_notification_data );
333
334
		foreach ( $db_size_notification_data as $setting => $value ) {
335
			if ( 'notify' === $setting ) {
336
				$db_size_notification_data[ $setting ] = \filter_var( $value, FILTER_VALIDATE_BOOLEAN );
337
			} elseif ( 'admin_email' === $setting ) {
338
				$db_size_notification_data[ $setting ] = \sanitize_email( $value );
339
			} elseif ( 'logs_threshold' === $setting ) {
340
				$db_size_notification_data[ $setting ] = absint( \sanitize_text_field( $value ) );
341
			}
342
		}
343
344
		// wp_parse_args won't merge nested array keys. So add the key here if it is not set.
345
		if ( ! array_key_exists( 'notify', $db_size_notification_data ) ) {
346
			$db_size_notification_data['notify'] = false;
347
		}
348
		if ( ! array_key_exists( 'log_threshold_met', $db_size_notification_data ) ) {
349
			$db_size_notification_data['log_threshold_met'] = false;
350
		}
351
		if ( ! array_key_exists( 'threshold_email_last_sent', $db_size_notification_data ) ) {
352
			$db_size_notification_data['threshold_email_last_sent'] = false;
353
		}
354
355
		return $db_size_notification_data;
356
	}
357
358
	/**
359
	 * Triggers the Cron to notify admin via email.
360
	 *
361
	 * Email is triggered only when the threshold setting is met.
362
	 *
363
	 * @since 2.3.0
364
	 */
365
	public function verify_email_log_threshold() {
366
		$cron_hook = 'el_trigger_notify_email_when_log_threshold_met';
367
		if ( ! wp_next_scheduled( $cron_hook ) ) {
368
			wp_schedule_event( time(), 'hourly', $cron_hook );
369
		}
370
	}
371
372
	/**
373
	 * Utility method to verify all the given keys exist in the given array.
374
	 *
375
	 * This method helps reduce the Cyclomatic Complexity in its parent method.
376
	 *
377
	 * @since 2.3.0
378
	 *
379
	 * @param array $arr  The array whose keys must be checked.
380
	 * @param array $keys All the required keys that the array must contain.
381
	 *
382
	 * @return bool
383
	 */
384
	protected function has_array_contains_required_keys( $arr, $keys ) {
385
		$has_keys = true;
386
387
		if ( ! is_array( $arr ) || ! is_array( $keys ) ) {
0 ignored issues
show
introduced by
The condition is_array($arr) is always true.
Loading history...
introduced by
The condition is_array($keys) is always true.
Loading history...
388
			return false;
389
		}
390
391
		foreach ( $arr as $key => $value ) {
392
			$has_keys = $has_keys && in_array( $key, $keys, true );
393
		}
394
395
		return $has_keys;
396
	}
397
398
	/**
399
	 * Send the Threshold notification email to the admin.
400
	 *
401
	 * @since 2.3.0
402
	 */
403
	public function trigger_threshold_met_notification_email() {
404
		$email_log  = email_log();
405
		$logs_count = absint( $email_log->table_manager->get_logs_count() );
406
407
		$setting_data = $this->get_value();
408
409
		// Return early.
410
		if ( ! array_key_exists( 'db_size_notification', $setting_data ) ) {
411
			return;
412
		}
413
414
		$db_size_notification_key  = 'db_size_notification';
415
		$db_size_notification_data = $setting_data[ $db_size_notification_key ];
416
417
		// Return early.
418
		$keys = array_keys( $this->section->default_value['db_size_notification'] );
419
		if ( ! $this->has_array_contains_required_keys( $db_size_notification_data, $keys ) ) {
420
			return;
421
		}
422
423
		$is_notification_enabled = $db_size_notification_data['notify'];
424
		$admin_email             = $db_size_notification_data['admin_email'];
425
		$logs_threshold          = absint( $db_size_notification_data['logs_threshold'] );
426
		$logs_threshold_met      = $db_size_notification_data['log_threshold_met'];
427
428
		// Ideally threshold cannot be 0. Also, skip sending email if it is already sent.
429
		if ( 0 === $logs_threshold || true === $logs_threshold_met ) {
430
			return;
431
		}
432
433
		if ( $logs_count < $logs_threshold ) {
434
			return;
435
		}
436
437
		$this->register_threshold_met_admin_notice();
438
439
		if ( $is_notification_enabled && is_email( $admin_email ) ) {
440
			$subject = sprintf( __( 'Email Log Plugin: Your log threshold of %s has been met', 'email-log' ), $logs_threshold );
441
			$message = <<<EOT
442
<p>This email is generated by the Email Log plugin.</p>
443
<p>Your log threshold of $logs_threshold has been met. You may manually delete the logs to keep your database table in size.</p>
444
<p>Also, consider using our <a href="https://wpemaillog.com/addons/auto-delete-logs/">Auto Delete Logs</a> plugin to delete the logs automatically.</p>
445
EOT;
446
			$headers = array( 'Content-Type: text/html; charset=UTF-8' );
447
448
			/**
449
			 * Filters Log threshold notification email subject.
450
			 *
451
			 * @since 2.3.0
452
			 *
453
			 * @param string $subject The email subject.
454
			 */
455
			$subject = apply_filters( 'el_log_threshold_met_notification_email_subject', $subject );
456
457
			/**
458
			 * Filters Log threshold notification email body.
459
			 *
460
			 * @since 2.3.0
461
			 *
462
			 * @param string $message        The email body.
463
			 * @param int    $logs_threshold The log threshold value set by the user.
464
			 */
465
			$message = apply_filters( 'el_log_threshold_met_notification_email_body', $message, $logs_threshold );
466
467
			wp_mail( $admin_email, $subject, $message, $headers );
468
469
			$setting_data[ $db_size_notification_key ]['log_threshold_met']         = true;
470
			$setting_data[ $db_size_notification_key ]['threshold_email_last_sent'] = time();
471
			\update_option( $this->section->option_name, $setting_data );
472
		}
473
	}
474
475
	/**
476
	 * Registers the Email Log threshold met admin notice.
477
	 *
478
	 * @since 2.3.0
479
	 */
480
	public function register_threshold_met_admin_notice() {
481
		add_action( 'admin_notices', array( $this, 'render_log_threshold_met_notice' ) );
482
	}
483
484
	/**
485
	 * Displays the Email Log threshold met admin notice.
486
	 *
487
	 * @since 2.3.0
488
	 */
489
	public function render_log_threshold_met_notice() {
490
		$email_log      = email_log();
491
		$logs_count     = absint( $email_log->table_manager->get_logs_count() );
492
		$notice_message = sprintf( __( 'Currently there are %1$s logged, which is more than the threshold that is set in the %2$s screen. You can delete some logs or increase the threshold. You can also use our %3$s add-on to automatically delete logs', 'email-log' ),
493
			$logs_count . _n( ' email log', ' email logs', $logs_count, 'email-log' ),
494
			'<a href="' . esc_url( admin_url( 'admin.php?page=' . SettingsPage::PAGE_SLUG ) ) . '">settings</a> screen',
495
			'<a href="' . esc_url( 'https://wpemaillog.com/addons/auto-delete-logs/' ) . '">Auto Delete Logs</a>'
496
			 );
497
		?>
498
        <div class="notice notice-warning is-dismissible">
499
            <p><?php echo $notice_message; ?></p>
500
        </div>
501
		<?php
502
	}
503
504
}
505