Completed
Pull Request — master (#67)
by Maria Daniel Deepak
14:47
created

TableManager::on_delete_blog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php namespace EmailLog\Core\DB;
2
/**
3
 * Handle installation and db table creation
4
 */
5
6
defined( 'ABSPATH' ) || exit; // Exit if accessed directly
7
8
/**
9
 * Helper class to create table.
10
 *
11
 * @since 2.0
12
 */
13
class TableManager {
14
15
	/* Database table name */
16
	const LOG_TABLE_NAME = 'email_log';
17
18
	/* Database option name */
19
	const DB_OPTION_NAME = 'email-log-db';
20
21
	/* Database version */
22
	const DB_VERSION = '0.1';
23
24
	/**
25
	 * Setup hooks.
26
	 */
27
	public function load() {
28
		// when a new blog is created in multisite
29
		add_action( 'wpmu_new_blog', array( $this, 'on_create_blog' ), 10, 6 );
30
31
		// when a blog is deleted in multisite
32
		add_filter( 'wpmu_drop_tables', array( $this, 'on_delete_blog' ) );
33
	}
34
35
	/**
36
	 * On plugin activation, create table if needed.
37
	 */
38
	public function on_activate( $network_wide ) {
39
		if ( is_multisite() && $network_wide ) {
40
			// Note: if there are more than 10,000 blogs or
41
			// if `wp_is_large_network` filter is set, then this may fail.
42
			$sites = wp_get_sites();
43
44
			foreach ( $sites as $site ) {
45
				switch_to_blog( $site['blog_id'] );
46
				$this->create_table();
47
				restore_current_blog();
48
			}
49
		} else {
50
			$this->create_table();
51
		}
52
	}
53
54
	/**
55
	 * Create email log table when a new blog is created.
56
	 */
57
	public function on_create_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
58
		if ( is_plugin_active_for_network( 'email-log/email-log.php' ) ) {
59
			switch_to_blog( $blog_id );
60
			$this->create_table();
61
			restore_current_blog();
62
		}
63
	}
64
65
	/**
66
	 * Add email log table to the list of tables deleted when a blog is deleted.
67
	 *
68
	 * @param  array $tables List of tables to be deleted.
69
	 *
70
	 * @return string[]  $tables Modified list of tables to be deleted.
71
	 */
72 2
	public function on_delete_blog( $tables ) {
73 2
		$tables[] = $this->get_log_table_name();
74
75 2
		return $tables;
76
	}
77
78
	/**
79
	 * Get email log table name.
80
	 *
81
	 * @return string Email Log Table name.
82
	 */
83 4
	public function get_log_table_name() {
84 4
		global $wpdb;
85
86 4
		return $wpdb->prefix . self::LOG_TABLE_NAME;
87
	}
88
89
	/**
90
	 * Insert log data into DB.
91
	 *
92
	 * @param array $data Data to be inserted.
93
	 */
94
	public function insert_log( $data ) {
95
		global $wpdb;
96
97
		$table_name = $this->get_log_table_name();
98
		$wpdb->insert( $table_name, $data );
99
	}
100
101
	/**
102
	 * Delete log entires by ids.
103
	 *
104
	 * @param string $ids Comma seperated list of log ids.
105
	 *
106
	 * @return false|int Number of log entries that got deleted. False on failure.
107
	 */
108
	public function delete_logs_by_id( $ids ) {
109
		global $wpdb;
110
111
		// Can't use wpdb->prepare for the below query. If used it results in this bug
112
		// https://github.com/sudar/email-log/issues/13
113
114
		$ids        = esc_sql( $ids );
115
		$table_name = $this->get_log_table_name();
116
117
		return $wpdb->query( "DELETE FROM $table_name where id IN ( $ids )" ); //@codingStandardsIgnoreLine
118
	}
119
120
	/**
121
	 * Delete all log entries.
122
	 *
123
	 * @return false|int Number of log entries that got deleted. False on failure.
124
	 */
125
	public function delete_all_logs() {
126
		global $wpdb;
127
128
		$table_name = $this->get_log_table_name();
129
130
		return $wpdb->query( "DELETE FROM $table_name" ); //@codingStandardsIgnoreLine
131
	}
132
133
	/**
134
	 * Get message by log id.
135
	 *
136
	 * @param int $id Id of the log whose message is needed.
137
	 *
138
	 * @return null|string Message of the log with $id.
139
	 */
140
	public function get_log_message( $id ) {
141
		global $wpdb;
142
143
		$table_name = $this->get_log_table_name();
144
		$query      = $wpdb->prepare( 'SELECT message FROM ' . $table_name . ' WHERE id = %d', $id );
145
146
		return $wpdb->get_var( $query );
147
	}
148
149
	/**
150
	 * Fetch log items.
151
	 *
152
	 * @param array $request         Request object.
153
	 * @param int   $per_page        Entries per page.
154
	 * @param int   $current_page_no Current page no.
155
	 *
156
	 * @return array Log entries and total items count.
157
	 */
158
	public function fetch_log_items( $request, $per_page, $current_page_no ) {
159
		global $wpdb;
160
		$table_name = $this->get_log_table_name();
161
162
		$query       = 'SELECT * FROM ' . $table_name;
163
		$count_query = 'SELECT count(*) FROM ' . $table_name;
164
		$query_cond  = '';
165
166
		if ( isset( $request['s'] ) ) {
167
			$search_term = trim( esc_sql( $request['s'] ) );
168
			$query_cond .= " WHERE to_email LIKE '%$search_term%' OR subject LIKE '%$search_term%' ";
1 ignored issue
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $search_term instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
169
		}
170
171
		// Ordering parameters.
172
		$orderby = ! empty( $request['orderby'] ) ? esc_sql( $request['orderby'] ) : 'sent_date';
173
		$order   = ! empty( $request['order'] ) ? esc_sql( $request['order'] ) : 'DESC';
174
175
		if ( ! empty( $orderby ) & ! empty( $order ) ) {
176
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
177
		}
178
179
		// Find total number of items.
180
		$count_query = $count_query . $query_cond;
181
		$total_items = $wpdb->get_var( $count_query );
182
183
		// Adjust the query to take pagination into account.
184
		if ( ! empty( $current_page_no ) && ! empty( $per_page ) ) {
185
			$offset = ( $current_page_no - 1 ) * $per_page;
186
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
187
		}
188
189
		// Fetch the items.
190
		$query = $query . $query_cond;
191
		$items = $wpdb->get_results( $query );
192
193
		return array( $items, $total_items );
194
	}
195
196
	/**
197
	 * Create email log table.
198
	 *
199
	 * @access private
200
	 *
201
	 * @global object $wpdb
202
	 */
203
	private function create_table() {
204
		global $wpdb;
205
206
		$table_name      = $this->get_log_table_name();
207
		$charset_collate = $wpdb->get_charset_collate();
208
209
		if ( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
210
211
			$sql = 'CREATE TABLE ' . $table_name . ' (
212
				id mediumint(9) NOT NULL AUTO_INCREMENT,
213
				to_email VARCHAR(100) NOT NULL,
214
				subject VARCHAR(250) NOT NULL,
215
				message TEXT NOT NULL,
216
				headers TEXT NOT NULL,
217
				attachments TEXT NOT NULL,
218
				sent_date timestamp NOT NULL,
219
				PRIMARY KEY  (id)
220
			) ' . $charset_collate . ' ;';
221
222
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
223
			dbDelta( $sql );
224
225
			add_option( self::DB_OPTION_NAME, self::DB_VERSION );
226
		}
227
	}
228
229
	/**
230
	 * Fetch log item by ID.
231
	 *
232
	 * @param int $id ID of the log item to be retrieved.
233
	 * @return array  Log item.
234
	 */
235
	public function fetch_log_item_by_id( $id ) {
236
		global $wpdb;
237
		$table_name = $this->get_log_table_name();
238
239
		$query      = $wpdb->prepare( 'SELECT * FROM ' . $table_name . ' WHERE id = %d', $id );
240
		return $wpdb->get_results( $query );
241
	}
242
243
    /**
244
     * Deletes Email Logs older than the specified interval.
245
     *
246
     * @param $interval_in_days
247
     * @return int
248
     */
249
	public function delete_logs_older_than( $interval_in_days ) {
250
        global $wpdb;
251
        $table_name = $this->get_log_table_name();
252
253
        $query      = $wpdb->prepare( 'DELETE FROM ' . $table_name . ' WHERE sent_date < DATE_SUB( CURDATE(), INTERVAL %d DAY )', $interval_in_days );
254
255
        return $wpdb->query( $query );
256
    }
257
}
258