Completed
Push — 122-star-email-log ( cf82a2...0e8628 )
by Sudar
15:56 queued 04:25
created

TableManager::get_logs_count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

175
		$current_page_no = /** @scrutinizer ignore-call */ Util\el_array_get( $additional_args, 'current_page_no', false );
Loading history...
176
		$per_page        = Util\el_array_get( $additional_args, 'per_page', false );
177
178
		$query = "SELECT * FROM {$table_name}";
179
180
		// When `date_column_format` exists, should replace the `$query` var.
181
		$date_column_format_key = 'date_column_format';
182
		if ( array_key_exists( $date_column_format_key, $additional_args ) && ! empty( $additional_args[ $date_column_format_key ] ) ) {
183
			$query = "SELECT DATE_FORMAT(sent_date, \"{$additional_args[ $date_column_format_key ]}\") as sent_date_custom, el.* FROM {$table_name} as el";
184
		}
185
186
		if ( ! empty( $ids ) ) {
187
			$ids = array_map( 'absint', $ids );
188
189
			// Can't use wpdb->prepare for the below query. If used it results in this bug https://github.com/sudar/email-log/issues/13.
190
			$ids_list = esc_sql( implode( ',', $ids ) );
191
192
			$query .= " where id IN ( {$ids_list} )";
193
		}
194
195
		// Ordering parameters.
196
		$orderby = ! empty( $additional_args['orderby'] ) ? esc_sql( $additional_args['orderby'] ) : 'sent_date';
197
		$order   = ! empty( $additional_args['order'] ) ? esc_sql( $additional_args['order'] ) : 'DESC';
198
199
		$query .= " ORDER BY {$orderby} {$order}";
200
201
		// Adjust the query to take pagination into account.
202
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
203
			$offset = ( $current_page_no - 1 ) * $per_page;
204
			$query  .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
205
		}
206
		error_log( '$query' . $query );
207
		if ( ! empty( $additional_args['output_type'] )
208
		     && in_array( $additional_args['output_type'], array(
209
				OBJECT,
210
				OBJECT_K,
211
				ARRAY_A,
212
				ARRAY_N,
213
			) ) ) {
214
			return $wpdb->get_results( $query, $additional_args['output_type'] );
215
		}
216
217
		return $wpdb->get_results( $query, 'ARRAY_A' ); //@codingStandardsIgnoreLine
218
	}
219
220
	/**
221
	 * Fetch log items.
222
	 *
223
	 * @since 2.3.0 Implemented Advanced Search. Search queries could look like the following.
224
	 *              Example:
225
	 *              id: 2
226
	 *              to: [email protected]
227
	 *
228
	 * @param array $request         Request object.
229
	 * @param int   $per_page        Entries per page.
230
	 * @param int   $current_page_no Current page no.
231
	 *
232
	 * @return array Log entries and total items count.
233
	 */
234
	public function fetch_log_items( $request, $per_page, $current_page_no ) {
235
		global $wpdb;
236
		$table_name = $this->get_log_table_name();
237
238
		$query       = 'SELECT * FROM ' . $table_name;
239
		$count_query = 'SELECT count(*) FROM ' . $table_name;
240
		$query_cond  = '';
241
242
		if ( isset( $request['s'] ) && is_string( $request['s'] ) && $request['s'] !== '' ) {
243
			$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

243
			$search_term = trim( /** @scrutinizer ignore-type */ esc_sql( $request['s'] ) );
Loading history...
244
245
			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

245
			if ( /** @scrutinizer ignore-call */ Util\is_advanced_search_term( $search_term ) ) {
Loading history...
246
				$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

246
				$predicates = /** @scrutinizer ignore-call */ Util\get_advanced_search_term_predicates( $search_term );
Loading history...
247
248
				foreach ( $predicates as $column => $email ) {
249
					switch ( $column ) {
250
						case 'id':
251
							$query_cond .= empty( $query_cond ) ? ' WHERE ' : ' AND ';
252
							$query_cond .= "id = '$email'";
253
							break;
254
						case 'to':
255
							$query_cond .= empty( $query_cond ) ? ' WHERE ' : ' AND ';
256
							$query_cond .= "to_email LIKE '%$email%'";
257
							break;
258
						case 'email':
259
							$query_cond .= empty( $query_cond ) ? ' WHERE ' : ' AND ';
260
							$query_cond .= ' ( '; /* Begin 1st */
261
							$query_cond .= " ( to_email LIKE '%$email%' OR subject LIKE '%$email%' ) "; /* Begin 2nd & End 2nd */
262
							$query_cond .= ' OR ';
263
							$query_cond .= ' ( '; /* Begin 3rd */
264
							$query_cond .= "headers <> ''";
265
							$query_cond .= ' AND ';
266
							$query_cond .= ' ( '; /* Begin 4th */
267
							$query_cond .= "headers REGEXP '[F|f]rom:.*$email' OR ";
268
							$query_cond .= "headers REGEXP '[CC|Cc|cc]:.*$email' OR ";
269
							$query_cond .= "headers REGEXP '[BCC|Bcc|bcc]:.*$email' OR ";
270
							$query_cond .= "headers REGEXP '[R|r]eply-[T|t]o:.*$email'";
271
							$query_cond .= ' ) '; /* End 4th */
272
							$query_cond .= ' ) '; /* End 3rd */
273
							$query_cond .= ' ) '; /* End 1st */
274
							break;
275
						case 'cc':
276
							$query_cond .= empty( $query_cond ) ? ' WHERE ' : ' AND ';
277
							$query_cond .= ' ( '; /* Begin 1st */
278
							$query_cond .= "headers <> ''";
279
							$query_cond .= ' AND ';
280
							$query_cond .= ' ( '; /* Begin 2nd */
281
							$query_cond .= "headers REGEXP '[CC|Cc|cc]:.*$email' ";
282
							$query_cond .= ' ) '; /* End 2nd */
283
							$query_cond .= ' ) '; /* End 1st */
284
							break;
285
						case 'bcc':
286
							$query_cond .= empty( $query_cond ) ? ' WHERE ' : ' AND ';
287
							$query_cond .= ' ( '; /* Begin 1st */
288
							$query_cond .= "headers <> ''";
289
							$query_cond .= ' AND ';
290
							$query_cond .= ' ( '; /* Begin 2nd */
291
							$query_cond .= "headers REGEXP '[BCC|Bcc|bcc]:.*$email' ";
292
							$query_cond .= ' ) '; /* End 2nd */
293
							$query_cond .= ' ) '; /* End 1st */
294
							break;
295
						case 'reply-to':
296
							$query_cond .= empty( $query_cond ) ? ' 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 '[R|r]eply-to:.*$email' ";
302
							$query_cond .= ' ) '; /* End 2nd */
303
							$query_cond .= ' ) '; /* End 1st */
304
							break;
305
					}
306
				}
307
			} else {
308
				$query_cond .= " WHERE ( to_email LIKE '%$search_term%' OR subject LIKE '%$search_term%' ) ";
309
			}
310
		}
311
312
		if ( isset( $request['d'] ) && $request['d'] !== '' ) {
313
			$search_date = trim( esc_sql( $request['d'] ) );
314
			if ( '' === $query_cond ) {
315
				$query_cond .= " WHERE sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
316
			} else {
317
				$query_cond .= " AND sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
318
			}
319
		}
320
321
		// Ordering parameters.
322
		$orderby = ! empty( $request['orderby'] ) ? esc_sql( $request['orderby'] ) : 'sent_date';
323
		$order   = ! empty( $request['order'] ) ? esc_sql( $request['order'] ) : 'DESC';
324
325
		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...
326
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
0 ignored issues
show
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

326
			$query_cond .= ' ORDER BY ' . /** @scrutinizer ignore-type */ $orderby . ' ' . $order;
Loading history...
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

326
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . /** @scrutinizer ignore-type */ $order;
Loading history...
327
		}
328
329
		// Find total number of items.
330
		$count_query = $count_query . $query_cond;
331
		$total_items = $wpdb->get_var( $count_query );
332
333
		// Adjust the query to take pagination into account.
334
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
335
			$offset     = ( $current_page_no - 1 ) * $per_page;
336
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
337
		}
338
339
		// Fetch the items.
340
		$query = $query . $query_cond;
341
		$items = $wpdb->get_results( $query );
342
343
		return array( $items, $total_items );
344
	}
345
346
	/**
347
	 * Create email log table.
348
	 *
349
	 * @global object $wpdb
350
	 */
351
	public function create_table_if_needed() {
352
		global $wpdb;
353
354
		$table_name = $this->get_log_table_name();
355
356
		if ( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
357
358
			$sql = $this->get_create_table_query();
359
360
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
361
			dbDelta( $sql );
362
363
			add_option( self::DB_OPTION_NAME, self::DB_VERSION );
364
		}
365
	}
366
367
	/**
368
	 * Get the total number of email logs.
369
	 *
370
	 * @return int Total email log count
371
	 */
372
	public function get_logs_count() {
373
		global $wpdb;
374
375
		$query = 'SELECT count(*) FROM ' . $this->get_log_table_name();
376
377
		return $wpdb->get_var( $query );
378
	}
379
380
	/**
381
	 * Fetches the log id by item data.
382
	 *
383
	 * Use this method to get the log item id when the error instance only returns the log item data.
384
	 *
385
	 * @param array        $data Array of Email information {
386
	 * @type  array|string to
387
	 * @type  string       subject
388
	 * @type  string       message
389
	 * @type  array|string headers
390
	 * @type  array|string attachments
391
	 *                          }
392
	 *
393
	 * @return int Log item id.
394
	 */
395
	public function fetch_log_id_by_data( $data ) {
396
		if ( empty( $data ) || ! is_array( $data ) ) {
397
			return 0;
398
		}
399
400
		global $wpdb;
401
		$table_name = $this->get_log_table_name();
402
403
		$query      = "SELECT ID FROM {$table_name}";
404
		$query_cond = '';
405
		$where      = array();
406
407
		// Execute the following `if` conditions only when $data is array.
408
		if ( array_key_exists( 'to', $data ) ) {
409
			// Since the value is stored as CSV in DB, convert the values from error data to CSV to compare.
410
			$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

410
			$to_email = /** @scrutinizer ignore-call */ Util\stringify( $data['to'] );
Loading history...
411
412
			$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

412
			$to_email = trim( /** @scrutinizer ignore-type */ esc_sql( $to_email ) );
Loading history...
413
			$where[]  = "to_email = '$to_email'";
414
		}
415
416
		if ( array_key_exists( 'subject', $data ) ) {
417
			$subject = trim( esc_sql( $data['subject'] ) );
418
			$where[] = "subject = '$subject'";
419
		}
420
421
		if ( array_key_exists( 'attachments', $data ) ) {
422
			if ( is_array( $data['attachments'] ) ) {
423
				$attachments = count( $data['attachments'] ) > 0 ? 'true' : 'false';
424
			} else {
425
				$attachments = empty( $data['attachments'] ) ? 'false' : 'true';
426
			}
427
			$attachments = trim( esc_sql( $attachments ) );
428
			$where[]     = "attachments = '$attachments'";
429
		}
430
431
		foreach ( $where as $index => $value ) {
432
			$query_cond .= 0 === $index ? ' WHERE ' : ' AND ';
433
			$query_cond .= $value;
434
		}
435
436
		// Get only the latest logged item when multiple rows match.
437
		$query_cond .= ' ORDER BY id DESC LIMIT 1';
438
439
		$query = $query . $query_cond;
440
441
		return absint( $wpdb->get_var( $query ) );
442
	}
443
444
	/**
445
	 * Sets email sent status and error message for the given log item when email fails.
446
	 *
447
	 * @param int    $log_item_id ID of the log item whose email sent status should be set to failed.
448
	 * @param string $message     Error message.
449
	 *
450
	 * @since 2.4.0 Include error message during update.
451
	 * @since 2.3.0
452
	 *
453
	 * @global \wpdb $wpdb
454
	 *
455
	 * @see  TableManager::get_log_table_name()
456
	 */
457
	public function mark_log_as_failed( $log_item_id, $message ) {
458
		global $wpdb;
459
		$table_name = $this->get_log_table_name();
460
461
		$wpdb->update(
462
			$table_name,
463
			array(
464
				'result'        => '0',
465
				'error_message' => $message,
466
			),
467
			array( 'ID' => $log_item_id ),
468
			array(
469
				'%d', // `result` format.
470
				'%s', // `error_message` format.
471
			),
472
			array(
473
				'%d', // `ID` format.
474
			)
475
		);
476
	}
477
478
	/**
479
	 * Updates the DB schema.
480
	 *
481
	 * Adds new columns to the Database as of v0.2.
482
	 *
483
	 * @since 2.3.0
484
	 */
485
	private function update_table_if_needed() {
486
		if ( get_option( self::DB_OPTION_NAME, false ) === self::DB_VERSION ) {
487
			return;
488
		}
489
490
		$sql = $this->get_create_table_query();
491
492
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
493
		dbDelta( $sql );
494
495
		update_option( self::DB_OPTION_NAME, self::DB_VERSION );
496
	}
497
498
	/**
499
	 * Gets the Create Table query.
500
	 *
501
	 * @since 2.4.0 Added error_message column.
502
	 * @since 2.3.0
503
	 *
504
	 * @return string
505
	 */
506
	private function get_create_table_query() {
507
		global $wpdb;
508
		$table_name      = $this->get_log_table_name();
509
		$charset_collate = $wpdb->get_charset_collate();
510
511
		$sql = 'CREATE TABLE ' . $table_name . ' (
512
				id mediumint(9) NOT NULL AUTO_INCREMENT,
513
				to_email VARCHAR(500) NOT NULL,
514
				subject VARCHAR(500) NOT NULL,
515
				message TEXT NOT NULL,
516
				headers TEXT NOT NULL,
517
				attachments TEXT NOT NULL,
518
				sent_date timestamp NOT NULL,
519
				attachment_name VARCHAR(1000),
520
				ip_address VARCHAR(15),
521
				result TINYINT(1),
522
				error_message VARCHAR(1000),
523
				PRIMARY KEY  (id)
524
			) ' . $charset_collate . ';';
525
526
		return $sql;
527
	}
528
529
	/**
530
	 * Callback for the Array filter.
531
	 *
532
	 * @since 2.3.0
533
	 *
534
	 * @param string $column A column from the array Columns.
535
	 *
536
	 * @return bool
537
	 */
538
	private function validate_columns( $column ) {
539
		return in_array( $column, array( 'to' ), true );
540
	}
541
542
	/**
543
	 * Query log items by column.
544
	 *
545
	 * @since 2.3.0
546
	 *
547
	 * @param array $columns Key value pair based on which items should be retrieved.
548
	 *
549
	 * @uses \EmailLog\Core\DB\TableManager::validate_columns()
550
	 *
551
	 * @return array|object|null
552
	 */
553
	public function query_log_items_by_column( $columns ) {
554
		if ( ! is_array( $columns ) ) {
0 ignored issues
show
introduced by
The condition is_array($columns) is always true.
Loading history...
555
			return;
556
		}
557
558
		// Since we support PHP v5.2.4, we cannot use ARRAY_FILTER_USE_KEY
559
		// TODO: PHP v5.5: Once WordPress updates minimum PHP version to v5.5, start using ARRAY_FILTER_USE_KEY.
560
		$columns_keys = array_keys( $columns );
561
		if ( ! array_filter( $columns_keys, array( $this, 'validate_columns' ) ) ) {
562
			return;
563
		}
564
565
		global $wpdb;
566
567
		$table_name = $this->get_log_table_name();
568
		$query      = "SELECT id, sent_date, to_email, subject FROM {$table_name}";
569
		$query_cond = '';
570
		$where      = array();
571
572
		// Execute the following `if` conditions only when $data is array.
573
		if ( array_key_exists( 'to', $columns ) ) {
574
			// Since the value is stored as CSV in DB, convert the values from error data to CSV to compare.
575
			$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

575
			$to_email = /** @scrutinizer ignore-call */ Util\stringify( $columns['to'] );
Loading history...
576
577
			$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

577
			$to_email = trim( /** @scrutinizer ignore-type */ esc_sql( $to_email ) );
Loading history...
578
			$where[]  = "to_email = '$to_email'";
579
580
			foreach ( $where as $index => $value ) {
581
				$query_cond .= 0 === $index ? ' WHERE ' : ' AND ';
582
				$query_cond .= $value;
583
			}
584
585
			// Get only the latest logged item when multiple rows match.
586
			$query_cond .= ' ORDER BY id DESC';
587
588
			$query = $query . $query_cond;
589
590
			return $wpdb->get_results( $query );
591
		}
592
	}
593
}
594