Passed
Pull Request — dev/2.5.0 (#244)
by
unknown
18:08 queued 15:14
created

TableManager::build_query_condition()   D

Complexity

Conditions 32
Paths 96

Size

Total Lines 94
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 1056

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 32
eloc 78
c 1
b 0
f 0
nc 96
nop 2
dl 0
loc 94
ccs 0
cts 70
cp 0
crap 1056
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace EmailLog\Core\DB;
2
3
/**
4
 * Handle installation and db table creation.
5
 */
6
use EmailLog\Core\Loadie;
7
use EmailLog\Util;
8
use function EmailLog\Util\el_array_get;
9
10
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
11
12
/**
13
 * Helper class to create table.
14
 *
15
 * @since 2.0.0
16
 */
17
class TableManager implements Loadie {
18
19
	/* Database table name */
20
	const LOG_TABLE_NAME = 'email_log';
21
22
	/* Database option name */
23
	const DB_OPTION_NAME = 'email-log-db';
24
25
	/* Database version */
26
	const DB_VERSION = '0.3';
27
28
	/**
29
	 * The user meta key in which the starred emails of a user are stored.
30
	 *
31
	 * @since 2.5.0
32
	 */
33
	const STARRED_LOGS_META_KEY = 'email-log-starred-logs';
34
35
	/**
36
	 * Setup hooks.
37
	 */
38
	public function load() {
39
		add_action( 'wpmu_new_blog', array( $this, 'create_table_for_new_blog' ) );
40
41
		add_filter( 'wpmu_drop_tables', array( $this, 'delete_table_from_deleted_blog' ) );
42
43
		// Do any DB upgrades.
44
		$this->update_table_if_needed();
45
	}
46
47
	/**
48
	 * On plugin activation, create table if needed.
49
	 *
50
	 * @param bool $network_wide True if the plugin was network activated.
51
	 */
52
	public function on_activate( $network_wide ) {
53
		if ( is_multisite() && $network_wide ) {
54
			// Note: if there are more than 10,000 blogs or
55
			// if `wp_is_large_network` filter is set, then this may fail.
56
			$sites = get_sites();
57
58
			foreach ( $sites as $site ) {
59
				switch_to_blog( $site->blog_id );
60
				$this->create_table_if_needed();
61
				restore_current_blog();
62
			}
63
		} else {
64
			$this->create_table_if_needed();
65
		}
66
	}
67
68
	/**
69
	 * Create email log table when a new blog is created.
70
	 *
71
	 * @param int $blog_id Blog Id.
72
	 */
73
	public function create_table_for_new_blog( $blog_id ) {
74
		if ( is_plugin_active_for_network( 'email-log/email-log.php' ) ) {
75
			switch_to_blog( $blog_id );
76
			$this->create_table_if_needed();
77
			restore_current_blog();
78
		}
79
	}
80
81
	/**
82
	 * Add email log table to the list of tables deleted when a blog is deleted.
83
	 *
84
	 * @param array $tables List of tables to be deleted.
85
	 *
86
	 * @return string[] $tables Modified list of tables to be deleted.
87
	 */
88 1
	public function delete_table_from_deleted_blog( $tables ) {
89 1
		$tables[] = $this->get_log_table_name();
90
91 1
		return $tables;
92
	}
93
94
	/**
95
	 * Get email log table name.
96
	 *
97
	 * @return string Email Log Table name.
98
	 */
99 2
	public function get_log_table_name() {
100 2
		global $wpdb;
101
102 2
		return $wpdb->prefix . self::LOG_TABLE_NAME;
103
	}
104
105
	/**
106
	 * Insert log data into DB.
107
	 *
108
	 * @param array $data Data to be inserted.
109
	 */
110
	public function insert_log( $data ) {
111
		global $wpdb;
112
113
		$table_name = $this->get_log_table_name();
114
		$wpdb->insert( $table_name, $data );
115
	}
116
117
	/**
118
	 * Delete log entries by ids.
119
	 *
120
	 * @param string $ids Comma separated list of log ids.
121
	 *
122
	 * @return false|int Number of log entries that got deleted. False on failure.
123
	 */
124
	public function delete_logs( $ids ) {
125
		global $wpdb;
126
127
		$table_name = $this->get_log_table_name();
128
129
		// Can't use wpdb->prepare for the below query. If used it results in this bug // https://github.com/sudar/email-log/issues/13.
130
		$ids = esc_sql( $ids );
131
132
		return $wpdb->query( "DELETE FROM {$table_name} where id IN ( {$ids} )" ); //@codingStandardsIgnoreLine
133
	}
134
135
	/**
136
	 * Delete all log entries.
137
	 *
138
	 * @return false|int Number of log entries that got deleted. False on failure.
139
	 */
140
	public function delete_all_logs() {
141
		global $wpdb;
142
143
		$table_name = $this->get_log_table_name();
144
145
		return $wpdb->query( "DELETE FROM {$table_name}" ); //@codingStandardsIgnoreLine
146
	}
147
148
	/**
149
	 * Deletes Email Logs older than the specified interval.
150
	 *
151
	 * @param int $interval_in_days No. of days beyond which logs are to be deleted.
152
	 *
153
	 * @return int $deleted_rows_count  Count of rows deleted.
154
	 */
155
	public function delete_logs_older_than( $interval_in_days ) {
156
		global $wpdb;
157
		$table_name = $this->get_log_table_name();
158
159
		$query              = $wpdb->prepare( "DELETE FROM {$table_name} WHERE sent_date < DATE_SUB( CURDATE(), INTERVAL %d DAY )", $interval_in_days );
160
		$deleted_rows_count = $wpdb->query( $query );
161
162
		return $deleted_rows_count;
163
	}
164
165
	/**
166
	 * Fetch log item by ID.
167
	 *
168
	 * @param array $ids             Optional. Array of IDs of the log items to be retrieved.
169
	 * @param array $additional_args {
170
	 *                               Optional. Array of additional args.
171
	 *
172
	 * @type string $date_column_format MySQL date column format. Refer
173
	 *
174
	 * @link  https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
175
	 * @type int $current_page_no    Current Page number.
176
	 * @type int $per_page           Per Page count.
177
	 *           }
178
	 *
179
	 * @return array Log item(s).
180
	 */
181
	public function fetch_log_items_by_id( $ids = array(), $additional_args = array() ) {
182
		global $wpdb;
183
		$table_name      = $this->get_log_table_name();
184
		$current_page_no = el_array_get( $additional_args, 'current_page_no', false );
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $default of EmailLog\Util\el_array_get(). ( Ignorable by Annotation )

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

184
		$current_page_no = el_array_get( $additional_args, 'current_page_no', /** @scrutinizer ignore-type */ false );
Loading history...
185
		$per_page        = el_array_get( $additional_args, 'per_page', false );
186
187
		$query = "SELECT * FROM {$table_name}";
188
189
		// When `date_column_format` exists, should replace the `$query` var.
190
		$date_column_format_key = 'date_column_format';
191
		if ( array_key_exists( $date_column_format_key, $additional_args ) && ! empty( $additional_args[ $date_column_format_key ] ) ) {
192
			$query = "SELECT DATE_FORMAT(sent_date, \"{$additional_args[ $date_column_format_key ]}\") as sent_date_custom, el.* FROM {$table_name} as el";
193
		}
194
195
		if ( ! empty( $ids ) ) {
196
			$ids = array_map( 'absint', $ids );
197
198
			// Can't use wpdb->prepare for the below query. If used it results in this bug https://github.com/sudar/email-log/issues/13.
199
			$ids_list = esc_sql( implode( ',', $ids ) );
200
201
			$query .= " where id IN ( {$ids_list} )";
202
		}
203
204
		$query .= $this->build_query_condition( $_GET, true );
205
206
		// Adjust the query to take pagination into account.
207
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
208
			$offset = ( $current_page_no - 1 ) * $per_page;
209
			$query .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
210
		}
211
		if ( in_array( $additional_args['output_type'], [ OBJECT, OBJECT_K, ARRAY_A, ARRAY_N ], true ) ) {
212
			return $wpdb->get_results( $query, $additional_args['output_type'] );
213
		}
214
215
		return $wpdb->get_results( $query, 'ARRAY_A' ); //@codingStandardsIgnoreLine
216
	}
217
218
	/**
219
	 * Fetch log items.
220
	 *
221
	 * @since 2.3.0 Implemented Advanced Search. Search queries could look like the following.
222
	 *              Example:
223
	 *              id: 2
224
	 *              to: [email protected]
225
	 * @since 2.5.0 Return only fetched log items and not total count.
226
	 *
227
	 * @param array $request         Request object.
228
	 * @param int   $per_page        Entries per page.
229
	 * @param int   $current_page_no Current page no.
230
	 *
231
	 * @return array Log entries.
232
	 */
233
	public function fetch_log_items( $request, $per_page, $current_page_no ) {
234
		global $wpdb;
235
		$table_name = $this->get_log_table_name();
236
237
		$query      = 'SELECT * FROM ' . $table_name;
238
239
		$query_cond = $this->build_query_condition( $request );
240
241
		// Adjust the query to take pagination into account.
242
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
243
			$offset      = ( $current_page_no - 1 ) * $per_page;
244
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
245
		}
246
247
		$query .= $query_cond;
248
249
		return $wpdb->get_results( $query );
250
	}
251
252
	/**
253
	 * Builds query condition based on supplied parameters. Currently handles search and sorting.
254
	 *
255
	 * @param array $request      Request object.
256
	 * @param bool  $where_clause True if where clause is present, False otherwise.
257
	 *
258
	 * @since 2.5.0
259
	 */
260
	public function build_query_condition( $request, $where_clause = false ) {
261
		$query_cond = '';
262
		if ( isset( $request['s'] ) && is_string( $request['s'] ) && $request['s'] !== '' ) {
263
			$search_term = trim( esc_sql( $request['s'] ) );
0 ignored issues
show
Bug introduced by
It seems like esc_sql($request['s']) can also be of type array; however, parameter $str of trim() 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

263
			$search_term = trim( /** @scrutinizer ignore-type */ esc_sql( $request['s'] ) );
Loading history...
264
265
			if ( Util\is_advanced_search_term( $search_term ) ) {
0 ignored issues
show
Bug introduced by
The function is_advanced_search_term was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

265
			if ( /** @scrutinizer ignore-call */ Util\is_advanced_search_term( $search_term ) ) {
Loading history...
266
				$predicates = Util\get_advanced_search_term_predicates( $search_term );
0 ignored issues
show
Bug introduced by
The function get_advanced_search_term_predicates was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

266
				$predicates = /** @scrutinizer ignore-call */ Util\get_advanced_search_term_predicates( $search_term );
Loading history...
267
268
				foreach ( $predicates as $column => $email ) {
269
					switch ( $column ) {
270
						case 'id':
271
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
272
							$query_cond .= "id = '$email'";
273
							break;
274
						case 'to':
275
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
276
							$query_cond .= "to_email LIKE '%$email%'";
277
							break;
278
						case 'email':
279
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
280
							$query_cond .= ' ( '; /* Begin 1st */
281
							$query_cond .= " ( to_email LIKE '%$email%' OR subject LIKE '%$email%' ) "; /* Begin 2nd & End 2nd */
282
							$query_cond .= ' OR ';
283
							$query_cond .= ' ( '; /* Begin 3rd */
284
							$query_cond .= "headers <> ''";
285
							$query_cond .= ' AND ';
286
							$query_cond .= ' ( '; /* Begin 4th */
287
							$query_cond .= "headers REGEXP '[F|f]rom:.*$email' OR ";
288
							$query_cond .= "headers REGEXP '[CC|Cc|cc]:.*$email' OR ";
289
							$query_cond .= "headers REGEXP '[BCC|Bcc|bcc]:.*$email' OR ";
290
							$query_cond .= "headers REGEXP '[R|r]eply-[T|t]o:.*$email'";
291
							$query_cond .= ' ) '; /* End 4th */
292
							$query_cond .= ' ) '; /* End 3rd */
293
							$query_cond .= ' ) '; /* End 1st */
294
							break;
295
						case 'cc':
296
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
297
							$query_cond .= ' ( '; /* Begin 1st */
298
							$query_cond .= "headers <> ''";
299
							$query_cond .= ' AND ';
300
							$query_cond .= ' ( '; /* Begin 2nd */
301
							$query_cond .= "headers REGEXP '[CC|Cc|cc]:.*$email' ";
302
							$query_cond .= ' ) '; /* End 2nd */
303
							$query_cond .= ' ) '; /* End 1st */
304
							break;
305
						case 'bcc':
306
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
307
							$query_cond .= ' ( '; /* Begin 1st */
308
							$query_cond .= "headers <> ''";
309
							$query_cond .= ' AND ';
310
							$query_cond .= ' ( '; /* Begin 2nd */
311
							$query_cond .= "headers REGEXP '[BCC|Bcc|bcc]:.*$email' ";
312
							$query_cond .= ' ) '; /* End 2nd */
313
							$query_cond .= ' ) '; /* End 1st */
314
							break;
315
						case 'reply-to':
316
							$query_cond .= empty( $query_cond ) && ! $where_clause ? ' WHERE ' : ' AND ';
317
							$query_cond .= ' ( '; /* Begin 1st */
318
							$query_cond .= "headers <> ''";
319
							$query_cond .= ' AND ';
320
							$query_cond .= ' ( '; /* Begin 2nd */
321
							$query_cond .= "headers REGEXP '[R|r]eply-to:.*$email' ";
322
							$query_cond .= ' ) '; /* End 2nd */
323
							$query_cond .= ' ) '; /* End 1st */
324
							break;
325
					}
326
				}
327
			} else {
328
				if ( $where_clause ) {
329
					$query_cond .= " AND ( to_email LIKE '%$search_term%' OR subject LIKE '%$search_term%' ) ";
330
				} else {
331
					$query_cond .= " WHERE ( to_email LIKE '%$search_term%' OR subject LIKE '%$search_term%' ) ";
332
				}
333
			}
334
		}
335
336
		if ( isset( $request['d'] ) && $request['d'] !== '' ) {
337
			$search_date = trim( esc_sql( $request['d'] ) );
338
			if ( empty( $query_cond ) && ! $where_clause ) {
339
				$query_cond .= " WHERE sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
340
			} else {
341
				$query_cond .= " AND sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
342
			}
343
		}
344
345
		// Ordering parameters.
346
		$orderby = ! empty( $request['orderby'] ) ? esc_sql( $request['orderby'] ) : 'sent_date';
347
		$order   = ! empty( $request['order'] ) ? esc_sql( $request['order'] ) : 'DESC';
348
349
		if ( ! empty( $orderby ) & ! empty( $order ) ) {
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise & or did you mean &&?
Loading history...
350
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
0 ignored issues
show
Bug introduced by
Are you sure $order of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

350
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . /** @scrutinizer ignore-type */ $order;
Loading history...
Bug introduced by
Are you sure $orderby of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

350
			$query_cond .= ' ORDER BY ' . /** @scrutinizer ignore-type */ $orderby . ' ' . $order;
Loading history...
351
		}
352
353
		return $query_cond;
354
	}
355
356
	/**
357
	 * Create email log table.
358
	 *
359
	 * @global object $wpdb
360
	 */
361
	public function create_table_if_needed() {
362
		global $wpdb;
363
364
		$table_name = $this->get_log_table_name();
365
366
		if ( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
367
368
			$sql = $this->get_create_table_query();
369
370
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
371
			dbDelta( $sql );
372
373
			add_option( self::DB_OPTION_NAME, self::DB_VERSION );
374
		}
375
	}
376
377
	/**
378
	 * Get the total number of email logs.
379
	 *
380
	 * @return int Total email log count
381
	 */
382
	public function get_logs_count() {
383
		global $wpdb;
384
385
		$query = 'SELECT count(*) FROM ' . $this->get_log_table_name();
386
387
		return $wpdb->get_var( $query );
388
	}
389
390
	/**
391
	 * Get the total number of email logs in the result after search or filtering.
392
	 *
393
	 * @param array $request Request object.
394
	 *
395
	 * @return int Total email log count in the result.
396
	 *
397
	 * @since 2.5.0
398
	 */
399
	public function get_result_logs_count( $request ) {
400
		global $wpdb;
401
402
		$query = 'SELECT count(*) FROM ' . $this->get_log_table_name();
403
404
		$query_condition = $this->build_query_condition( $request );
405
406
		$query .= $query_condition;
407
408
		return $wpdb->get_var( $query );
409
	}
410
411
	/**
412
	 * Fetches the log id by item data.
413
	 *
414
	 * Use this method to get the log item id when the error instance only returns the log item data.
415
	 *
416
	 * @param array        $data Array of Email information {
417
	 * @type  array|string to
418
	 * @type  string       subject
419
	 * @type  string       message
420
	 * @type  array|string headers
421
	 * @type  array|string attachments
422
	 *                          }
423
	 *
424
	 * @return int Log item id.
425
	 */
426
	public function fetch_log_id_by_data( $data ) {
427
		if ( empty( $data ) || ! is_array( $data ) ) {
428
			return 0;
429
		}
430
431
		global $wpdb;
432
		$table_name = $this->get_log_table_name();
433
434
		$query      = "SELECT ID FROM {$table_name}";
435
		$query_cond = '';
436
		$where      = array();
437
438
		// Execute the following `if` conditions only when $data is array.
439
		if ( array_key_exists( 'to', $data ) ) {
440
			// Since the value is stored as CSV in DB, convert the values from error data to CSV to compare.
441
			$to_email = Util\stringify( $data['to'] );
0 ignored issues
show
Bug introduced by
The function stringify was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

441
			$to_email = /** @scrutinizer ignore-call */ Util\stringify( $data['to'] );
Loading history...
442
443
			$to_email = trim( esc_sql( $to_email ) );
0 ignored issues
show
Bug introduced by
It seems like esc_sql($to_email) can also be of type array; however, parameter $str of trim() 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

443
			$to_email = trim( /** @scrutinizer ignore-type */ esc_sql( $to_email ) );
Loading history...
444
			$where[]  = "to_email = '$to_email'";
445
		}
446
447
		if ( array_key_exists( 'subject', $data ) ) {
448
			$subject = trim( esc_sql( $data['subject'] ) );
449
			$where[] = "subject = '$subject'";
450
		}
451
452
		if ( array_key_exists( 'attachments', $data ) ) {
453
			if ( is_array( $data['attachments'] ) ) {
454
				$attachments = count( $data['attachments'] ) > 0 ? 'true' : 'false';
455
			} else {
456
				$attachments = empty( $data['attachments'] ) ? 'false' : 'true';
457
			}
458
			$attachments = trim( esc_sql( $attachments ) );
459
			$where[]     = "attachments = '$attachments'";
460
		}
461
462
		foreach ( $where as $index => $value ) {
463
			$query_cond .= 0 === $index ? ' WHERE ' : ' AND ';
464
			$query_cond .= $value;
465
		}
466
467
		// Get only the latest logged item when multiple rows match.
468
		$query_cond .= ' ORDER BY id DESC LIMIT 1';
469
470
		$query = $query . $query_cond;
471
472
		return absint( $wpdb->get_var( $query ) );
473
	}
474
475
	/**
476
	 * Get the list of starred log items for a user.
477
	 *
478
	 * @since 2.5.0
479
	 *
480
	 * @param int|null $user_id User id. If empty, then current user id is used.
481
	 *
482
	 * @return array Starred log list items.
483
	 */
484
	public function get_starred_log_item_ids( $user_id = null ) {
485
		if ( empty( $user_id ) ) {
486
			$user_id = get_current_user_id();
487
		}
488
489
		$starred_log_item_ids = get_user_meta(
490
			$user_id,
491
			self::STARRED_LOGS_META_KEY,
492
			true
493
		);
494
495
		if ( empty( $starred_log_item_ids ) || ! is_array( $starred_log_item_ids ) ) {
496
			return [];
497
		}
498
499
		return $starred_log_item_ids;
500
	}
501
502
	/**
503
	 * Star (or Unstar) an email log id.
504
	 *
505
	 * @since 2.5.0
506
	 *
507
	 * @param int      $log_id  Log id.
508
	 * @param bool     $un_star Whether to unstar an email or star it. Default false.
509
	 * @param int|null $user_id User id. Default null. Current user id is used if not specified.
510
	 *
511
	 * @return bool Whether the update was successful.
512
	 */
513
	public function star_log_item( $log_id, $un_star = false, $user_id = null ) {
514
		if ( empty( $user_id ) ) {
515
			$user_id = get_current_user_id();
516
		}
517
518
		$starred_log_ids = $this->get_starred_log_item_ids( $user_id );
519
520
		if ( $un_star ) {
521
			$key = array_search( $log_id, $starred_log_ids, true );
522
			unset( $starred_log_ids[ $key ] );
523
		} else {
524
			$starred_log_ids = array_merge( $starred_log_ids, array( $log_id ) );
525
		}
526
527
		return update_user_meta(
528
			$user_id,
529
			self::STARRED_LOGS_META_KEY,
530
			$starred_log_ids
531
		);
532
	}
533
534
	/**
535
	 * Sets email sent status and error message for the given log item when email fails.
536
	 *
537
	 * @param int    $log_item_id ID of the log item whose email sent status should be set to failed.
538
	 * @param string $message     Error message.
539
	 *
540
	 * @since 2.4.0 Include error message during update.
541
	 * @since 2.3.0
542
	 *
543
	 * @global \wpdb $wpdb
544
	 *
545
	 * @see  TableManager::get_log_table_name()
546
	 */
547
	public function mark_log_as_failed( $log_item_id, $message ) {
548
		global $wpdb;
549
		$table_name = $this->get_log_table_name();
550
551
		$wpdb->update(
552
			$table_name,
553
			array(
554
				'result'        => '0',
555
				'error_message' => $message,
556
			),
557
			array( 'ID' => $log_item_id ),
558
			array(
559
				'%d', // `result` format.
560
				'%s', // `error_message` format.
561
			),
562
			array(
563
				'%d', // `ID` format.
564
			)
565
		);
566
	}
567
568
	/**
569
	 * Updates the DB schema.
570
	 *
571
	 * Adds new columns to the Database as of v0.2.
572
	 *
573
	 * @since 2.3.0
574
	 */
575
	private function update_table_if_needed() {
576
		if ( get_option( self::DB_OPTION_NAME, false ) === self::DB_VERSION ) {
577
			return;
578
		}
579
580
		$sql = $this->get_create_table_query();
581
582
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
583
		dbDelta( $sql );
584
585
		update_option( self::DB_OPTION_NAME, self::DB_VERSION );
586
	}
587
588
	/**
589
	 * Gets the Create Table query.
590
	 *
591
	 * @since 2.4.0 Added error_message column.
592
	 * @since 2.3.0
593
	 *
594
	 * @return string
595
	 */
596
	private function get_create_table_query() {
597
		global $wpdb;
598
		$table_name      = $this->get_log_table_name();
599
		$charset_collate = $wpdb->get_charset_collate();
600
601
		$sql = 'CREATE TABLE ' . $table_name . ' (
602
				id mediumint(9) NOT NULL AUTO_INCREMENT,
603
				to_email VARCHAR(500) NOT NULL,
604
				subject VARCHAR(500) NOT NULL,
605
				message TEXT NOT NULL,
606
				headers TEXT NOT NULL,
607
				attachments TEXT NOT NULL,
608
				sent_date timestamp NOT NULL,
609
				attachment_name VARCHAR(1000),
610
				ip_address VARCHAR(15),
611
				result TINYINT(1),
612
				error_message VARCHAR(1000),
613
				PRIMARY KEY  (id)
614
			) ' . $charset_collate . ';';
615
616
		return $sql;
617
	}
618
619
	/**
620
	 * Callback for the Array filter.
621
	 *
622
	 * @since 2.3.0
623
	 *
624
	 * @param string $column A column from the array Columns.
625
	 *
626
	 * @return bool
627
	 */
628
	private function validate_columns( $column ) {
629
		return in_array( $column, array( 'to' ), true );
630
	}
631
632
	/**
633
	 * Query log items by column.
634
	 *
635
	 * @since 2.3.0
636
	 *
637
	 * @param array $columns Key value pair based on which items should be retrieved.
638
	 *
639
	 * @uses \EmailLog\Core\DB\TableManager::validate_columns()
640
	 *
641
	 * @return array|object|null
642
	 */
643
	public function query_log_items_by_column( $columns ) {
644
		if ( ! is_array( $columns ) ) {
0 ignored issues
show
introduced by
The condition is_array($columns) is always true.
Loading history...
645
			return;
646
		}
647
648
		// Since we support PHP v5.2.4, we cannot use ARRAY_FILTER_USE_KEY
649
		// TODO: PHP v5.5: Once WordPress updates minimum PHP version to v5.5, start using ARRAY_FILTER_USE_KEY.
650
		$columns_keys = array_keys( $columns );
651
		if ( ! array_filter( $columns_keys, array( $this, 'validate_columns' ) ) ) {
652
			return;
653
		}
654
655
		global $wpdb;
656
657
		$table_name = $this->get_log_table_name();
658
		$query      = "SELECT id, sent_date, to_email, subject FROM {$table_name}";
659
		$query_cond = '';
660
		$where      = array();
661
662
		// Execute the following `if` conditions only when $data is array.
663
		if ( array_key_exists( 'to', $columns ) ) {
664
			// Since the value is stored as CSV in DB, convert the values from error data to CSV to compare.
665
			$to_email = Util\stringify( $columns['to'] );
0 ignored issues
show
Bug introduced by
The function stringify was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

665
			$to_email = /** @scrutinizer ignore-call */ Util\stringify( $columns['to'] );
Loading history...
666
667
			$to_email = trim( esc_sql( $to_email ) );
0 ignored issues
show
Bug introduced by
It seems like esc_sql($to_email) can also be of type array; however, parameter $str of trim() 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

667
			$to_email = trim( /** @scrutinizer ignore-type */ esc_sql( $to_email ) );
Loading history...
668
			$where[]  = "to_email = '$to_email'";
669
670
			foreach ( $where as $index => $value ) {
671
				$query_cond .= 0 === $index ? ' WHERE ' : ' AND ';
672
				$query_cond .= $value;
673
			}
674
675
			// Get only the latest logged item when multiple rows match.
676
			$query_cond .= ' ORDER BY id DESC';
677
678
			$query = $query . $query_cond;
679
680
			return $wpdb->get_results( $query );
681
		}
682
	}
683
}
684