Completed
Pull Request — dev/2.5.0 (#244)
by Sudar
21:46 queued 12:27
created

TableManager   F

Complexity

Total Complexity 80

Size/Duplication

Total Lines 635
Duplicated Lines 0 %

Test Coverage

Coverage 2.33%

Importance

Changes 24
Bugs 3 Features 0
Metric Value
eloc 251
dl 0
loc 635
ccs 6
cts 258
cp 0.0233
rs 2
c 24
b 3
f 0
wmc 80

21 Methods

Rating   Name   Duplication   Size   Complexity  
A star_log_item() 0 18 3
A insert_log() 0 5 1
A update_table_if_needed() 0 11 2
A get_logs_count() 0 6 1
A delete_table_from_deleted_blog() 0 4 1
A get_create_table_query() 0 21 1
A create_table_for_new_blog() 0 5 2
A validate_columns() 0 2 1
B fetch_log_items_by_id() 0 45 10
A delete_logs_older_than() 0 8 1
F fetch_log_items() 0 103 26
B fetch_log_id_by_data() 0 47 11
B query_log_items_by_column() 0 38 6
A load() 0 7 1
A get_log_table_name() 0 4 1
A create_table_if_needed() 0 13 2
A get_starred_log_item_ids() 0 16 3
A delete_all_logs() 0 6 1
A delete_logs() 0 9 1
A mark_log_as_failed() 0 17 1
A on_activate() 0 13 4

How to fix   Complexity   

Complex Class

Complex classes like TableManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TableManager, and based on these observations, apply Extract Interface, too.

1
<?php namespace EmailLog\Core\DB;
2
3
/**
4
 * Handle installation and db table creation.
5
 */
6
use EmailLog\Core\Loadie;
7
use EmailLog\Core\UI\Page\LogListPage;
8
use EmailLog\Util;
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 = 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

184
		$current_page_no = /** @scrutinizer ignore-call */ Util\el_array_get( $additional_args, 'current_page_no', false );
Loading history...
185
		$per_page        = Util\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
		// Ordering parameters.
205
		$orderby = ! empty( $additional_args['orderby'] ) ? esc_sql( $additional_args['orderby'] ) : 'sent_date';
206
		$order   = ! empty( $additional_args['order'] ) ? esc_sql( $additional_args['order'] ) : 'DESC';
207
208
		$query .= " ORDER BY {$orderby} {$order}";
209
210
		// Adjust the query to take pagination into account.
211
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
212
			$offset = ( $current_page_no - 1 ) * $per_page;
213
			$query .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
214
		}
215
		if ( ! empty( $additional_args['output_type'] )
216
		     && in_array( $additional_args['output_type'], array(
217
				OBJECT,
218
				OBJECT_K,
219
				ARRAY_A,
220
				ARRAY_N,
221
			) ) ) {
222
			return $wpdb->get_results( $query, $additional_args['output_type'] );
223
		}
224
225
		return $wpdb->get_results( $query, 'ARRAY_A' ); //@codingStandardsIgnoreLine
226
	}
227
228
	/**
229
	 * Fetch log items.
230
	 *
231
	 * @since 2.3.0 Implemented Advanced Search. Search queries could look like the following.
232
	 *              Example:
233
	 *              id: 2
234
	 *              to: [email protected]
235
	 * @since 2.5.0 Return only fetched log items and not total count.
236
	 *
237
	 * @param array $request         Request object.
238
	 * @param int   $per_page        Entries per page.
239
	 * @param int   $current_page_no Current page no.
240
	 *
241
	 * @return array Log entries.
242
	 */
243
	public function fetch_log_items( $request, $per_page, $current_page_no ) {
244
		global $wpdb;
245
		$table_name = $this->get_log_table_name();
246
247
		$query      = 'SELECT * FROM ' . $table_name;
248
		$query_cond = '';
249
250
		if ( isset( $request['s'] ) && is_string( $request['s'] ) && $request['s'] !== '' ) {
251
			$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

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

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

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

334
			$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

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

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

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

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

638
			$to_email = trim( /** @scrutinizer ignore-type */ esc_sql( $to_email ) );
Loading history...
639
			$where[]  = "to_email = '$to_email'";
640
641
			foreach ( $where as $index => $value ) {
642
				$query_cond .= 0 === $index ? ' WHERE ' : ' AND ';
643
				$query_cond .= $value;
644
			}
645
646
			// Get only the latest logged item when multiple rows match.
647
			$query_cond .= ' ORDER BY id DESC';
648
649
			$query = $query . $query_cond;
650
651
			return $wpdb->get_results( $query );
652
		}
653
	}
654
}
655