Completed
Push — master ( 8bffa3...d70731 )
by Sudar
06:01 queued 03:08
created

LogTable::prepare_items()   C

Complexity

Conditions 7
Paths 32

Size

Total Lines 51
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 28
c 1
b 0
f 1
nc 32
nop 0
dl 0
loc 51
ccs 0
cts 33
cp 0
crap 56
rs 6.9743

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace EmailLog\Core\UI;
2
3
use EmailLog\Core\DB\TableManager;
4
use EmailLog\Core\EmailLog as EmailLog;
5
6
if ( ! class_exists( 'WP_List_Table' ) ) {
7
	require_once ABSPATH . WPINC . '/class-wp-list-table.php';
8
}
9
10
/**
11
 * Table to display Email Logs.
12
 *
13
 * Based on Custom List Table Example by Matt Van Andel.
14
 *
15
 * @author  Sudar
16
 * @package Email Log
17
 */
18
class LogTable extends \WP_List_Table {
19
20
	/**
21
	 * Set up a constructor that references the parent constructor.
22
	 *
23
	 * We use the parent reference to set some default configs.
24
	 */
25
	public function __construct() {
26
		parent::__construct( array(
27
			'singular'  => 'email-log',     //singular name of the listed records
28
			'plural'    => 'email-logs',    //plural name of the listed records
29
			'ajax'      => false,           //does this table support ajax?
30
		) );
31
	}
32
33
	/**
34
	 * Adds extra markup in the toolbars before or after the list.
35
	 *
36
	 * @access protected
37
	 *
38
	 * @param string $which Add the markup after (bottom) or before (top) the list.
39
	 */
40
	protected function extra_tablenav( $which ) {
41
		if ( 'top' == $which ) {
42
			// The code that goes before the table is here.
43
			echo '<span id = "el-pro-msg">';
44
			_e( 'More fields are available in Pro addon. ', 'email-log' );
45
			echo '<a href = "http://sudarmuthu.com/out/buy-email-log-more-fields-addon" style = "color:red">';
46
			_e( 'Buy Now', 'email-log' );
47
			echo '</a>';
48
			echo '</span>';
49
		}
50
51
		if ( 'bottom' == $which ) {
52
			// The code that goes after the table is here.
53
			echo '<p>&nbsp;</p>';
54
			echo '<p>&nbsp;</p>';
55
56
			echo '<p>';
57
			_e( 'The following are the list of pro addons that are currently available for purchase.', 'email-log' );
58
			echo '</p>';
59
60
			echo '<ul style="list-style:disc; padding-left:35px">';
61
62
			echo '<li>';
63
			echo '<strong>', __( 'Email Log - Resend Email', 'email-log' ), '</strong>', ' - ';
64
			echo __( 'Adds the ability to resend email from logs.', 'email-log' );
65
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#resend-email-addon">', __( 'More Info', 'email-log' ), '</a>.';
66
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-resend-email-addon">', __( 'Buy now', 'email-log' ), '</a>';
67
			echo '</li>';
68
69
			echo '<li>';
70
			echo '<strong>', __( 'Email Log - More fields', 'email-log' ), '</strong>', ' - ';
71
			echo __( 'Adds more fields (From, CC, BCC, Reply To, Attachment) to the logs page.', 'email-log' );
72
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#more-fields-addon">', __( 'More Info', 'email-log' ), '</a>.';
73
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-more-fields-addon">', __( 'Buy now', 'email-log' ), '</a>';
74
			echo '</li>';
75
76
			echo '<li>';
77
			echo '<strong>', __( 'Email Log - Forward Email', 'email-log' ), '</strong>', ' - ';
78
			echo __( 'This addon allows you to send a copy of all emails send from WordPress to another email address', 'email-log' );
79
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#forward-email-addon">', __( 'More Info', 'email-log' ), '</a>.';
80
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-forward-email-addon">', __( 'Buy now', 'email-log' ), '</a>';
81
			echo '</li>';
82
83
			echo '</ul>';
84
		}
85
	}
86
87
	/**
88
	 * Returns the list of column and title names.
89
	 *
90
	 * @see WP_List_Table::::single_row_columns()
91
	 *
92
	 * @return array An associative array containing column information: 'slugs'=>'Visible Titles'.
93
	 */
94
	public function get_columns() {
95
		$columns = array(
96
			'cb'        => '<input type="checkbox" />', //Render a checkbox instead of text
97
			'sent_date' => __( 'Sent at', 'email-log' ),
98
			'to'        => __( 'To', 'email-log' ),
99
			'subject'   => __( 'Subject', 'email-log' ),
100
		);
101
102
		return apply_filters( EmailLog::HOOK_LOG_COLUMNS, $columns );
103
	}
104
105
	/**
106
	 * Returns the list of columns.
107
	 *
108
	 * @access protected
109
	 *
110
	 * @return array An associative array containing all the columns that should be sortable: 'slugs'=>array('data_values',bool).
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,array<string|boolean>>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
111
	 */
112
	protected function get_sortable_columns() {
113
		$sortable_columns = array(
114
			'sent_date'   => array( 'sent_date', true ), //true means it's already sorted
115
			'to'          => array( 'to_email', false ),
116
			'subject'     => array( 'subject', false ),
117
		);
118
		return $sortable_columns;
119
	}
120
121
	/**
122
	 * Returns value for default columns.
123
	 *
124
	 * @access protected
125
	 *
126
	 * @param object $item
127
	 * @param string $column_name
128
	 */
129
	protected function column_default( $item, $column_name ) {
130
		do_action( EmailLog::HOOK_LOG_DISPLAY_COLUMNS, $column_name, $item );
131
	}
132
133
	/**
134
	 * Display sent date column.
135
	 *
136
	 * @access protected
137
	 *
138
	 * @param  object $item Current item object.
139
	 * @return string       Markup to be displayed for the column.
140
	 */
141
	protected function column_sent_date( $item ) {
142
		$email_date = mysql2date(
143
			sprintf( __( '%s @ %s', 'email-log' ), get_option( 'date_format', 'F j, Y' ), get_option( 'time_format', 'g:i A' ) ),
144
			$item->sent_date
145
		);
146
147
		$actions = array();
148
149
		$content_ajax_url = add_query_arg(
150
			array(
151
				'action'    => 'display_content',
152
				'email_id'  => $item->id,
153
				'TB_iframe' => 'true',
154
				'width'     => '600',
155
				'height'    => '550',
156
			),
157
			'admin-ajax.php'
158
		);
159
160
		$actions['view-content'] = sprintf( '<a href="%1$s" class="thickbox" title="%2$s">%3$s</a>',
161
			esc_url( $content_ajax_url ),
162
			__( 'Email Content', 'email-log' ),
163
			__( 'View Content', 'email-log' )
164
		);
165
166
		$delete_url = add_query_arg(
167
			array(
168
				'page'                           => $_REQUEST['page'],
169
				'action'                         => 'delete',
170
				$this->_args['singular']         => $item->id,
171
				EmailLog::DELETE_LOG_NONCE_FIELD => wp_create_nonce( EmailLog::DELETE_LOG_ACTION ),
172
			)
173
		);
174
175
		$actions['delete'] = sprintf( '<a href="%s">%s</a>',
176
			esc_url( $delete_url ),
177
			__( 'Delete', 'email-log' )
178
		);
179
180
		/**
181
		 * This filter can be used to modify the list of row actions that are displayed.
182
		 *
183
		 * @since 1.8
184
		 *
185
		 * @param array $actions List of actions.
186
		 * @param object $item The current log item.
187
		 */
188
		$actions = apply_filters( 'el_row_actions', $actions, $item );
189
190
		return sprintf( '%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
191
			/*$1%s*/ $email_date,
192
			/*$2%s*/ $item->id,
193
			/*$3%s*/ $this->row_actions( $actions )
194
		);
195
	}
196
197
	/**
198
	 * To field.
199
	 *
200
	 * @access protected
201
	 *
202
	 * @param object $item
203
	 * @return string
204
	 */
205
	protected function column_to( $item ) {
206
		return esc_html( $item->to_email );
207
	}
208
209
	/**
210
	 * Subject field.
211
	 *
212
	 * @access protected
213
	 *
214
	 * @param object $item
215
	 * @return string
216
	 */
217
	protected function column_subject( $item ) {
218
		return esc_html( $item->subject );
219
	}
220
221
	/**
222
	 * Markup for action column.
223
	 *
224
	 * @access protected
225
	 *
226
	 * @param object $item
227
	 * @return string
228
	 */
229
	protected function column_cb( $item ) {
230
		return sprintf(
231
			'<input type="checkbox" name="%1$s[]" value="%2$s" />',
232
			/*$1%s*/ $this->_args['singular'],
233
			/*$2%s*/ $item->id
234
		);
235
	}
236
237
	/**
238
	 * Specify the list of bulk actions.
239
	 *
240
	 * @access protected
241
	 *
242
	 * @return array An associative array containing all the bulk actions: 'slugs'=>'Visible Titles'.
243
	 */
244
	protected function get_bulk_actions() {
245
		$actions = array(
246
			'delete'     => __( 'Delete', 'email-log' ),
247
			'delete-all' => __( 'Delete All Logs', 'email-log' ),
248
		);
249
		return $actions;
250
	}
251
252
	/**
253
	 * Handles bulk actions.
254
	 *
255
	 * @see $this->prepare_items()
256
	 */
257
	public function process_bulk_action() {
258
		global $wpdb;
259
260
		$email_log = email_log();
261
262
		if ( 'delete' === $this->current_action() ) {
263
			// Delete a list of logs by id.
264
265
			$nonce = $_REQUEST[ EmailLog::DELETE_LOG_NONCE_FIELD ];
266
			if ( wp_verify_nonce( $nonce, EmailLog::DELETE_LOG_ACTION ) ) {
267
268
				$ids = $_GET[ $this->_args['singular'] ];
269
270
				if ( is_array( $ids ) ) {
271
					$selected_ids = implode( ',', $ids );
272
				} else {
273
					$selected_ids = $ids;
274
				}
275
276
				// Can't use wpdb->prepare for the below query. If used it results in this bug
277
				// https://github.com/sudar/email-log/issues/13
278
279
				$selected_ids = esc_sql( $selected_ids );
280
281
				$table_name = $wpdb->prefix . TableManager::TABLE_NAME;
282
				// TODO: move this logic away from Email Log class
283
				$email_log->logs_deleted = $wpdb->query( "DELETE FROM $table_name where id IN ( $selected_ids )" ); //@codingStandardsIgnoreLine
284
			} else {
285
				wp_die( 'Cheating, Huh? ' );
286
			}
287
		} elseif ( 'delete-all' === $this->current_action() ) {
288
			// Delete all logs.
289
			$nonce = $_REQUEST[ EmailLog::DELETE_LOG_NONCE_FIELD ];
290
			if ( wp_verify_nonce( $nonce, EmailLog::DELETE_LOG_ACTION ) ) {
291
				$table_name = $wpdb->prefix . TableManager::TABLE_NAME;
292
				$email_log->logs_deleted = $wpdb->query( "DELETE FROM $table_name" ); //@codingStandardsIgnoreLine
293
			} else {
294
				wp_die( 'Cheating, Huh? ' );
295
			}
296
		}
297
	}
298
299
	/**
300
	 * Prepare data for display.
301
	 */
302
	public function prepare_items() {
303
		global $wpdb;
304
305
		$table_name = $wpdb->prefix . TableManager::TABLE_NAME;
306
		$this->_column_headers = $this->get_column_info();
307
308
		// Handle bulk actions.
309
		$this->process_bulk_action();
310
311
		// Get current page number.
312
		$current_page = $this->get_pagenum();
313
314
		$query = 'SELECT * FROM ' . $table_name;
315
		$count_query = 'SELECT count(*) FROM ' . $table_name;
316
		$query_cond = '';
317
318
		if ( isset( $_GET['s'] ) ) {
319
			$search_term = trim( esc_sql( $_GET['s'] ) );
320
			$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...
321
		}
322
323
		// Ordering parameters.
324
		$orderby = ! empty( $_GET['orderby'] ) ? esc_sql( $_GET['orderby'] ) : 'sent_date';
325
		$order   = ! empty( $_GET['order'] ) ? esc_sql( $_GET['order'] ) : 'DESC';
326
327
		if ( ! empty( $orderby ) & ! empty( $order ) ) {
328
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
329
		}
330
331
		// Find total number of items.
332
		$count_query = $count_query . $query_cond;
333
		$total_items = $wpdb->get_var( $count_query );
334
335
		// Adjust the query to take pagination into account.
336
		$per_page = EmailLog::get_per_page();
337
		if ( ! empty( $current_page ) && ! empty( $per_page ) ) {
338
			$offset = ( $current_page - 1 ) * $per_page;
339
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
340
		}
341
342
		// Fetch the items.
343
		$query = $query . $query_cond;
344
		$this->items = $wpdb->get_results( $query );
345
346
		// Register pagination options & calculations.
347
		$this->set_pagination_args( array(
348
			'total_items' => $total_items,
349
			'per_page'    => $per_page,
350
			'total_pages' => ceil( $total_items / $per_page ),
351
		) );
352
	}
353
354
	/**
355
	 * Displays default message when no items are found.
356
	 */
357
	public function no_items() {
358
		_e( 'Your email log is empty', 'email-log' );
359
	}
360
}
361