Completed
Push — master ( 398cde...bcdce8 )
by Mike
08:01
created

WC_Admin_Webhooks::bulk_untrash()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 13
rs 9.4286
cc 2
eloc 7
nc 2
nop 1
1
<?php
1 ignored issue
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 18 and the first side effect is on line 12.

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
 * WooCommerce Admin Webhooks Class
4
 *
5
 * @author   WooThemes
6
 * @category Admin
7
 * @package  WooCommerce/Admin
8
 * @version  2.4.0
9
 */
10
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit; // Exit if accessed directly
13
}
14
15
/**
16
 * WC_Admin_Webhooks.
17
 */
18
class WC_Admin_Webhooks {
19
20
	/**
21
	 * Initialize the webhooks admin actions.
22
	 */
23
	public function __construct() {
24
		add_action( 'admin_init', array( $this, 'actions' ) );
25
	}
26
27
	/**
28
	 * Check if is webhook settings page.
29
	 *
30
	 * @return bool
31
	 */
32 View Code Duplication
	private function is_webhook_settings_page() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
33
		return isset( $_GET['page'] )
34
			&& 'wc-settings' == $_GET['page']
35
			&& isset( $_GET['tab'] )
36
			&& 'api' == $_GET['tab']
37
			&& isset( $_GET['section'] )
38
			&& 'webhooks' == isset( $_GET['section'] );
39
	}
40
41
	/**
42
	 * Updated the Webhook name.
43
	 *
44
	 * @param int $webhook_id
45
	 */
46
	private function update_name( $webhook_id ) {
47
		global $wpdb;
48
49
		$name = ! empty( $_POST['webhook_name'] ) ? $_POST['webhook_name'] : sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) );
50
		$wpdb->update( $wpdb->posts, array( 'post_title' => $name ), array( 'ID' => $webhook_id ) );
51
	}
52
53
	/**
54
	 * Updated the Webhook status.
55
	 *
56
	 * @param WC_Webhook $webhook
57
	 */
58
	private function update_status( $webhook ) {
59
		$status = ! empty( $_POST['webhook_status'] ) ? wc_clean( $_POST['webhook_status'] ) : '';
60
61
		$webhook->update_status( $status );
62
	}
63
64
	/**
65
	 * Updated the Webhook delivery URL.
66
	 *
67
	 * @param WC_Webhook $webhook
68
	 */
69
	private function update_delivery_url( $webhook ) {
70
		$delivery_url = ! empty( $_POST['webhook_delivery_url'] ) ? $_POST['webhook_delivery_url'] : '';
71
72
		if ( wc_is_valid_url( $delivery_url ) ) {
73
			$webhook->set_delivery_url( $delivery_url );
74
		}
75
	}
76
77
	/**
78
	 * Updated the Webhook secret.
79
	 *
80
	 * @param WC_Webhook $webhook
81
	 */
82
	private function update_secret( $webhook ) {
83
		$secret = ! empty( $_POST['webhook_secret'] ) ? $_POST['webhook_secret'] : get_user_meta( get_current_user_id(), 'woocommerce_api_consumer_secret', true );
84
85
		$webhook->set_secret( $secret );
86
	}
87
88
	/**
89
	 * Updated the Webhook topic.
90
	 *
91
	 * @param WC_Webhook $webhook
92
	 */
93
	private function update_topic( $webhook ) {
94
		if ( ! empty( $_POST['webhook_topic'] ) ) {
95
96
			$resource = '';
97
			$event    = '';
98
99
			switch ( $_POST['webhook_topic'] ) {
100
				case 'custom' :
101
					if ( ! empty( $_POST['webhook_custom_topic'] ) ) {
102
						list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_custom_topic'] ) );
103
					}
104
					break;
105
				case 'action' :
106
					$resource = 'action';
107
					$event    = ! empty( $_POST['webhook_action_event'] ) ? wc_clean( $_POST['webhook_action_event'] ) : '';
108
					break;
109
110
				default :
111
					list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_topic'] ) );
112
					break;
113
			}
114
115
			$topic = $resource . '.' . $event;
116
117
			if ( wc_is_webhook_valid_topic( $topic ) ) {
118
				$webhook->set_topic( $topic );
119
			}
120
		}
121
	}
122
123
	/**
124
	 * Save method.
125
	 */
126
	private function save() {
127 View Code Duplication
		if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
			wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
129
		}
130
131
		$webhook_id = absint( $_POST['webhook_id'] );
132
133
		if ( ! current_user_can( 'edit_shop_webhook', $webhook_id ) ) {
134
			return;
135
		}
136
137
		$webhook = new WC_Webhook( $webhook_id );
138
139
		// Name
140
		$this->update_name( $webhook->id );
141
142
		// Status
143
		$this->update_status( $webhook );
144
145
		// Delivery URL
146
		$this->update_delivery_url( $webhook );
147
148
		// Secret
149
		$this->update_secret( $webhook );
150
151
		// Topic
152
		$this->update_topic( $webhook );
153
154
		// Run actions
155
		do_action( 'woocommerce_webhook_options_save', $webhook->id );
156
157
		delete_transient( 'woocommerce_webhook_ids' );
158
159
		// Ping the webhook at the first time that is activated
160
		$pending_delivery = get_post_meta( $webhook->id, '_webhook_pending_delivery', true );
161
162
		if ( isset( $_POST['webhook_status'] ) && 'active' === $_POST['webhook_status'] && $pending_delivery ) {
163
			$result = $webhook->deliver_ping();
164
165
			if ( is_wp_error( $result ) ) {
166
				// Redirect to webhook edit page to avoid settings save actions
167
				wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&error=' . urlencode( $result->get_error_message() ) ) );
168
				exit();
169
			}
170
		}
171
172
		// Redirect to webhook edit page to avoid settings save actions
173
		wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&updated=1' ) );
174
		exit();
175
	}
176
177
	/**
178
	 * Create Webhook.
179
	 */
180
	private function create() {
181
		if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'create-webhook' ) ) {
182
			wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
183
		}
184
185
		if ( ! current_user_can( 'publish_shop_webhooks' ) ) {
186
			wp_die( __( 'You don\'t have permissions to create Webhooks!', 'woocommerce' ) );
187
		}
188
189
		$webhook_id = wp_insert_post( array(
190
			'post_type'     => 'shop_webhook',
191
			'post_status'   => 'pending',
192
			'ping_status'   => 'closed',
193
			'post_author'   => get_current_user_id(),
194
			'post_password' => strlen( ( $password = uniqid( 'webhook_' ) ) ) > 20 ? substr( $password, 0, 20 ) : $password,
195
			'post_title'    => sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ),
196
			'comment_status' => 'open'
197
		) );
198
199
		if ( is_wp_error( $webhook_id ) ) {
200
			wp_die( $webhook_id->get_error_messages() );
201
		}
202
203
		update_post_meta( $webhook_id, '_webhook_pending_delivery', true );
204
205
		delete_transient( 'woocommerce_webhook_ids' );
206
207
		// Redirect to edit page
208
		wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook_id . '&created=1' ) );
209
		exit();
210
	}
211
212
	/**
213
	 * Bulk trash/delete.
214
	 *
215
	 * @param array $webhooks
216
	 * @param bool  $delete
217
	 */
218
	private function bulk_trash( $webhooks, $delete = false ) {
219
		foreach ( $webhooks as $webhook_id ) {
220
			if ( $delete ) {
221
				wp_delete_post( $webhook_id, true );
222
			} else {
223
				wp_trash_post( $webhook_id );
224
			}
225
		}
226
227
		$type   = ! EMPTY_TRASH_DAYS || $delete ? 'deleted' : 'trashed';
228
		$qty    = count( $webhooks );
229
		$status = isset( $_GET['status'] ) ? '&status=' . sanitize_text_field( $_GET['status'] ) : '';
230
231
		delete_transient( 'woocommerce_webhook_ids' );
232
233
		// Redirect to webhooks page
234
		wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks' . $status . '&' . $type . '=' . $qty ) );
235
		exit();
236
	}
237
238
	/**
239
	 * Bulk untrash.
240
	 *
241
	 * @param array $webhooks
242
	 */
243
	private function bulk_untrash( $webhooks ) {
244
		foreach ( $webhooks as $webhook_id ) {
245
			wp_untrash_post( $webhook_id );
246
		}
247
248
		$qty = count( $webhooks );
249
250
		delete_transient( 'woocommerce_webhook_ids' );
251
252
		// Redirect to webhooks page
253
		wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&status=trash&untrashed=' . $qty ) );
254
		exit();
255
	}
256
257
	/**
258
	 * Bulk actions.
259
	 */
260
	private function bulk_actions() {
261 View Code Duplication
		if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
262
			wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
263
		}
264
265
		if ( ! current_user_can( 'edit_shop_webhooks' ) ) {
266
			wp_die( __( 'You don\'t have permissions to edit Webhooks!', 'woocommerce' ) );
267
		}
268
269
		$webhooks = array_map( 'absint', (array) $_GET['webhook'] );
270
271
		switch ( $_GET['action'] ) {
272
			case 'trash' :
273
				$this->bulk_trash( $webhooks );
274
				break;
275
			case 'untrash' :
276
				$this->bulk_untrash( $webhooks );
277
				break;
278
			case 'delete' :
279
				$this->bulk_trash( $webhooks, true );
280
				break;
281
			default :
282
				break;
283
		}
284
	}
285
286
	/**
287
	 * Empty Trash.
288
	 */
289
	private function empty_trash() {
290
		if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'empty_trash' ) ) {
291
			wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) );
292
		}
293
294
		if ( ! current_user_can( 'delete_shop_webhooks' ) ) {
295
			wp_die( __( 'You don\'t have permissions to delete Webhooks!', 'woocommerce' ) );
296
		}
297
298
		$webhooks = get_posts( array(
299
			'post_type'           => 'shop_webhook',
300
			'ignore_sticky_posts' => true,
301
			'nopaging'            => true,
302
			'post_status'         => 'trash',
303
			'fields'              => 'ids'
304
		) );
305
306
		foreach ( $webhooks as $webhook_id ) {
307
			wp_delete_post( $webhook_id, true );
308
		}
309
310
		$qty = count( $webhooks );
311
312
		// Redirect to webhooks page
313
		wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&deleted=' . $qty ) );
314
		exit();
315
	}
316
317
	/**
318
	 * Webhooks admin actions.
319
	 */
320
	public function actions() {
321
		if ( $this->is_webhook_settings_page() ) {
322
			// Save
323
			if ( isset( $_POST['save'] ) && isset( $_POST['webhook_id'] ) ) {
324
				$this->save();
325
			}
326
327
			// Create
328
			if ( isset( $_GET['create-webhook'] ) ) {
329
				$this->create();
330
			}
331
332
			// Bulk actions
333
			if ( isset( $_GET['action'] ) && isset( $_GET['webhook'] ) ) {
334
				$this->bulk_actions();
335
			}
336
337
			// Empty trash
338
			if ( isset( $_GET['empty_trash'] ) ) {
339
				$this->empty_trash();
340
			}
341
		}
342
	}
343
344
	/**
345
	 * Page output.
346
	 */
347
	public static function page_output() {
348
		// Hide the save button
349
		$GLOBALS['hide_save_button'] = true;
350
351 View Code Duplication
		if ( isset( $_GET['edit-webhook'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
			$webhook_id = absint( $_GET['edit-webhook'] );
353
			$webhook    = new WC_Webhook( $webhook_id );
354
355
			if ( 'trash' != $webhook->post_data->post_status ) {
356
				include( 'settings/views/html-webhooks-edit.php' );
357
				return;
358
			}
359
		}
360
361
		self::table_list_output();
362
	}
363
364
	/**
365
	 * Notices.
366
	 */
367
	public static function notices() {
368 View Code Duplication
		if ( isset( $_GET['trashed'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369
			$trashed = absint( $_GET['trashed'] );
370
371
			WC_Admin_Settings::add_message( sprintf( _n( '1 webhook moved to the Trash.', '%d webhooks moved to the Trash.', $trashed, 'woocommerce' ), $trashed ) );
372
		}
373
374 View Code Duplication
		if ( isset( $_GET['untrashed'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
375
			$untrashed = absint( $_GET['untrashed'] );
376
377
			WC_Admin_Settings::add_message( sprintf( _n( '1 webhook restored from the Trash.', '%d webhooks restored from the Trash.', $untrashed, 'woocommerce' ), $untrashed ) );
378
		}
379
380 View Code Duplication
		if ( isset( $_GET['deleted'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
381
			$deleted = absint( $_GET['deleted'] );
382
383
			WC_Admin_Settings::add_message( sprintf( _n( '1 webhook permanently deleted.', '%d webhooks permanently deleted.', $deleted, 'woocommerce' ), $deleted ) );
384
		}
385
386
		if ( isset( $_GET['updated'] ) ) {
387
			WC_Admin_Settings::add_message( __( 'Webhook updated successfully.', 'woocommerce' ) );
388
		}
389
390
		if ( isset( $_GET['created'] ) ) {
391
			WC_Admin_Settings::add_message( __( 'Webhook created successfully.', 'woocommerce' ) );
392
		}
393
394
		if ( isset( $_GET['error'] ) ) {
395
			WC_Admin_Settings::add_error( wc_clean( $_GET['error'] ) );
1 ignored issue
show
Bug introduced by
It seems like wc_clean($_GET['error']) targeting wc_clean() can also be of type array; however, WC_Admin_Settings::add_error() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
396
		}
397
	}
398
399
	/**
400
	 * Table list output.
401
	 */
402 View Code Duplication
	private static function table_list_output() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
403
		echo '<h3>' . __( 'Webhooks', 'woocommerce' ) . ' <a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&create-webhook=1' ), 'create-webhook' ) ) . '" class="add-new-h2">' . __( 'Add Webhook', 'woocommerce' ) . '</a></h3>';
404
405
		$webhooks_table_list = new WC_Admin_Webhooks_Table_List();
406
		$webhooks_table_list->prepare_items();
407
408
		echo '<input type="hidden" name="page" value="wc-settings" />';
409
		echo '<input type="hidden" name="tab" value="api" />';
410
		echo '<input type="hidden" name="section" value="webhooks" />';
411
412
		$webhooks_table_list->views();
413
		$webhooks_table_list->search_box( __( 'Search Webhooks', 'woocommerce' ), 'webhook' );
414
		$webhooks_table_list->display();
415
	}
416
417
	/**
418
	 * Logs output.
419
	 *
420
	 * @param WC_Webhook $webhook
421
	 */
422
	public static function logs_output( $webhook ) {
423
		$current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1;
424
		$args    = array(
425
			'post_id' => $webhook->id,
426
			'status'  => 'approve',
427
			'type'    => 'webhook_delivery',
428
			'number'  => 10
429
		);
430
431
		if ( 1 < $current ) {
432
			$args['offset'] = ( $current - 1 ) * 10;
433
		}
434
435
		remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 );
436
437
		$logs = get_comments( $args );
438
439
		add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 );
440
441
		if ( $logs ) {
442
			include_once( 'settings/views/html-webhook-logs.php' );
443
		} else {
444
			echo '<p>' . __( 'This Webhook has no log yet.', 'woocommerce' ) . '</p>';
445
		}
446
	}
447
448
	/**
449
	 * Get the webhook topic data.
450
	 *
451
	 * @return array
452
	 */
453
	public static function get_topic_data( $webhook ) {
454
		$topic    = $webhook->get_topic();
455
		$event    = '';
456
		$resource = '';
457
458
		if ( $topic ) {
459
			list( $resource, $event ) = explode( '.', $topic );
460
461
			if ( 'action' === $resource ) {
462
				$topic = 'action';
463
			} else if ( ! in_array( $resource, array( 'coupon', 'customer', 'order', 'product' ) ) ) {
464
				$topic = 'custom';
465
			}
466
		}
467
468
		return array(
469
			'topic'    => $topic,
470
			'event'    => $event,
471
			'resource' => $resource
472
		);
473
	}
474
475
	/**
476
	 * Get the logs navigation.
477
	 *
478
	 * @param  int $total
479
	 *
480
	 * @return string
481
	 */
482
	public static function get_logs_navigation( $total, $webhook ) {
483
		$pages   = ceil( $total / 10 );
484
		$current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1;
485
486
		$html = '<div class="webhook-logs-navigation">';
487
488
			$html .= '<p class="info" style="float: left;"><strong>';
489
			$html .= sprintf( '%s &ndash; Page %d of %d', _n( '1 item', sprintf( '%d items', $total ), $total, 'woocommerce' ), $current, $pages );
490
			$html .= '</strong></p>';
491
492
			if ( 1 < $pages ) {
493
				$html .= '<p class="tools" style="float: right;">';
494 View Code Duplication
					if ( 1 == $current ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
495
						$html .= '<button class="button-primary" disabled="disabled">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</button> ';
496
					} else {
497
						$html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current - 1 ) ) . '#webhook-logs">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</a> ';
498
					}
499
500 View Code Duplication
					if ( $pages == $current ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
501
						$html .= '<button class="button-primary" disabled="disabled">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</button>';
502
					} else {
503
						$html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current + 1 ) ) . '#webhook-logs">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</a>';
504
					}
505
				$html .= '</p>';
506
			}
507
508
		$html .= '<div class="clear"></div></div>';
509
510
		return $html;
511
	}
512
}
513
514
new WC_Admin_Webhooks();
515