Completed
Push — 106-feature/store-attachment-n... ( d01742...317068 )
by Maria Daniel Deepak
01:49
created

TableManager::update_table_if_needed()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 2
nop 0
dl 0
loc 16
ccs 0
cts 5
cp 0
crap 20
rs 9.7333
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->update_table_if_needed();
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_if_needed();
52
				restore_current_blog();
53
			}
54
		} else {
55
			$this->create_table_if_needed();
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_if_needed();
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_if_needed() {
245
		global $wpdb;
246
247
		$table_name = $this->get_log_table_name();
248
249
		if ( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
250
251
			$sql = $this->get_create_table_query();
252
253
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
254
			dbDelta( $sql );
255
256
			add_option( self::DB_OPTION_NAME, self::DB_VERSION );
257
		}
258
	}
259
260
	/**
261
	 * Get the total number of email logs.
262
	 *
263
	 * @return int Total email log count
264
	 */
265
	public function get_logs_count() {
266
		global $wpdb;
267
268
		$query = 'SELECT count(*) FROM ' . $this->get_log_table_name();
269
270
		return $wpdb->get_var( $query );
271
	}
272
273
	/**
274
	 * Updates the DB schema.
275
	 *
276
	 * Adds new columns to the Database as of v0.2.
277
	 *
278
	 * @since 2.3.0
279
	 */
280
	private function update_table_if_needed() {
281
		$existing_db_version = get_option( self::DB_OPTION_NAME, false );
282
		$updated_db_version  = self::DB_VERSION;
283
284
		// Bail out when the DB version is `0.1` or equals to self::DB_VERSION
285
		if ( ! $existing_db_version || $existing_db_version !== '0.1' || $existing_db_version === $updated_db_version ) {
286
			return;
287
		}
288
289
		$sql = $this->create_table_sql();
0 ignored issues
show
Bug introduced by
The method create_table_sql() does not seem to exist on object<EmailLog\Core\DB\TableManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
290
291
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
292
		dbDelta( $sql );
293
294
		update_option( self::DB_OPTION_NAME, self::DB_VERSION );
295
	}
296
297
	/**
298
	 * Gets the Create Table query.
299
	 *
300
	 * @since 2.3.0
301
	 *
302
	 * @return string
303
	 */
304
	private function get_create_table_query() {
305
		global $wpdb;
306
		$table_name      = $this->get_log_table_name();
307
		$charset_collate = $wpdb->get_charset_collate();
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
		return $sql;
324
	}
325
}
326