Completed
Push — 106-feature/store-attachment-n... ( 0b152b...aa0ea0 )
by Maria Daniel Deepak
10:15
created

TableManager::upgrade_db_schema()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 35
ccs 0
cts 16
cp 0
crap 20
rs 9.36
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
8
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
9
10
/**
11
 * Helper class to create table.
12
 *
13
 * @since 2.0.0
14
 */
15
class TableManager implements Loadie {
16
17
	/* Database table name */
18
	const LOG_TABLE_NAME = 'email_log';
19
20
	/* Database option name */
21
	const DB_OPTION_NAME = 'email-log-db';
22
23
	/* Database version */
24
	const DB_VERSION = '0.2';
25
26
	/**
27
	 * Setup hooks.
28
	 */
29
	public function load() {
30
		add_action( 'wpmu_new_blog', array( $this, 'create_table_for_new_blog' ) );
31
32
		add_filter( 'wpmu_drop_tables', array( $this, 'delete_table_from_deleted_blog' ) );
33
34
		// Do any DB upgrades.
35
		$this->upgrade_db_schema();
36
	}
37
38
	/**
39
	 * On plugin activation, create table if needed.
40
	 *
41
	 * @param bool $network_wide True if the plugin was network activated.
42
	 */
43
	public function on_activate( $network_wide ) {
44
		if ( is_multisite() && $network_wide ) {
45
			// Note: if there are more than 10,000 blogs or
46
			// if `wp_is_large_network` filter is set, then this may fail.
47
			$sites = get_sites();
48
49
			foreach ( $sites as $site ) {
50
				switch_to_blog( $site['blog_id'] );
51
				$this->create_table();
52
				restore_current_blog();
53
			}
54
		} else {
55
			$this->create_table();
56
		}
57
	}
58
59
	/**
60
	 * Create email log table when a new blog is created.
61
	 *
62
	 * @param int $blog_id Blog Id.
63
	 */
64
	public function create_table_for_new_blog( $blog_id ) {
65
		if ( is_plugin_active_for_network( 'email-log/email-log.php' ) ) {
66
			switch_to_blog( $blog_id );
67
			$this->create_table();
68
			restore_current_blog();
69
		}
70
	}
71
72
	/**
73
	 * Add email log table to the list of tables deleted when a blog is deleted.
74
	 *
75
	 * @param array $tables List of tables to be deleted.
76
	 *
77
	 * @return string[] $tables Modified list of tables to be deleted.
78
	 */
79 1
	public function delete_table_from_deleted_blog( $tables ) {
80 1
		$tables[] = $this->get_log_table_name();
81
82 1
		return $tables;
83
	}
84
85
	/**
86
	 * Get email log table name.
87
	 *
88
	 * @return string Email Log Table name.
89
	 */
90 2
	public function get_log_table_name() {
91 2
		global $wpdb;
92
93 2
		return $wpdb->prefix . self::LOG_TABLE_NAME;
94
	}
95
96
	/**
97
	 * Insert log data into DB.
98
	 *
99
	 * @param array $data Data to be inserted.
100
	 */
101
	public function insert_log( $data ) {
102
		global $wpdb;
103
104
		$table_name = $this->get_log_table_name();
105
		$wpdb->insert( $table_name, $data );
106
	}
107
108
	/**
109
	 * Delete log entries by ids.
110
	 *
111
	 * @param string $ids Comma separated list of log ids.
112
	 *
113
	 * @return false|int Number of log entries that got deleted. False on failure.
114
	 */
115
	public function delete_logs( $ids ) {
116
		global $wpdb;
117
118
		$table_name = $this->get_log_table_name();
119
120
		// Can't use wpdb->prepare for the below query. If used it results in this bug // https://github.com/sudar/email-log/issues/13.
121
		$ids = esc_sql( $ids );
122
123
		return $wpdb->query( "DELETE FROM {$table_name} where id IN ( {$ids} )" ); //@codingStandardsIgnoreLine
124
	}
125
126
	/**
127
	 * Delete all log entries.
128
	 *
129
	 * @return false|int Number of log entries that got deleted. False on failure.
130
	 */
131
	public function delete_all_logs() {
132
		global $wpdb;
133
134
		$table_name = $this->get_log_table_name();
135
136
		return $wpdb->query( "DELETE FROM {$table_name}" ); //@codingStandardsIgnoreLine
137
	}
138
139
	/**
140
	 * Deletes Email Logs older than the specified interval.
141
	 *
142
	 * @param int $interval_in_days No. of days beyond which logs are to be deleted.
143
	 *
144
	 * @return int $deleted_rows_count  Count of rows deleted.
145
	 */
146
	public function delete_logs_older_than( $interval_in_days ) {
147
		global $wpdb;
148
		$table_name = $this->get_log_table_name();
149
150
		$query              = $wpdb->prepare( "DELETE FROM {$table_name} WHERE sent_date < DATE_SUB( CURDATE(), INTERVAL %d DAY )", $interval_in_days );
151
		$deleted_rows_count = $wpdb->query( $query );
152
153
		return $deleted_rows_count;
154
	}
155
156
	/**
157
	 * Fetch log item by ID.
158
	 *
159
	 * @param array $ids Optional. Array of IDs of the log items to be retrieved.
160
	 *
161
	 * @return array Log item(s).
162
	 */
163
	public function fetch_log_items_by_id( $ids = array() ) {
164
		global $wpdb;
165
		$table_name = $this->get_log_table_name();
166
167
		$query = "SELECT * FROM {$table_name}";
168
169
		if ( ! empty( $ids ) ) {
170
			$ids = array_map( 'absint', $ids );
171
172
			// Can't use wpdb->prepare for the below query. If used it results in this bug https://github.com/sudar/email-log/issues/13.
173
			$ids_list = esc_sql( implode( ',', $ids ) );
174
175
			$query .= " where id IN ( {$ids_list} )";
176
		}
177
178
		return $wpdb->get_results( $query, 'ARRAY_A' ); //@codingStandardsIgnoreLine
179
	}
180
181
	/**
182
	 * Fetch log items.
183
	 *
184
	 * @param array $request         Request object.
185
	 * @param int   $per_page        Entries per page.
186
	 * @param int   $current_page_no Current page no.
187
	 *
188
	 * @return array Log entries and total items count.
189
	 */
190
	public function fetch_log_items( $request, $per_page, $current_page_no ) {
191
		global $wpdb;
192
		$table_name = $this->get_log_table_name();
193
194
		$query       = 'SELECT * FROM ' . $table_name;
195
		$count_query = 'SELECT count(*) FROM ' . $table_name;
196
		$query_cond  = '';
197
198
		if ( isset( $request['s'] ) && $request['s'] !== '' ) {
199
			$search_term = trim( esc_sql( $request['s'] ) );
200
			$query_cond .= " WHERE ( to_email LIKE '%$search_term%' OR subject LIKE '%$search_term%' ) ";
201
		}
202
203
		if ( isset( $request['d'] ) && $request['d'] !== '' ) {
204
			$search_date = trim( esc_sql( $request['d'] ) );
205
			if ( '' === $query_cond ) {
206
				$query_cond .= " WHERE sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
207
			} else {
208
				$query_cond .= " AND sent_date BETWEEN '$search_date 00:00:00' AND '$search_date 23:59:59' ";
209
			}
210
		}
211
212
		// Ordering parameters.
213
		$orderby = ! empty( $request['orderby'] ) ? esc_sql( $request['orderby'] ) : 'sent_date';
214
		$order   = ! empty( $request['order'] ) ? esc_sql( $request['order'] ) : 'DESC';
215
216
		if ( ! empty( $orderby ) & ! empty( $order ) ) {
217
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
218
		}
219
220
		// Find total number of items.
221
		$count_query = $count_query . $query_cond;
222
		$total_items = $wpdb->get_var( $count_query );
223
224
		// Adjust the query to take pagination into account.
225
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
226
			$offset = ( $current_page_no - 1 ) * $per_page;
227
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
228
		}
229
230
		// Fetch the items.
231
		$query = $query . $query_cond;
232
		$items = $wpdb->get_results( $query );
233
234
		return array( $items, $total_items );
235
	}
236
237
	/**
238
	 * Create email log table.
239
	 *
240
	 * @access private
241
	 *
242
	 * @global object $wpdb
243
	 */
244
	private function create_table() {
245
		global $wpdb;
246
247
		$table_name      = $this->get_log_table_name();
248
		$charset_collate = $wpdb->get_charset_collate();
249
250
		if ( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
251
252
			$sql = 'CREATE TABLE ' . $table_name . ' (
253
				id mediumint(9) NOT NULL AUTO_INCREMENT,
254
				to_email VARCHAR(100) NOT NULL,
255
				subject VARCHAR(250) NOT NULL,
256
				message TEXT NOT NULL,
257
				headers TEXT NOT NULL,
258
				attachments TEXT NOT NULL,
259
				sent_date timestamp NOT NULL,
260
				attachment_name VARCHAR(1000),
261
				ip_address VARCHAR(15),
262
				result TINYINT(1)
263
				PRIMARY KEY  (id)
264
			) ' . $charset_collate . ' ;';
265
266
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
267
			dbDelta( $sql );
268
269
			add_option( self::DB_OPTION_NAME, self::DB_VERSION );
270
		}
271
	}
272
273
	/**
274
	 * Get the total number of email logs.
275
	 *
276
	 * @return int Total email log count
277
	 */
278
	public function get_logs_count() {
279
		global $wpdb;
280
281
		$query = 'SELECT count(*) FROM ' . $this->get_log_table_name();
282
283
		return $wpdb->get_var( $query );
284
	}
285
286
	/**
287
	 * Upgrades the DB schema.
288
	 *
289
	 * Adds new columns to the Database as of v0.2.
290
	 *
291
	 * @since 2.3.0
292
	 */
293
	public function upgrade_db_schema() {
294
		global $wpdb;
295
		$existing_db_version = get_option( self::DB_OPTION_NAME, false );
296
		$updated_db_version  = self::DB_VERSION;
297
298
		if ( ! $existing_db_version || $existing_db_version === $updated_db_version ) {
299
			return;
300
		}
301
302
		$table_name      = $this->get_log_table_name();
303
		$charset_collate = $wpdb->get_charset_collate();
304
305
		if ( $this->is_columns_exist( array( 'attachment_name', 'ip_address', 'result' ) ) ) {
306
			return;
307
		}
308
309
		$sql = 'CREATE TABLE ' . $table_name . ' (
310
				id mediumint(9) NOT NULL AUTO_INCREMENT,
311
				to_email VARCHAR(250) NOT NULL,
312
				subject VARCHAR(250) NOT NULL,
313
				message TEXT NOT NULL,
314
				headers TEXT NOT NULL,
315
				attachments TEXT NOT NULL,
316
				sent_date timestamp NOT NULL,
317
				attachment_name VARCHAR(1000),
318
				ip_address VARCHAR(15),
319
				result TINYINT(1)
320
				PRIMARY KEY  (id)
321
			) ' . $charset_collate . ' ;';
322
323
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
324
		dbDelta( $sql );
325
326
		add_option( self::DB_OPTION_NAME, self::DB_VERSION );
327
	}
328
329
	/**
330
	 * Returns TRUE when the given column(s) exists in Database table.
331
	 *
332
	 * @since 2.3.0
333
	 *
334
	 * @param string|array $columns
335
	 *
336
	 * @return bool
337
	 */
338
	protected function is_columns_exist( $columns ) {
339
		global $wpdb;
340
341
		if ( empty( $columns ) ) {
342
			return false;
343
		}
344
345
		if ( ! is_array( $columns ) ) {
346
			$columns = array( $columns );
347
		}
348
349
		$table_name  = $this->get_log_table_name();
350
		$columns_str = '';
351
352
		$columns_count = count( $columns );
353
		foreach ( $columns as $key => $column ) {
354
			$columns_str .= "COLUMN_NAME = '" . $column . "'";
355
356
			if ( $key !== $columns_count - 1 ) {
357
				$columns_str .= ' OR ';
358
			}
359
		}
360
361
		$columns_sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table_name . "' AND ({$columns_str});";
362
363
		$results = $wpdb->get_results( $columns_sql );
364
365
		return count( $results ) > 0;
366
	}
367
}
368