Passed
Pull Request — dev/2.5.0 (#244)
by Sudar
21:29 queued 18:00
created

TableManager::star_log_item()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

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

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

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

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

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

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

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

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

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

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