Completed
Push — issues/611 ( 661115...758b1c )
by Ravinder
21:11
created

Give_API_Keys_Table::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 29 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * API Key Table Class
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Tools/APIKeys
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.1
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
// Load WP_List_Table if not loaded
18
if ( ! class_exists( 'WP_List_Table' ) ) {
19
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
20
}
21
22
/**
23
 * Give_API_Keys_Table Class
24
 *
25
 * Renders the API Keys table
26
 *
27
 * @since 1.1
28
 */
29
class Give_API_Keys_Table extends WP_List_Table {
30
31
	/**
32
	 * @var int Number of items per page
33
	 * @since 1.1
34
	 */
35
	public $per_page = 30;
36
37
	/**
38
	 * @var object Query results
39
	 * @since 1.1
40
	 */
41
	private $keys;
0 ignored issues
show
Unused Code introduced by
The property $keys is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
42
43
	/**
44
	 * Get things started
45
	 *
46
	 * @since 1.1
47
	 * @see   WP_List_Table::__construct()
48
	 *
49
	 * @global $status
50
	 * @global $page
51
	 */
52
	public function __construct() {
53
		global $status, $page;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
54
55
		// Set parent defaults
56
		parent::__construct( array(
57
			'singular' => esc_html__( 'API Key', 'give' ),     // Singular name of the listed records
58
			'plural'   => esc_html__( 'API Keys', 'give' ),    // Plural name of the listed records
59
			'ajax'     => false,// Does this table support ajax?
60
		) );
61
62
		$this->query();
63
	}
64
65
	/**
66
	 * This function renders most of the columns in the list table.
67
	 *
68
	 * @access public
69
	 * @since  1.1
70
	 *
71
	 * @param array  $item        Contains all the data of the keys
72
	 * @param string $column_name The name of the column
73
	 *
74
	 * @return string Column Name
75
	 */
76
	public function column_default( $item, $column_name ) {
77
		return $item[ $column_name ];
78
	}
79
80
	/**
81
	 * Displays the public key rows
82
	 *
83
	 * @access public
84
	 * @since  1.1
85
	 *
86
	 * @param array $item Contains all the data of the keys
87
	 *
88
	 * @return string Column Name
89
	 */
90
	public function column_key( $item ) {
91
		return '<input onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" type="text" class="large-text" value="' . esc_attr( $item['key'] ) . '"/>';
92
	}
93
94
	/**
95
	 * Displays the token rows
96
	 *
97
	 * @access public
98
	 * @since  1.1
99
	 *
100
	 * @param array $item Contains all the data of the keys
101
	 *
102
	 * @return string Column Name
103
	 */
104
	public function column_token( $item ) {
105
		return '<input onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" type="text" class="large-text" value="' . esc_attr( $item['token'] ) . '"/>';
106
	}
107
108
	/**
109
	 * Displays the secret key rows
110
	 *
111
	 * @access public
112
	 * @since  1.1
113
	 *
114
	 * @param array $item Contains all the data of the keys
115
	 *
116
	 * @return string Column Name
117
	 */
118
	public function column_secret( $item ) {
119
		return '<input onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" type="text" class="large-text" value="' . esc_attr( $item['secret'] ) . '"/>';
120
	}
121
122
	/**
123
	 * Renders the column for the user field
124
	 *
125
	 * @access public
126
	 * @since  1.1
127
	 * @return string
128
	 */
129
	public function column_user( $item ) {
130
131
		$actions = array();
132
133
		if ( apply_filters( 'give_api_log_requests', true ) ) {
134
			$actions['view'] = sprintf(
135
				'<a href="%s">%s</a>',
136
				esc_url( add_query_arg( array(
137
					'section'   => 'api_requests',
138
					'post_type' => 'give_forms',
139
					'page'      => 'give-tools',
140
					'tab'       => 'logs',
141
					's'         => $item['email'],
142
				), 'edit.php' ) ),
143
				esc_html__( 'View API Log', 'give' )
144
			);
145
		}
146
147
		$actions['reissue'] = sprintf(
148
			'<a href="%s" class="give-regenerate-api-key">%s</a>',
149
			esc_url( wp_nonce_url( add_query_arg( array(
150
				'user_id'          => $item['id'],
151
				'give_action'      => 'process_api_key',
152
				'give_api_process' => 'regenerate',
153
			) ), 'give-api-nonce' ) ),
154
			esc_html__( 'Reissue', 'give' )
155
		);
156
		$actions['revoke']  = sprintf(
157
			'<a href="%s" class="give-revoke-api-key give-delete">%s</a>',
158
			esc_url( wp_nonce_url( add_query_arg( array(
159
				'user_id'          => $item['id'],
160
				'give_action'      => 'process_api_key',
161
				'give_api_process' => 'revoke',
162
			) ), 'give-api-nonce' ) ),
163
			esc_html__( 'Revoke', 'give' )
164
		);
165
166
		$actions = apply_filters( 'give_api_row_actions', array_filter( $actions ) );
167
168
		return sprintf( '%1$s %2$s', $item['user'], $this->row_actions( $actions ) );
169
	}
170
171
	/**
172
	 * Gets the name of the primary column.
173
	 *
174
	 * @since  1.5
175
	 * @access protected
176
	 *
177
	 * @return string Name of the primary column.
178
	 */
179
	protected function get_primary_column_name() {
180
		return 'user';
181
	}
182
183
	/**
184
	 * Retrieve the table columns
185
	 *
186
	 * @access public
187
	 * @since  1.1
188
	 * @return array $columns Array of all the list table columns
189
	 */
190
	public function get_columns() {
191
		$columns = array(
192
			'user'   => esc_html__( 'Username', 'give' ),
193
			'key'    => esc_html__( 'Public Key', 'give' ),
194
			'token'  => esc_html__( 'Token', 'give' ),
195
			'secret' => esc_html__( 'Secret Key', 'give' ),
196
		);
197
198
		return $columns;
199
	}
200
201
	/**
202
	 * Generate the table navigation above or below the table
203
	 *
204
	 * @since  3.1.0
205
	 * @access protected
206
	 *
207
	 * @param string $which
208
	 */
209
	protected function display_tablenav( $which ) {
210
		if ( 'top' === $which ) {
211
			wp_nonce_field( 'bulk-' . $this->_args['plural'] );
212
		}
213
		?>
214
		<div class="tablenav <?php echo esc_attr( $which ); ?>">
215
216
			<div class="alignleft actions bulkactions">
217
				<?php $this->bulk_actions( $which ); ?>
218
			</div>
219
220
			<?php
221
			$this->extra_tablenav( $which );
222
			$this->pagination( $which );
223
			?>
224
225
			<br class="clear"/>
226
		</div>
227
		<?php
228
	}
229
230
	/**
231
	 * Display the key generation form
232
	 *
233
	 * @access public
234
	 * @since  1.1
235
	 *
236
	 * @param  string $which
237
	 *
238
	 * @return void
239
	 */
240
	function bulk_actions( $which = '' ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
241
		// These aren't really bulk actions but this outputs the markup in the right place
242
		static $give_api_is_bottom;
243
244
		if ( $give_api_is_bottom ) {
245
			return;
246
		}
247
		?>
248
		<input type="hidden" name="give_action" value="process_api_key"/>
249
		<input type="hidden" name="give_api_process" value="generate"/>
250
		<?php wp_nonce_field( 'give-api-nonce' ); ?>
251
		<?php echo Give()->html->ajax_user_search(); ?>
252
		<?php submit_button( esc_html__( 'Generate New API Keys', 'give' ), 'secondary', 'submit', false ); ?>
253
		<?php
254
		$give_api_is_bottom = true;
255
	}
256
257
	/**
258
	 * Retrieve the current page number
259
	 *
260
	 * @access public
261
	 * @since  1.1
262
	 * @return int Current page number
263
	 */
264
	public function get_paged() {
265
		return isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
266
	}
267
268
	/**
269
	 * Performs the key query
270
	 *
271
	 * @access public
272
	 * @since  1.1
273
	 * @return array
274
	 */
275
	public function query() {
276
		$users = get_users( array(
277
			'meta_value' => 'give_user_secret_key',
278
			'number'     => $this->per_page,
279
			'offset'     => $this->per_page * ( $this->get_paged() - 1 ),
280
		) );
281
		$keys  = array();
282
283
		foreach ( $users as $user ) {
284
			$keys[ $user->ID ]['id']    = $user->ID;
285
			$keys[ $user->ID ]['email'] = $user->user_email;
286
			$keys[ $user->ID ]['user']  = '<a href="' . add_query_arg( 'user_id', $user->ID, 'user-edit.php' ) . '"><strong>' . $user->user_login . '</strong></a>';
287
288
			$keys[ $user->ID ]['key']    = Give()->api->get_user_public_key( $user->ID );
289
			$keys[ $user->ID ]['secret'] = Give()->api->get_user_secret_key( $user->ID );
290
			$keys[ $user->ID ]['token']  = Give()->api->get_token( $user->ID );
291
		}
292
293
		return $keys;
294
	}
295
296
297
	/**
298
	 * Retrieve count of total users with keys
299
	 *
300
	 * @access public
301
	 * @since  1.1
302
	 * @return int
303
	 */
304
	public function total_items() {
305
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
306
307
		if ( ! get_transient( 'give_total_api_keys' ) ) {
308
			$total_items = $wpdb->get_var( "SELECT count(user_id) FROM $wpdb->usermeta WHERE meta_value='give_user_secret_key'" );
309
310
			set_transient( 'give_total_api_keys', $total_items, 60 * 60 );
311
		}
312
313
		return get_transient( 'give_total_api_keys' );
314
	}
315
316
	/**
317
	 * Setup the final data for the table
318
	 *
319
	 * @access public
320
	 * @since  1.1
321
	 * @return void
322
	 */
323
	public function prepare_items() {
324
		$columns = $this->get_columns();
325
326
		$hidden   = array(); // No hidden columns
327
		$sortable = array(); // Not sortable... for now
328
329
		$this->_column_headers = array( $columns, $hidden, $sortable );
330
331
		$data = $this->query();
332
333
		$total_items = $this->total_items();
334
335
		$this->items = $data;
336
337
		$this->set_pagination_args( array(
338
				'total_items' => $total_items,
339
				'per_page'    => $this->per_page,
340
				'total_pages' => ceil( $total_items / $this->per_page ),
341
			)
342
		);
343
	}
344
}
345