Completed
Push — 19-feature/export-logs-in-batc... ( bca245...a346a8 )
by Sudar
09:44 queued 05:40
created

stringify()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 6
ccs 2
cts 3
cp 0.6667
crap 2.1481
rs 10
1
<?php namespace EmailLog\Util;
2
3
/**
4
 * Email Log Helper functions.
5
 * Some of these functions would be used the addons.
6
 */
7
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
8
9
/**
10
 * Perform additional sanitation of emails.
11
 *
12
 * @since 1.9
13
 *
14
 * @param string $email    Email string to be sanitized.
15
 * @param bool   $multiple (Optional) Should multiple emails be allowed. True by default.
16
 *
17
 * @return string Sanitized email.
18
 */
19
function sanitize_email( $email, $multiple = true ) {
20 13
	$emails = explode( ',', $email );
21 13
	if ( ! $multiple ) {
22 3
		$emails = array_slice( $emails, 0, 1 );
23 3
	}
24
25 13
	$cleaned_emails = array_map( __NAMESPACE__ . '\\sanitize_email_with_name', $emails );
26
27 13
	return implode( ', ', $cleaned_emails );
28
}
29
30
/**
31
 * Sanitize email with name.
32
 *
33
 * @since 1.9
34
 *
35
 * @param string $string Email string to be sanitized.
36
 *
37
 * @return string Sanitized email.
38
 */
39
function sanitize_email_with_name( $string ) {
40 13
	$string = trim( $string );
41
42 13
	$bracket_pos = strpos( $string, '<' );
43 13
	if ( false !== $bracket_pos ) {
44 5
		if ( $bracket_pos > 0 ) {
45 5
			$name = substr( $string, 0, $bracket_pos );
46 5
			$name = trim( $name );
47
48 5
			$email = substr( $string, $bracket_pos + 1 );
49 5
			$email = str_replace( '>', '', $email );
50
51 5
			return sanitize_text_field( $name ) . ' <' . \sanitize_email( $email ) . '>';
52
		}
53
	}
54
55 8
	return \sanitize_email( $string );
56
}
57
58
/**
59
 * Gets the columns to export logs.
60
 *
61
 * If the More Fields add-on is active, additional columns are returned.
62
 *
63
 * @since 2.0.0
64
 *
65
 * @return string[] List of Columns to export.
66
 */
67
function get_log_columns_to_export() {
68
69
	if ( is_plugin_active( 'email-log-more-fields/email-log-more-fields.php' ) ) {
70
		return array( 'id', 'sent_date', 'to_email', 'subject', 'from', 'cc', 'bcc', 'reply-to', 'attachment' );
71
	}
72
73
	return array( 'id', 'sent_date', 'to_email', 'subject' );
74
}
75
76
/**
77
 * Is it an admin request and not an ajax request.
78
 *
79
 * @since 2.1
80
 *
81
 * @return bool True if admin non ajax request, False otherwise.
82
 */
83
function is_admin_non_ajax_request() {
84
	if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) {
85
		return false;
86
	}
87
88
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
89
		return false;
90
	}
91
92
	return is_admin();
93
}
94
95
/**
96
 * Checks the Checkbox when values are present in a given array.
97
 *
98
 * Use this function in Checkbox fields.
99
 *
100
 * @since 2.1.0
101
 *
102
 * @param array  $values  List of all possible values.
103
 * @param string $current The current value to be checked.
104
 */
105
function checked_array( $values, $current ) {
106 2
	if ( ! is_array( $values ) ) {
107 1
		return;
108
	}
109
110 1
	if ( in_array( $current, $values ) ) {
111 1
		echo "checked='checked'";
112 1
	}
113 1
}
114
115
/**
116
 * Stringify arrays.
117
 *
118
 * If the parameter is an array, then return delimiter separated values of the array.
119
 * Otherwise return the parameter.
120
 *
121
 * @since 2.3.0
122
 * @since 2.3.2 Renamed name to `Stringify`.
123
 *
124
 * @param array|string $may_be_array The array whose values are to be converted to string.
125
 * @param string       $delimiter    Optional. Default is `,`.
126
 *
127
 * @return string Stringified value.
128
 */
129
function stringify( $may_be_array, $delimiter = ',' ) {
130 1
	if ( ! is_array( $may_be_array ) ) {
131
		return (string) $may_be_array;
132
	}
133
134 1
	return implode( $delimiter, $may_be_array );
135
}
136
137
/**
138
 * Gets the User defined Date time format.
139
 *
140
 * @used-by \EmailLog\Core\UI\Setting\CoreSetting
141
 * @used-by \EmailLog\Util\render_auto_delete_logs_next_run_schedule()
142
 *
143
 * @since   2.3.0
144
 *
145
 * @return string
146
 */
147
function get_user_defined_date_time_format() {
148
	return sprintf( '%1$s %2$s', get_option( 'date_format', 'Y-m-d' ), get_option( 'time_format', 'g:i a' ) );
0 ignored issues
show
Bug introduced by
It seems like get_option('date_format', 'Y-m-d') 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

148
	return sprintf( '%1$s %2$s', /** @scrutinizer ignore-type */ get_option( 'date_format', 'Y-m-d' ), get_option( 'time_format', 'g:i a' ) );
Loading history...
149
}
150
151
/**
152
 * Renders the next run auto delete logs schedule in Date and time format set within WordPress.
153
 *
154
 * @used-by \EmailLog\Addon\UI\Setting\DashboardWidget
155
 * @used-by \EmailLog\Core\UI\Component\AutoDeleteLogsSetting
156
 *
157
 * @since 2.3.0
158
 */
159
function render_auto_delete_logs_next_run_schedule() {
160
	?>
161
	<?php if ( wp_next_scheduled( 'el_scheduled_delete_logs' ) ) : ?>
162
		<p>
163
			<?php _e( 'Auto delete logs cron will be triggered next at', 'email-log' ); ?>:
164
			<?php $date_time_format = get_user_defined_date_time_format(); ?>
165
			<strong><?php echo get_date_from_gmt( date( 'Y-m-d H:i:s', wp_next_scheduled( 'el_scheduled_delete_logs' ) ), $date_time_format ); ?></strong>
0 ignored issues
show
Bug introduced by
It seems like wp_next_scheduled('el_scheduled_delete_logs') can also be of type false; however, parameter $timestamp of date() does only seem to accept integer, 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

165
			<strong><?php echo get_date_from_gmt( date( 'Y-m-d H:i:s', /** @scrutinizer ignore-type */ wp_next_scheduled( 'el_scheduled_delete_logs' ) ), $date_time_format ); ?></strong>
Loading history...
166
		</p>
167
	<?php endif; ?>
168
	<?php
169
}
170
171
/**
172
 * Gets the value by key from the array.
173
 *
174
 * If the key isn't found, then null is returned.
175
 *
176
 * @since 2.3.0
177
 *
178
 * @param array  $array   The actual array.
179
 * @param string $key     The key whose value is to be retrieved.
180
 * @param string $default Optional.
181
 *
182
 * @return mixed|null
183
 */
184
function el_array_get( $array, $key, $default = null ) {
185
	return isset( $array[ $key ] ) ? $array[ $key ] : $default;
186
}
187
188
/**
189
 * Returns TRUE if the given search term is Advanced Search Term.
190
 *
191
 * @param string $term Search Term.
192
 *
193
 * @return bool
194
 */
195
function is_advanced_search_term( $term ) {
196
	if ( ! is_string( $term ) ) {
0 ignored issues
show
introduced by
The condition is_string($term) is always true.
Loading history...
197
		return false;
198
	}
199
200
	$predicates = get_advanced_search_term_predicates( $term );
201
202
	return ! empty( $predicates );
203
}
204
205
/**
206
 * Gets the Search Term Predicates.
207
 *
208
 * Example:
209
 *
210
 * If $term = to:[email protected] then,
211
 *
212
 * the output would be
213
 *
214
 * $output = array(
215
 *      'to' => [email protected]
216
 * )
217
 *
218
 * @since 2.3.0
219
 *
220
 * @param string $term Search Term.
221
 *
222
 * @return array
223
 */
224
function get_advanced_search_term_predicates( $term ) {
225
	if ( ! is_string( $term ) ) {
0 ignored issues
show
introduced by
The condition is_string($term) is always true.
Loading history...
226
		return array();
227
	}
228
229
	$predicates           = explode( ' ', $term );
230
	$predicates_organized = array();
231
232
	foreach ( $predicates as $predicate ) {
233
		$is_match = preg_match( '/(id|email|to|cc|bcc|reply-to):(.*)$/', $predicate, $matches );
234
		if ( 1 === $is_match ) {
235
			$predicates_organized[ $matches[1] ] = $matches[2];
236
		}
237
	}
238
239
	return $predicates_organized;
240
}
241
242
/**
243
 * Gets the Advanced Search URL.
244
 *
245
 * @since 2.3.0
246
 *
247
 * @return string
248
 */
249
function get_advanced_search_url() {
250
	$admin_url = get_admin_url( null, 'admin.php?page=email-log' );
251
252
	return add_query_arg( 'el_as', 1, $admin_url );
253
}
254
255
/**
256
 * Gets the Column labels to be used in LogList table.
257
 *
258
 * @since 2.3.2 Standardize fetching DB Column label by using get_email_log_columns() and $mapping.
259
 *              Renamed $db_column arg to $maybe_db_column to make it more appropriate.
260
 * @since 2.3.0 Initial definition.
261
 *
262
 * @param string $maybe_db_column
263
 *
264
 * @return string
265
 */
266
function get_column_label_by_db_column( $maybe_db_column ) {
267
	// Standard column labels are on the right.
268
	// $mapping[ $non_standard_key ] => $standard_key
269
	$mapping = array(
270 1
		'to'         => 'to_email', // EmailLog\Core\UI\ListTable::get_columns() uses `to`
271 1
		'reply-to'   => 'reply_to',
272 1
		'attachment' => 'attachments',
273 1
	);
274
275 1
	$labels = get_email_log_columns();
276
277
	/**
278
	 * Filters the Labels used through out the Email Log plugin.
279
	 *
280
	 * @since 2.3.0
281
	 *
282
	 * @param array $labels {
283
	 *                      List of DB Columns and its respective labels.
284
	 *
285
	 *                      Example:
286
	 *                      'id'          => __( 'ID', 'email-log' ),
287
	 *
288
	 * @type string $key    DB Column or any key for which a Label would be required. Accepts a internationalized string as Label.
289
	 *              }
290
	 */
291 1
	$labels = apply_filters( 'el_db_column_labels', $labels );
292
293 1
	if ( array_key_exists( $maybe_db_column, $mapping ) ) {
294 1
		$maybe_db_column = $mapping[ $maybe_db_column ];
295 1
	}
296
297 1
	if ( array_key_exists( $maybe_db_column, $labels ) ) {
298 1
		return $labels[ $maybe_db_column ];
299
	}
300
301
	return $maybe_db_column;
302
}
303
304
/**
305
 * Returns an array of Email Log columns.
306
 *
307
 * Keys are the column names in the DB.
308
 * This holds true except for From, CC, BCC & Reply To as they are put under one column `headers`.
309
 *
310
 * @since 2.3.2
311
 *
312
 * @return array Key value pair of Email Log columns.
313
 */
314
function get_email_log_columns() {
315
	return array(
316 1
		'id'          => __( 'ID', 'email-log' ),
317 1
		'sent_date'   => __( 'Sent at', 'email-log' ),
318 1
		'to_email'    => __( 'To', 'email-log' ),
319 1
		'subject'     => __( 'Subject', 'email-log' ),
320 1
		'message'     => __( 'Message', 'email-log' ),
321 1
		'from'        => __( 'From', 'email-log' ),
322 1
		'cc'          => __( 'CC', 'email-log' ),
323 1
		'bcc'         => __( 'BCC', 'email-log' ),
324 1
		'attachments' => __( 'Attachment', 'email-log' ),
325 1
		'ip_address'  => __( 'IP Address', 'email-log' ),
326 1
		'reply_to'    => __( 'Reply To', 'email-log' ),
327 1
	);
328
}
329
330
/**
331
 * Abstract of the core logic behind masking.
332
 *
333
 * @since 2.3.2
334
 *
335
 * @param string $value     Content
336
 * @param string $mask_char Mask character.
337
 * @param int    $percent   The higher the percent, the more masking character on the email.
338
 *
339
 * @return string
340
 */
341
function get_masked_value( $value, $mask_char, $percent ) {
342
	$len        = strlen( $value );
343
	$mask_count = (int) floor( $len * $percent / 100 );
344
	$offset     = (int) floor( ( $len - $mask_count ) / 2 );
345
346
	return substr( $value, 0, $offset )
347
	       . str_repeat( $mask_char, $mask_count )
348
	       . substr( $value, $mask_count + $offset );
349
}
350
351
/**
352
 * Masks Email address.
353
 *
354
 * @see http://www.webhostingtalk.com/showthread.php?t=1014672
355
 * @since 2.3.2
356
 *
357
 * @uses get_masked_value()
358
 *
359
 * @param string $email     Email to be masked.
360
 * @param string $mask_char Mask character.
361
 * @param int    $percent   The higher the percent, the more masking character on the email.
362
 *
363
 * @return string
364
 */
365
function mask_email( $email, $mask_char = '*', $percent = 50 ) {
366
	if ( ! is_email( $email ) ) {
367
		return $email;
368
	}
369
370
	list( $user, $domain ) = preg_split( '/@/', $email );
371
372
	return sprintf( '%1$s@%2$s',
373
		get_masked_value( $user, $mask_char, $percent ),
374
		get_masked_value( $domain, $mask_char, $percent )
375
	);
376
}
377
378
/**
379
 * Mask Content fields.
380
 *
381
 * Content fields can be Subject or Email message.
382
 *
383
 * @since 2.3.2
384
 *
385
 * @uses get_masked_value()
386
 *
387
 * @param string $content   The actual content.
388
 * @param string $mask_char Mask character.
389
 * @param int    $percent   The higher the percent, the more masking character on the email.
390
 *
391
 * @return string
392
 */
393
function mask_content( $content, $mask_char = '*', $percent = 80 ) {
394
	$content = wp_strip_all_tags( $content );
395
396
	return get_masked_value( $content, $mask_char, $percent );
397
}
398