WC_Zapier_Trigger.php
20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* Represents a supported Zapier trigger.
*
* A trigger is an "event" that can be acted on in Zapier.
*
* Class WC_Zapier_Trigger
*/
abstract class WC_Zapier_Trigger {
/**
* Trigger name/key.
* Used internally, so should only contain alphanumeric characters and underscores.
*
* @var string
*/
protected $trigger_key = '';
/**
* User-friendly title that describes the trigger.
* Used in the WordPress dashboard.
*
* @var string
*/
protected $trigger_title = '';
/**
* User-friendly description that describes the trigger.
* Used in the WordPress dashboard.
*
* @var string
*/
protected $trigger_description = '';
/**
* List of WooCommerce hooks/actions that this trigger should fire on.
* @var array
*/
protected $actions = array();
/**
* Stores the list of Zapier feeds that apply to this trigger.
*
* @var WC_Zapier_Feed[] Array of WC_Zapier_Feed objects
*/
private $feeds;
/**
* Stores the raw data that is send to Zapier when this feed executes.
*
* @var array
*/
private $data;
/**
* Whether or not we are sending sample data or real live data.
*
* @var bool
*/
protected $is_sample = false;
/**
* The numeric sort order for this Trigger.
* Should be a unique integer greater than zero.
*
* This sort order is used when listing the Triggers on the Add/Edit Zapier Feed dashboard screen.
*
* @var int
*/
public $sort_order;
/**
* Whether or not data should be sent to Zapier asynchronously (using WP Cron)
* @var bool
*/
protected $send_asynchronously = true;
/**
* Constructor.
*
* Important: any child classes *must* call this constructor!
*
* @throws Exception
*/
public function __construct() {
if ( is_null( $this->sort_order ) )
throw new Exception( 'WC_Zapier_Trigger::sort_order must be specified' );
foreach ( $this->actions as $action_name => $action_num_args ) {
// When the specified action occurs, schedule it to be acted on during the next page load. Intercepted by the __call() function below.
add_action( $action_name, array( $this, $action_name ), 10, $action_num_args );
// The action name that is executed on the next page load. Intercepted by the __call() function below.
// The number of accepted arguments is increased by 1 to allow for the retrying of failed attempts to contact the Zapier Webhook URL.
add_action( "zapier_triggered_{$action_name}", array( $this, "zapier_triggered_{$action_name}" ), 10, $action_num_args + 1 );
}
}
/**
* Executed when WooCommerce executes one of the defined hooks/actions.
*
* Should gather the necessary data, in preparation for being sent to Zapier.
*
* Important: the WC_Zapier_Trigger->is_sample() method should be used to determine whether to use real or sample data.
*
* @param array $args The arguments to the hook/action.
* @param string $action_name The name of the WordPress action/hook
*
* @return array|false Array of data that is to be sent to Zapier, or false on failure
*/
public abstract function assemble_data( $args, $action_name );
/**
* Obtain the key/slug of this trigger.
*
* @return string
*/
public function get_trigger_key() {
return $this->trigger_key;
}
/**
* Obtain the title of this trigger.
*
* @return string
*/
public function get_trigger_title() {
return $this->trigger_title;
}
/**
* Obtain the description of this trigger.
* @return string
*/
public function get_trigger_description() {
return $this->trigger_description;
}
/**
* Obtain the Zapier Feeds that are configured for the specified trigger.
* The oldest feeds are first.
*
* Note: multiple calls to this function will simply return the cached result.
*
* @return WC_Zapier_Feed[] Array of WC_Zapier_Feed objects
*/
protected function get_feeds_for_this_trigger() {
if ( is_null( $this->feeds ) ) {
$this->feeds = WC_Zapier_Feed_Factory::get_feeds_for_trigger( $this );
}
return $this->feeds;
}
/**
* Clear the cached list of feeds that use this trigger.
*/
public function clear_feed_cache() {
$this->feeds = null;
}
/**
* Sends the assembled data to Zapier.
*
* If an error occurs, the request is retried using a truncated exponential backoff strategy: http://en.wikipedia.org/wiki/Exponential_backoff
*
* For sample data, there is no retry mechanism for failed requests.
*
* @param string $action_name Hook/action name (needed to be able to retry failed attempts)
* @param array $arguments Hook/action arguments (needed to be able to retry failed attempts)
*
* @return bool|string true on success, error message (string) on failure
*/
protected function send_to_zapier( $action_name, $arguments ) {
if ( is_null( $this->data ) || ! $this->data )
return;
$data = $this->data;
/**
* Override the WooCommerce data that is about to be sent to Zapier.
*
* Occurs just before the data is converted to JSON.
*
* Applies to all Zapier Triggers.
*
* Important: WC_Zapier_Trigger->is_sample() should be used to distinguish between sample and real data being sent to Zapier.
*
* @since 1.1.0
*
* @param array $data The WooCommerce data about to be sent to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that is causing the data to be sent to Zapier.
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
*/
$data = apply_filters( 'wc_zapier_data', $data, $this, $action_name, $arguments );
/**
* Override the WooCommerce data that is about to be sent to Zapier.
*
* Occurs just before the data is converted to JSON.
*
* The dynamic portion of the filter name, $this->trigger_key,
* refers to the unique key of the trigger being executed.
*
* This filter allows you to override data for a specific Zapier trigger.
*
* Important: WC_Zapier_Trigger->is_sample() should be used to distinguish between sample and real data being sent to Zapier.
*
* @since 1.1.0
*
* @param array $data The WooCommerce data about to be sent to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that is causing the data to be sent to Zapier.
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
*/
$data = apply_filters( "wc_zapier_data_{$this->trigger_key}", $data, $this, $action_name, $arguments );
$json_data = json_encode( $data );
/**
* Override the JSON data that is about to be sent to Zapier.
*
* Applies to all Zapier Triggers.
*
* Important: $this->is_sample() should be used to distinguish between sample and real data being sent to Zapier.
*
* @since 1.1.0
*
* @param string $json_data The JSON-encoded data about to be sent to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that is causing the data to be sent to Zapier.
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
*/
$json_data = apply_filters( 'wc_zapier_data_json', $json_data, $this, $action_name, $arguments );
/**
* Override the JSON data that is about to be sent to Zapier.
*
* The dynamic portion of the filter name, $this->trigger_key,
* refers to the unique key of the trigger being executed.
*
* This filter allows you to override data for a specific Zapier trigger.
*
* Important: $this->is_sample() should be used to distinguish between sample and real data being sent to Zapier.
*
* @since 1.1.0
*
* @param string $json_data The JSON-encoded data about to be sent to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that is causing the data to be sent to Zapier.
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
*/
$json_data = apply_filters( "wc_zapier_data_json_{$this->trigger_key}", $json_data, $this, $action_name, $arguments );
foreach ( $this->get_feeds_for_this_trigger() as $feed ) {
$args = array(
'sslverify' => false,
'ssl' => true,
'timeout' => 10, // Use a 10 second timeout instead of 5 seconds
'body' => $json_data
);
$webhook_url = $feed->webhook_url();
if ( $this->is_sample() ) {
// Testing the webhook - we're not sending real data
// Send X-Hook-Test header as per https://zapier.com/developer/reference/#static-webhooks and https://zapier.com/support/questions/1125/validating-urls/
// This will never trigger an action for real - Zapier will just cache the payload in their UI
$args['headers'] = array(
'X-Hook-Test' => 'true'
);
}
$num_attempts = 0;
if ( ! $this->is_sample() ) {
// For real data, keep track of the number of retries
if ( $this->actions[$action_name] == sizeof( $arguments ) ) {
// No num_retries parameter specified
$num_attempts = 0;
} else {
// We've retried at least once
$num_attempts = array_pop( $arguments );
}
$num_attempts++;
}
$sampletext = $this->is_sample() ? 'Sample ' : '';
WC_Zapier()->log( " Attempting to send {$sampletext}data to Zapier Feed:");
WC_Zapier()->log( " - Feed ID: " . $feed->id() );
WC_Zapier()->log( " - Feed Title: " . $feed->title() );
WC_Zapier()->log( " - Trigger: " . $this->get_trigger_title() );
WC_Zapier()->log( " - Webhook URL: $webhook_url" );
WC_Zapier()->log( "" );
WC_Zapier()->log( "{$sampletext}JSON Data: " . substr( $json_data, 0, 9 ) . " ..." ); // Logs the id but not much else
$result = wp_remote_post( $webhook_url, $args );
// Was there was an error communicating with the Zapier webhook?
if ( 200 != wp_remote_retrieve_response_code( $result ) ) {
$error_message = 'Unknown error';
if ( is_wp_error($result) ) {
$error_message = $result->get_error_messages();
$error_message = implode( ', ', $error_message );
} else {
// Non HTTP 200 response
$error_message = sprintf( __( 'HTTP %1$d (%2$s)' , 'wc_zapier' ), wp_remote_retrieve_response_code( $result ), esc_html( wp_remote_retrieve_response_message($result) ) );
}
WC_Zapier()->log( "Error: $error_message" );
if ( $this->is_sample() ) {
// When sending sample data, don't automatically retry
return $error_message;
}
$arguments['num_attempts'] = $num_attempts;
// Retry the request at a later date.
// Use a Truncated exponential backoff strategy: http://en.wikipedia.org/wiki/Exponential_backoff
// (with a maximum retry retry time of 1 hour)
$retry_seconds = min ( (int) pow( 2, $arguments['num_attempts'] ), 3600 );
WC_Zapier()->log( "Attempt #$num_attempts failed. Scheduling retry to occur in $retry_seconds second(s) from now." );
$this->schedule_event( $action_name, $arguments, $retry_seconds );
return $error_message;
}
// The request was a success
WC_Zapier()->log( "Success - HTTP 200 response code." );
if ( ! $this->is_sample() ) {
// Only do this for real data
$this->data_sent_to_feed( $feed, $result, $action_name, $arguments, $num_attempts );
}
/**
* After data is sent to Zapier successfully.
*
* Important: $this->is_sample() should be used to distinguish between sample and real data being sent to Zapier.
*
* @since 1.6.2
*
* @param string $json_data The JSON-encoded data that was sent to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that caused the data to be sent to Zapier.
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
*/
do_action( 'wc_zapier_data_sent_to_zapier_successfully', $json_data, $this, $action_name, $arguments );
}
return true;
}
/**
* Executed every time data is sent to a Zapier feed.
*
* Not executed when sample data is sent.
*
* @param WC_Zapier_Feed $feed Feed data
* @param array $result Response from the wp_remote_post() call
* @param string $action_name Hook/action name (needed to be able to retry failed attempts)
* @param array $arguments Hook/action arguments (needed to be able to retry failed attempts)
* @param int $num_attempts The number of attempts it took to successfully send the data to Zapier.
*/
protected function data_sent_to_feed( WC_Zapier_Feed $feed, $result, $action_name, $arguments, $num_attempts = 0 ) {
}
/**
* Executed whenever one of the trigger's supported hooks/actions is called.
*
* Called initially when a supported hook/filter is called, in which case we
* schedule the data to be sent to Zapier on the next page load.
*
* Called again on the next page load (when WordPress cron is executing), in which case
* the data is assembled and send to Zapier.
*
* @param string $action_name hook/action name
* @param array $arguments hook/action arguments
*
* @throws Exception
*/
public function __call( $action_name, array $arguments ) {
$pos = $this->send_asynchronously() ? strpos( $action_name, 'zapier_triggered_' ) : 0;
WC_Zapier()->log( "WC_Zapier_Trigger::__call() : $this->trigger_title" );
WC_Zapier()->log( " action_name: $action_name " );
WC_Zapier()->log( " arguments: " . print_r( $arguments, true ) );
if ( false === $pos ) {
// One of the specified actions has just been triggered
// Make sure it is an action/hook that we support and expect
if ( ! array_key_exists( $action_name, $this->actions ) )
return;
// Make sure there is at least one active feed configured for this trigger, otherwise there is no point continuing.
$feeds = $this->get_feeds_for_this_trigger();
WC_Zapier()->log( sizeof( $feeds ) . " active feed(s) found for trigger '$this->trigger_title'." );
if ( empty($feeds) ) {
WC_Zapier()->log( "No feeds. Aborting.\n\n" );
return;
}
if ( ! $this->should_schedule_event( $action_name, $arguments ) ) {
WC_Zapier()->log( "should_schedule_event() returned false when sending asynchronously. Aborting.\n\n" );
return false;
}
// Rather than acting on this immediately, schedule an event to run on the next page load.
// This also makes the Zapier API calls (somewhat) asynchronous, and allows us to retry if it fails.
$this->schedule_event( $action_name, $arguments );
WC_Zapier()->log( "Scheduled the asynchronous event to occur via wp-cron: " );
WC_Zapier()->log( " action_name: $action_name" );
WC_Zapier()->log( " arguments: " . print_r( $arguments, true ) );
} else if ( 0 === $pos ) {
if ( defined( 'DOING_CRON' ) ) {
WC_Zapier()->log( "This is a cron request" );
} else {
WC_Zapier()->log( "This isn't a cron request" );
if ( ! $this->send_asynchronously() ) {
// Sending synchronously (immediately)
if ( !$this->should_schedule_event( $action_name, $arguments ) ) {
WC_Zapier()->log( "should_schedule_event() returned false when sending synchronously. Aborting.\n\n" );
return false;
}
}
}
WC_Zapier()->log( " url = $_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" );
$action_name_to_trigger = str_replace( 'zapier_triggered_', '', $action_name );
WC_Zapier()->log( " action_name_to_trigger: $action_name_to_trigger" );
WC_Zapier()->log( " arguments: " . print_r( $arguments, true ) );
WC_Zapier()->log( "Assembling data..." );
$this->data = $this->assemble_data( $arguments, $action_name_to_trigger );
// Only send the data to Zapier if the assembled data wasn't false.
if ( false !== $this->data ) {
WC_Zapier()->log( "Sending to Zapier:" );
WC_Zapier()->log( " action_name: $action_name" );
WC_Zapier()->log( " arguments: " . print_r( $arguments, true ) );
$this->send_to_zapier( $action_name_to_trigger, $arguments );
} else {
WC_Zapier()->log( "Assembled data was false. Aborting.\n\n" );
}
} else {
//
WC_Zapier()->log( "Action_name doesn't seem to be supported. action_name = $action_name" );
// Silently ignore this request
}
}
/**
* Send some sample data to the specified Zapier Feed.
*
* This is done so that Zapier knows what data field to expect.
*
* @param WC_Zapier_Feed $feed
* @return bool|string true on success, or an error message (string) on failure.
*/
public function send_sample_data_payload( WC_Zapier_Feed $feed ) {
$this->is_sample = true;
$this->feeds = array( $feed );
$this->data = $this->assemble_data( array(), 'test' );
$result = $this->send_to_zapier( 'test', array() );
$this->is_sample = false;
$this->feeds = null;
return $result;
}
/**
* Schedules a single event to be executed on the next page load via WordPress' cron system.
*
* @param string $action_name
* @param array $arguments
* @param int $number_of_seconds_from_now
*
* @return bool
*/
protected function schedule_event( $action_name, $arguments, $number_of_seconds_from_now = 10 ) {
$result = wp_schedule_single_event( time() + $number_of_seconds_from_now, "zapier_triggered_{$action_name}", $arguments );
/**
* After data is scheduled to be sent to Zapier (asynchronously via WP-cron).
*
* @since 1.6.3
*
* @param string $action_name Hook/action name that initiated this data send to Zapier.
* @param array $arguments Arguments for the hook/action that initiated this data send to Zapier.
* @param WC_Zapier_Trigger $this The Trigger instance that caused the data to be sent to Zapier.
*/
do_action( 'wc_zapier_scheduled_event', $action_name, $arguments, $this );
return $result;
}
/**
* Whether or not we are sending sample data to Zapier.
*
* @return bool true if sending sample data, false if sending real live data.
*/
public function is_sample() {
return $this->is_sample;
}
/**
* Given a stdClass object, empty out the values for all properties.
*
* @param stdClass $object
*
* @return stdClass
*/
protected function create_empty_object_recursive( stdClass $object ) {
foreach ( $object as $key => $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $array_key => $array_item ) {
$object->{$key}[$array_key] = $this->create_empty_object_recursive( $array_item );
}
} else if ( is_string( $value ) ) {
$object->{$key} = '';
} else if ( is_integer( $value ) ) {
$object->{$key} = '';
} else if ( is_bool( $value ) ) {
$object->{$key} = '';
}
}
return $object;
}
/**
* Send sample data to all active feeds that use this trigger event.
*/
public function send_sample_data_to_active_feeds_using_this_trigger() {
foreach ( WC_Zapier_Feed_Factory::get_feeds_for_trigger( $this ) as $feed ) {
$feed->trigger()->send_sample_data_payload( $feed );
}
}
/**
* Whether or not the trigger event should send data to Zapier.
*
* Defaults to true, but allows specific triggers (sub-classes) to optionally prevent the data send from being scheduled.
*
* A trigger can override this function when/if required.
*
* @param string $action_name hook/action name
* @param array $args hook/action arguments
*
* @return bool True if the event should be scheduled, false if not
*/
protected function should_schedule_event( $action_name, $args ) {
return true;
}
/**
* Whether or not to send data to Zapier asynchronously (using WP-Cron).
*
* @return bool
*/
public function send_asynchronously() {
/**
* Override whether or not to send data to Zapier asynchronously (using WP-Cron).
*
* @since 1.6.0
*
* @param bool $send_asynchronously true to send via WP-cron, false to send immediately.
* @param WC_Zapier_Trigger $this The Trigger instance that is causing the data to be sent to Zapier.
*/
return apply_filters( 'wc_zapier_send_asynchronously', $this->send_asynchronously, $this );
}
}