Completed
Push — feature/45-drop-php-52 ( f96425 )
by Sudar
11:51
created

LogTable::prepare_items()   C

Complexity

Conditions 7
Paths 32

Size

Total Lines 51
Code Lines 28

Duplication

Lines 0
Ratio 0 %

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
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\EmailLog as EmailLog;
4
5
if ( ! class_exists( 'WP_List_Table' ) ) {
6
	require_once ABSPATH . WPINC . '/class-wp-list-table.php';
7
}
8
9
/**
10
 * Table to display Email Logs.
11
 *
12
 * Based on Custom List Table Example by Matt Van Andel.
13
 *
14
 * @author  Sudar
15
 * @package Email Log
16
 */
17
class LogTable extends \WP_List_Table {
18
19
	/**
20
	 * Set up a constructor that references the parent constructor.
21
	 *
22
	 * We use the parent reference to set some default configs.
23
	 */
24
	public function __construct() {
25
		parent::__construct( array(
26
			'singular'  => 'email-log',     //singular name of the listed records
27
			'plural'    => 'email-logs',    //plural name of the listed records
28
			'ajax'      => false,           //does this table support ajax?
29
		) );
30
	}
31
32
	/**
33
	 * Adds extra markup in the toolbars before or after the list.
34
	 *
35
	 * @access protected
36
	 *
37
	 * @param string $which Add the markup after (bottom) or before (top) the list.
38
	 */
39
	protected function extra_tablenav( $which ) {
40
		if ( 'top' == $which ) {
41
			// The code that goes before the table is here.
42
			echo '<span id = "el-pro-msg">';
43
			_e( 'More fields are available in Pro addon. ', 'email-log' );
44
			echo '<a href = "http://sudarmuthu.com/out/buy-email-log-more-fields-addon" style = "color:red">';
45
			_e( 'Buy Now', 'email-log' );
46
			echo '</a>';
47
			echo '</span>';
48
		}
49
50
		if ( 'bottom' == $which ) {
51
			// The code that goes after the table is here.
52
			echo '<p>&nbsp;</p>';
53
			echo '<p>&nbsp;</p>';
54
55
			echo '<p>';
56
			_e( 'The following are the list of pro addons that are currently available for purchase.', 'email-log' );
57
			echo '</p>';
58
59
			echo '<ul style="list-style:disc; padding-left:35px">';
60
61
			echo '<li>';
62
			echo '<strong>', __( 'Email Log - Resend Email', 'email-log' ), '</strong>', ' - ';
63
			echo __( 'Adds the ability to resend email from logs.', 'email-log' );
64
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#resend-email-addon">', __( 'More Info', 'email-log' ), '</a>.';
65
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-resend-email-addon">', __( 'Buy now', 'email-log' ), '</a>';
66
			echo '</li>';
67
68
			echo '<li>';
69
			echo '<strong>', __( 'Email Log - More fields', 'email-log' ), '</strong>', ' - ';
70
			echo __( 'Adds more fields (From, CC, BCC, Reply To, Attachment) to the logs page.', 'email-log' );
71
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#more-fields-addon">', __( 'More Info', 'email-log' ), '</a>.';
72
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-more-fields-addon">', __( 'Buy now', 'email-log' ), '</a>';
73
			echo '</li>';
74
75
			echo '<li>';
76
			echo '<strong>', __( 'Email Log - Forward Email', 'email-log' ), '</strong>', ' - ';
77
			echo __( 'This addon allows you to send a copy of all emails send from WordPress to another email address', 'email-log' );
78
			echo ' <a href = "http://sudarmuthu.com/wordpress/email-log/pro-addons#forward-email-addon">', __( 'More Info', 'email-log' ), '</a>.';
79
			echo ' <a href = "http://sudarmuthu.com/out/buy-email-log-forward-email-addon">', __( 'Buy now', 'email-log' ), '</a>';
80
			echo '</li>';
81
82
			echo '</ul>';
83
		}
84
	}
85
86
	/**
87
	 * Returns the list of column and title names.
88
	 *
89
	 * @see WP_List_Table::::single_row_columns()
90
	 *
91
	 * @return array An associative array containing column information: 'slugs'=>'Visible Titles'.
92
	 */
93
	public function get_columns() {
94
		$columns = array(
95
			'cb'        => '<input type="checkbox" />', //Render a checkbox instead of text
96
			'sent_date' => __( 'Sent at', 'email-log' ),
97
			'to'        => __( 'To', 'email-log' ),
98
			'subject'   => __( 'Subject', 'email-log' ),
99
		);
100
101
		return apply_filters( EmailLog::HOOK_LOG_COLUMNS, $columns );
102
	}
103
104
	/**
105
	 * Returns the list of columns.
106
	 *
107
	 * @access protected
108
	 *
109
	 * @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...
110
	 */
111
	protected function get_sortable_columns() {
112
		$sortable_columns = array(
113
			'sent_date'   => array( 'sent_date', true ), //true means it's already sorted
114
			'to'          => array( 'to_email', false ),
115
			'subject'     => array( 'subject', false ),
116
		);
117
		return $sortable_columns;
118
	}
119
120
	/**
121
	 * Returns value for default columns.
122
	 *
123
	 * @access protected
124
	 *
125
	 * @param object $item
126
	 * @param string $column_name
127
	 */
128
	protected function column_default( $item, $column_name ) {
129
		do_action( EmailLog::HOOK_LOG_DISPLAY_COLUMNS, $column_name, $item );
130
	}
131
132
	/**
133
	 * Display sent date column.
134
	 *
135
	 * @access protected
136
	 *
137
	 * @param  object $item Current item object.
138
	 * @return string       Markup to be displayed for the column.
139
	 */
140
	protected function column_sent_date( $item ) {
141
		$email_date = mysql2date(
142
			sprintf( __( '%s @ %s', 'email-log' ), get_option( 'date_format', 'F j, Y' ), get_option( 'time_format', 'g:i A' ) ),
143
			$item->sent_date
144
		);
145
146
		$actions = array();
147
148
		$content_ajax_url = add_query_arg(
149
			array(
150
				'action'    => 'display_content',
151
				'email_id'  => $item->id,
152
				'TB_iframe' => 'true',
153
				'width'     => '600',
154
				'height'    => '550',
155
			),
156
			'admin-ajax.php'
157
		);
158
159
		$actions['view-content'] = sprintf( '<a href="%1$s" class="thickbox" title="%2$s">%3$s</a>',
160
			esc_url( $content_ajax_url ),
161
			__( 'Email Content', 'email-log' ),
162
			__( 'View Content', 'email-log' )
163
		);
164
165
		$delete_url = add_query_arg(
166
			array(
167
				'page'                           => $_REQUEST['page'],
168
				'action'                         => 'delete',
169
				$this->_args['singular']         => $item->id,
170
				EmailLog::DELETE_LOG_NONCE_FIELD => wp_create_nonce( EmailLog::DELETE_LOG_ACTION ),
171
			)
172
		);
173
174
		$actions['delete'] = sprintf( '<a href="%s">%s</a>',
175
			esc_url( $delete_url ),
176
			__( 'Delete', 'email-log' )
177
		);
178
179
		/**
180
		 * This filter can be used to modify the list of row actions that are displayed.
181
		 *
182
		 * @since 1.8
183
		 *
184
		 * @param array $actions List of actions.
185
		 * @param object $item The current log item.
186
		 */
187
		$actions = apply_filters( 'el_row_actions', $actions, $item );
188
189
		return sprintf( '%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
190
			/*$1%s*/ $email_date,
191
			/*$2%s*/ $item->id,
192
			/*$3%s*/ $this->row_actions( $actions )
193
		);
194
	}
195
196
	/**
197
	 * To field.
198
	 *
199
	 * @access protected
200
	 *
201
	 * @param object $item
202
	 * @return string
203
	 */
204
	protected function column_to( $item ) {
205
		return esc_html( $item->to_email );
206
	}
207
208
	/**
209
	 * Subject field.
210
	 *
211
	 * @access protected
212
	 *
213
	 * @param object $item
214
	 * @return string
215
	 */
216
	protected function column_subject( $item ) {
217
		return esc_html( $item->subject );
218
	}
219
220
	/**
221
	 * Markup for action column.
222
	 *
223
	 * @access protected
224
	 *
225
	 * @param object $item
226
	 * @return string
227
	 */
228
	protected function column_cb( $item ) {
229
		return sprintf(
230
			'<input type="checkbox" name="%1$s[]" value="%2$s" />',
231
			/*$1%s*/ $this->_args['singular'],
232
			/*$2%s*/ $item->id
233
		);
234
	}
235
236
	/**
237
	 * Specify the list of bulk actions.
238
	 *
239
	 * @access protected
240
	 *
241
	 * @return array An associative array containing all the bulk actions: 'slugs'=>'Visible Titles'.
242
	 */
243
	protected function get_bulk_actions() {
244
		$actions = array(
245
			'delete'     => __( 'Delete', 'email-log' ),
246
			'delete-all' => __( 'Delete All Logs', 'email-log' ),
247
		);
248
		return $actions;
249
	}
250
251
	/**
252
	 * Handles bulk actions.
253
	 *
254
	 * @see $this->prepare_items()
255
	 */
256
	public function process_bulk_action() {
257
		global $wpdb;
258
259
		$email_log = email_log();
260
261
		if ( 'delete' === $this->current_action() ) {
262
			// Delete a list of logs by id.
263
264
			$nonce = $_REQUEST[ EmailLog::DELETE_LOG_NONCE_FIELD ];
265
			if ( wp_verify_nonce( $nonce, EmailLog::DELETE_LOG_ACTION ) ) {
266
267
				$ids = $_GET[ $this->_args['singular'] ];
268
269
				if ( is_array( $ids ) ) {
270
					$selected_ids = implode( ',', $ids );
271
				} else {
272
					$selected_ids = $ids;
273
				}
274
275
				// Can't use wpdb->prepare for the below query. If used it results in this bug
276
				// https://github.com/sudar/email-log/issues/13
277
278
				$selected_ids = esc_sql( $selected_ids );
279
280
				$table_name = $wpdb->prefix . EmailLog::TABLE_NAME;
281
				// TODO: move this logic away from Email Log class
282
				$email_log->logs_deleted = $wpdb->query( "DELETE FROM $table_name where id IN ( $selected_ids )" ); //@codingStandardsIgnoreLine
283
			} else {
284
				wp_die( 'Cheating, Huh? ' );
285
			}
286
		} elseif ( 'delete-all' === $this->current_action() ) {
287
			// Delete all logs.
288
			$nonce = $_REQUEST[ EmailLog::DELETE_LOG_NONCE_FIELD ];
289
			if ( wp_verify_nonce( $nonce, EmailLog::DELETE_LOG_ACTION ) ) {
290
				$table_name = $wpdb->prefix . EmailLog::TABLE_NAME;
291
				$email_log->logs_deleted = $wpdb->query( "DELETE FROM $table_name" ); //@codingStandardsIgnoreLine
292
			} else {
293
				wp_die( 'Cheating, Huh? ' );
294
			}
295
		}
296
	}
297
298
	/**
299
	 * Prepare data for display.
300
	 */
301
	public function prepare_items() {
302
		global $wpdb;
303
304
		$table_name = $wpdb->prefix . EmailLog::TABLE_NAME;
305
		$this->_column_headers = $this->get_column_info();
306
307
		// Handle bulk actions.
308
		$this->process_bulk_action();
309
310
		// Get current page number.
311
		$current_page = $this->get_pagenum();
312
313
		$query = 'SELECT * FROM ' . $table_name;
314
		$count_query = 'SELECT count(*) FROM ' . $table_name;
315
		$query_cond = '';
316
317
		if ( isset( $_GET['s'] ) ) {
318
			$search_term = trim( esc_sql( $_GET['s'] ) );
319
			$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...
320
		}
321
322
		// Ordering parameters.
323
		$orderby = ! empty( $_GET['orderby'] ) ? esc_sql( $_GET['orderby'] ) : 'sent_date';
324
		$order   = ! empty( $_GET['order'] ) ? esc_sql( $_GET['order'] ) : 'DESC';
325
326
		if ( ! empty( $orderby ) & ! empty( $order ) ) {
327
			$query_cond .= ' ORDER BY ' . $orderby . ' ' . $order;
328
		}
329
330
		// Find total number of items.
331
		$count_query = $count_query . $query_cond;
332
		$total_items = $wpdb->get_var( $count_query );
333
334
		// Adjust the query to take pagination into account.
335
		$per_page = EmailLog::get_per_page();
336
		if ( ! empty( $current_page ) && ! empty( $per_page ) ) {
337
			$offset = ( $current_page - 1 ) * $per_page;
338
			$query_cond .= ' LIMIT ' . (int) $offset . ',' . (int) $per_page;
339
		}
340
341
		// Fetch the items.
342
		$query = $query . $query_cond;
343
		$this->items = $wpdb->get_results( $query );
344
345
		// Register pagination options & calculations.
346
		$this->set_pagination_args( array(
347
			'total_items' => $total_items,
348
			'per_page'    => $per_page,
349
			'total_pages' => ceil( $total_items / $per_page ),
350
		) );
351
	}
352
353
	/**
354
	 * Displays default message when no items are found.
355
	 */
356
	public function no_items() {
357
		_e( 'Your email log is empty', 'email-log' );
358
	}
359
}
360