Passed
Push — 189-feature/include-settings-m... ( e9909d...7763f0 )
by Sudar
02:55
created

CoreSetting::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php namespace EmailLog\Core\UI\Setting;
2
3
use  \EmailLog\Core\UI\Page\SettingsPage;
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 $args of sprintf() does only seem to accept 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 endif; ?>
285
		<?php
286
	}
287
288
	/**
289
	 * Removes any additional keys set other than the ones in db_size_notification array.
290
	 *
291
	 * @since 2.3.0
292
	 *
293
	 * @param array $arr `db_size_notification` option array.
294
	 *
295
	 * @return array `db_size_notification` option array with keys removed other than the allowed.
296
	 */
297
	protected function restrict_array_to_db_size_notification_setting_keys( $arr ) {
298
		$allowed_keys = array_keys( $this->section->default_value['db_size_notification'] );
299
		$arr_keys     = array_keys( $arr );
300
301
		// Return the array when only the allowed keys exist.
302
		$intersecting_keys = array_intersect( $allowed_keys, $arr_keys );
303
		if ( count( $allowed_keys ) === count( $intersecting_keys ) ) {
304
			return $arr;
305
		}
306
307
		// Otherwise remove keys that aren't expected.
308
		$diff_keys = array_diff_key( $arr, $allowed_keys );
309
		foreach ( $diff_keys as $key ) {
310
			unset( $arr[ $key ] );
311
		}
312
313
		return $arr;
314
	}
315
316
	/**
317
	 * Sanitizes the db_size_notification option.
318
	 *
319
	 * @since 2.3.0
320
	 *
321
	 * @param array $db_size_notification_data
322
	 *
323
	 * @return array $db_size_notification_data
324
	 */
325
	public function sanitize_db_size_notification( $db_size_notification_data ) {
326
		$db_size_notification_data = $this->restrict_array_to_db_size_notification_setting_keys( $db_size_notification_data );
327
328
		foreach ( $db_size_notification_data as $setting => $value ) {
329
			if ( 'notify' === $setting ) {
330
				$db_size_notification_data[ $setting ] = \filter_var( $value, FILTER_VALIDATE_BOOLEAN );
331
			} elseif ( 'admin_email' === $setting ) {
332
				$db_size_notification_data[ $setting ] = \sanitize_email( $value );
333
			} elseif ( 'logs_threshold' === $setting ) {
334
				$db_size_notification_data[ $setting ] = absint( \sanitize_text_field( $value ) );
335
			}
336
		}
337
338
		// wp_parse_args won't merge nested array keys. So add the key here if it is not set.
339
		if ( ! array_key_exists( 'notify', $db_size_notification_data ) ) {
340
			$db_size_notification_data['notify'] = false;
341
		}
342
		if ( ! array_key_exists( 'log_threshold_met', $db_size_notification_data ) ) {
343
			$db_size_notification_data['log_threshold_met'] = false;
344
		}
345
		if ( ! array_key_exists( 'threshold_email_last_sent', $db_size_notification_data ) ) {
346
			$db_size_notification_data['threshold_email_last_sent'] = false;
347
		}
348
349
		return $db_size_notification_data;
350
	}
351
352
	/**
353
	 * Triggers the Cron to notify admin via email.
354
	 *
355
	 * Email is triggered only when the threshold setting is met.
356
	 *
357
	 * @since 2.3.0
358
	 */
359
	public function verify_email_log_threshold() {
360
		$cron_hook = 'el_trigger_notify_email_when_log_threshold_met';
361
		if ( ! wp_next_scheduled( $cron_hook ) ) {
362
			wp_schedule_event( time(), 'hourly', $cron_hook );
363
		}
364
	}
365
366
	/**
367
	 * Utility method to verify all the given keys exist in the given array.
368
	 *
369
	 * This method helps reduce the Cyclomatic Complexity in its parent method.
370
	 *
371
	 * @since 2.3.0
372
	 *
373
	 * @param array $arr  The array whose keys must be checked.
374
	 * @param array $keys All the required keys that the array must contain.
375
	 *
376
	 * @return bool
377
	 */
378
	protected function has_array_contains_required_keys( $arr, $keys ) {
379
		$has_keys = true;
380
381
		if ( ! is_array( $arr ) || ! is_array( $keys ) ) {
0 ignored issues
show
introduced by
The condition is_array($keys) is always true.
Loading history...
introduced by
The condition is_array($arr) is always true.
Loading history...
382
			return false;
383
		}
384
385
		foreach ( $arr as $key => $value ) {
386
			$has_keys = $has_keys && in_array( $key, $keys, true );
387
		}
388
389
		return $has_keys;
390
	}
391
392
	/**
393
	 * Send the Threshold notification email to the admin.
394
	 *
395
	 * @since 2.3.0
396
	 */
397
	public function trigger_threshold_met_notification_email() {
398
		$email_log  = email_log();
399
		$logs_count = absint( $email_log->table_manager->get_logs_count() );
400
401
		$setting_data = $this->get_value();
402
403
		// Return early.
404
		if ( ! array_key_exists( 'db_size_notification', $setting_data ) ) {
405
			return;
406
		}
407
408
		$db_size_notification_key  = 'db_size_notification';
409
		$db_size_notification_data = $setting_data[ $db_size_notification_key ];
410
411
		// Return early.
412
		$keys = array_keys( $this->section->default_value['db_size_notification'] );
413
		if ( ! $this->has_array_contains_required_keys( $db_size_notification_data, $keys ) ) {
414
			return;
415
		}
416
417
		$is_notification_enabled = $db_size_notification_data['notify'];
418
		$admin_email             = $db_size_notification_data['admin_email'];
419
		$logs_threshold          = absint( $db_size_notification_data['logs_threshold'] );
420
		$logs_threshold_met      = $db_size_notification_data['log_threshold_met'];
421
422
		// Ideally threshold cannot be 0. Also, skip sending email if it is already sent.
423
		if ( 0 === $logs_threshold || true === $logs_threshold_met ) {
424
			return;
425
		}
426
427
		if ( $logs_count < $logs_threshold ) {
428
			return;
429
		}
430
431
		$this->register_threshold_met_admin_notice();
432
433
		if ( $is_notification_enabled && is_email( $admin_email ) ) {
434
			$subject = sprintf( __( 'Email Log Plugin: Your log threshold of %s has been met', 'email-log' ), $logs_threshold );
435
			$message = <<<EOT
436
<p>This email is generated by the Email Log plugin.</p>
437
<p>Your log threshold of $logs_threshold has been met. You may manually delete the logs to keep your database table in size.</p>
438
<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>
439
EOT;
440
			$headers = array( 'Content-Type: text/html; charset=UTF-8' );
441
442
			/**
443
			 * Filters Log threshold notification email subject.
444
			 *
445
			 * @since 2.3.0
446
			 *
447
			 * @param string $subject The email subject.
448
			 */
449
			$subject = apply_filters( 'el_log_threshold_met_notification_email_subject', $subject );
450
451
			/**
452
			 * Filters Log threshold notification email body.
453
			 *
454
			 * @since 2.3.0
455
			 *
456
			 * @param string $message        The email body.
457
			 * @param int    $logs_threshold The log threshold value set by the user.
458
			 */
459
			$message = apply_filters( 'el_log_threshold_met_notification_email_body', $message, $logs_threshold );
460
461
			wp_mail( $admin_email, $subject, $message, $headers );
462
463
			$setting_data[ $db_size_notification_key ]['log_threshold_met']         = true;
464
			$setting_data[ $db_size_notification_key ]['threshold_email_last_sent'] = time();
465
			\update_option( $this->section->option_name, $setting_data );
466
		}
467
	}
468
469
	/**
470
	 * Registers the Email Log threshold met admin notice.
471
	 *
472
	 * @since 2.3.0
473
	 */
474
	public function register_threshold_met_admin_notice() {
475
		add_action( 'admin_notices', array( $this, 'render_log_threshold_met_notice' ) );
476
	}
477
478
	/**
479
	 * Displays the Email Log threshold met admin notice.
480
	 *
481
	 * @since 2.3.0
482
	 */
483
	public function render_log_threshold_met_notice() {
484
		$email_log      = email_log();
485
		$logs_count     = absint( $email_log->table_manager->get_logs_count() );
486
		$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' ),
487
			$logs_count . _n( ' email log', ' email logs', $logs_count, 'email-log' ),
488
			'<a href="' . esc_url( admin_url( 'admin.php?page=' . SettingsPage::PAGE_SLUG ) ) . '">settings</a> screen',
489
			'<a href="' . esc_url( 'https://wpemaillog.com/addons/auto-delete-logs/' ) . '">Auto Delete Logs</a>'
490
			 );
491
		?>
492
        <div class="notice notice-warning is-dismissible">
493
            <p><?php echo $notice_message; ?></p>
494
        </div>
495
		<?php
496
	}
497
498
}
499