-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathactionnetwork.php
1358 lines (1129 loc) · 58.3 KB
/
actionnetwork.php
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* @package ActionNetwork
* @version 1.0
*
* Plugin Name: Action Network
* Description: Provides Action Network (actionnetwork.org) action embed codes as shortcodes and a calendar and signup widget
* Author: Jonathan Kissam
* Text Domain: actionnetwork
* Domain Path: /languages
* Version: 1.0
* License: GPLv3
* Author URI: http://jonathankissam.com
*/
/**
* Includes
*/
if (!class_exists('ActionNetwork')) {
require_once( plugin_dir_path( __FILE__ ) . 'includes/actionnetwork.class.php' );
}
if (!class_exists('ActionNetwork_Sync')) {
require_once( plugin_dir_path( __FILE__ ) . 'includes/actionnetwork-sync.class.php' );
}
/**
* Set up options
*/
add_option( 'actionnetwork_api_key', null );
/**
* Installation, database setup
*/
global $actionnetwork_version;
$actionnetwork_version = '1.0';
global $actionnetwork_db_version;
$actionnetwork_db_version = '1.0.7';
function actionnetwork_install() {
global $wpdb;
global $actionnetwork_version;
global $actionnetwork_db_version;
global $actionnetwork_update_sync;
$installed_version = get_option( 'actionnetwork_version' );
$installed_db_version = get_option( 'actionnetwork_db_version' );
$notices = get_option('actionnetwork_deferred_admin_notices', array());
if ($installed_version != $actionnetwork_version) {
// test for particular updates here
// on first installation
if (!$installed_version) {
$notices[] = sprintf(
/* translators: %s is link to text "settings page" */
__('Thank for you installing the Action Network plugin. If you are an Action Network partner and have an API key, please visit the plugin %s and enter your API key.', 'actionnetwork'),
'<a href="admin.php?page=actionnetwork&actionnetwork_tab=settings">' . __('settings page','actionnetwork') . '</a>'
);
}
update_option( 'actionnetwork_version', $actionnetwork_version );
}
if ($installed_db_version != $actionnetwork_db_version) {
// test for particular updates
if ( $installed_db_version && ($actionnetwork_db_version == '1.0.7') ) {
$notices[] = __('Database updated to add description and location fields to actionnetwork table, and remove end_date', 'actionnetwork');
// force updating all actions in the database
update_option('actionnetwork_cache_timestamp', 0 );
}
// test for particular updates
if ( $installed_db_version && ($actionnetwork_db_version == '1.0.6') ) {
$notices[] = __('Database updated to add "end_date" field to actionnetwork table', 'actionnetwork');
}
if ( $installed_db_version && ($actionnetwork_db_version == '1.0.5') ) {
$notices[] = __('Database updated to add "hidden" field to actionnetwork table', 'actionnetwork');
}
if ( $installed_db_version && ($actionnetwork_db_version == '1.0.4') ) {
$notices[] = __('Database updated to add table actionnetwork_queue', 'actionnetwork');
}
$table_name = $wpdb->prefix . 'actionnetwork';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
wp_id mediumint(9) NOT NULL AUTO_INCREMENT,
an_id varchar(64) DEFAULT '' NOT NULL,
type varchar(24) DEFAULT '' NOT NULL,
name varchar(255) DEFAULT '' NOT NULL,
title varchar (255) DEFAULT '' NOT NULL,
created_date bigint DEFAULT NULL,
modified_date bigint DEFAULT NULL,
start_date bigint DEFAULT NULL,
browser_url varchar(255) DEFAULT '' NOT NULL,
embed_standard_default_styles text NOT NULL,
embed_standard_layout_only_styles text NOT NULL,
embed_standard_no_styles text NOT NULL,
embed_full_default_styles text NOT NULL,
embed_full_layout_only_styles text NOT NULL,
embed_full_no_styles text NOT NULL,
description text NOT NULL,
location text NOT NULL,
enabled tinyint(1) DEFAULT 0 NOT NULL,
hidden tinyint(1) DEFAULT 0 NOT NULL,
PRIMARY KEY (wp_id)
) $charset_collate;";
$table_name_queue = $wpdb->prefix . 'actionnetwork_queue';
$sql_queue = "CREATE TABLE $table_name_queue (
resource_id bigint(2) NOT NULL AUTO_INCREMENT,
resource text NOT NULL,
endpoint varchar(255) DEFAULT '' NOT NULL,
processed tinyint(1) DEFAULT 0 NOT NULL,
PRIMARY KEY (resource_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
dbDelta( $sql_queue );
update_option( 'actionnetwork_db_version', $actionnetwork_db_version );
}
if ( !wp_next_scheduled( 'actionnetwork_cron_daily' ) ) {
wp_schedule_event( time(), 'daily', 'actionnetwork_cron_daily' );
}
update_option('actionnetwork_deferred_admin_notices', $notices);
}
register_activation_hook( __FILE__, 'actionnetwork_install' );
function actionnetwork_update_version_check() {
global $actionnetwork_version;
global $actionnetwork_db_version;
$installed_version = get_option( 'actionnetwork_version' );
$installed_db_version = get_option( 'actionnetwork_db_version' );
if ( ($installed_version != $actionnetwork_version) || ($installed_db_version != $actionnetwork_db_version) ) {
actionnetwork_install();
}
}
add_action( 'plugins_loaded', 'actionnetwork_update_version_check' );
/**
* Uninstall
*/
function actionnetwork_uninstall() {
global $wpdb;
// remove options
$actionnetwork_options = array(
'actionnetwork_version',
'actionnetwork_db_version',
'actionnetwork_deferred_admin_notices',
'actionnetwork_api_key',
'actionnetwork_cache_timestamp',
'actionnetwork_queue_status',
'actionnetwork_cron_token',
);
foreach ($actionnetwork_options as $option) {
delete_option( $option );
}
// remove database tables
$table_name = $wpdb->prefix . 'actionnetwork';
$wpdb->query("DROP TABLE IF EXISTS $table_name");
$table_name = $wpdb->prefix . 'actionnetwork_queue';
$wpdb->query("DROP TABLE IF EXISTS $table_name");
}
register_uninstall_hook( __FILE__, 'actionnetwork_uninstall' );
/**
* Administrative notices
*/
function actionnetwork_admin_notices() {
if ($notices = get_option( 'actionnetwork_deferred_admin_notices' ) ) {
foreach ($notices as $notice) {
echo "<div class=\"updated notice is-dismissible\"><p>$notice</p></div>";
}
delete_option( 'actionnetwork_deferred_admin_notices' );
}
}
add_action( 'admin_notices', 'actionnetwork_admin_notices' );
/**
* Widgets
*/
if (!class_exists('ActionNetwork_Calendar_Widget')) {
require_once( plugin_dir_path( __FILE__ ) . 'includes/actionnetwork-widgets.class.php' );
}
add_action( 'widgets_init', function(){
register_widget( 'ActionNetwork_Calendar_Widget' );
register_widget( 'ActionNetwork_Signup_Widget' );
});
/**
* Shortcode for embeds
* Since the way Action Network's embed codes work
* does not support multiple embeds on a single page,
* only allow the first shortcode on a given page load
*/
global $actionnetwork_shortcode_count;
$actionnetwork_shortcode_count = 0;
function actionnetwork_shortcode( $atts ) {
global $wpdb;
global $actionnetwork_shortcode_count;
// only embed a single shortcode on any given page
if ($actionnetwork_shortcode_count) { return; }
$id = isset($atts['id']) ? (int) $atts['id'] : null;
$size = isset($atts['size']) ? $atts['size'] : 'standard';
$style = isset($atts['style']) ? $atts['style'] : 'layout_only';
if (!$id) { return; }
// validate size and style
if (!in_array($size, array('standard', 'full'))) { $size = 'standard'; }
if (!in_array($style, array('default', 'layout_only', 'no'))) { $style = 'layout_only'; }
$sql = "SELECT * FROM {$wpdb->prefix}actionnetwork WHERE wp_id=".$id;
$action = $wpdb->get_row( $sql, ARRAY_A );
$embed_style = 'embed_'.$size.'_'.$style.'_styles';
$output = _actionnetwork_get_embed_code( $action, $embed_style );
if ($output) {
$actionnetwork_shortcode_count++;
return $output;
}
}
add_shortcode( 'actionnetwork', 'actionnetwork_shortcode' );
/**
* Shortcode for calendar
*/
function actionnetwork_calendar_shortcode ( $atts, $content = null ) {
global $wpdb, $wp;
$n = isset($atts['n']) ? (int) $atts['n'] : 0;
// $page = isset($atts['page']) ? (int) $atts['page'] : 10;
$date_format = isset($atts['date_format']) ? sanitize_text_field($atts['date_format']) : 'F j, Y';
$link_format = isset($atts['link_format']) ? sanitize_text_field($atts['link_format']) : '{{ event.link }}';
$link_text = isset($atts['link_text']) ? $atts['link_text'] : '{{ event.date }}: {{ event.title }}';
$container_element = isset($atts['container_element']) ? sanitize_key($atts['container_element']) : 'ul';
$container_class = isset($atts['container_class']) ? sanitize_html_class($atts['container_class']) : 'actionnetwork-calendar';
$item_element = isset($atts['item_element']) ? sanitize_key($atts['item_element']) : 'li';
$item_class = isset($atts['item_class']) ? sanitize_html_class($atts['item_class']) : 'actionnetwork-calendar-item';
$no_events = isset($atts['no_events']) ? $atts['no_events'] : __( 'No upcoming events', 'actionnetwork' );
$location = (isset($atts['location']) && $atts['location']) ? '<div class="actionnetwork-calendar-location">{{ event.location }}</div>' : '';
$description = (isset($atts['description']) && $atts['description']) ? '<div class="actionnetwork-calendar-description">{{ event.description }}</div>' : '';
$embed_style = isset($atts['embed_style']) ? 'embed_'.sanitize_text_field($atts['embed_style']).'_styles' : 'embed_standard_layout_only_styles';
/*
$embed_fields = array(
'embed_standard_layout_only_styles',
'embed_full_layout_only_styles',
'embed_standard_no_styles',
'embed_full_no_styles',
'embed_standard_default_styles',
'embed_full_default_styles',
);
// validate embed_style
if (!in_array( $embed_style, $embed_fields )) { $embed_style = 'embed_standard_layout_only_styles'; }
*/
// check if we have an id that matches an existing event
$event_id = ( isset($wp->query_vars['page']) && (!isset($atts['ignore_url_id']) || !$atts['ignore_url_id']) ) ? (int) $wp->query_vars['page'] : 0;
if ($event_id) {
$sql = "SELECT * FROM {$wpdb->prefix}actionnetwork WHERE type IN ('event','ticketed_event') AND wp_id=$event_id";
$sql .= " AND enabled=1 AND hidden=0";
$sql .= " AND start_date > ".time();
$event = $wpdb->get_row( $sql, ARRAY_A );
if (count($event)) {
return _actionnetwork_get_embed_code( $event, $embed_style );
}
}
// template
if (trim($content)) {
$content = preg_replace('#</?p>|<br ?/?>#','',$content);
} else {
$content = <<<EOHTML
<$container_element class="$container_class">
{% for event in events %}
<$item_element class="$item_class">
<a href="$link_format">$link_text</a>
$location
$description
</$item_element>
{% else %}
<$item_element class="$item_class">$no_events</$item_element>
{% endfor %}
</$container_element>
EOHTML;
}
// parse template into $pre, $row, $else and $post
list ($pre,$content) = explode('{% for event in events %}', $content);
list ($row,$content) = explode('{% else %}', $content);
list ($no_events,$post) = explode('{% endfor %}', $content);
// load events
$sql = "SELECT * FROM {$wpdb->prefix}actionnetwork WHERE type IN ('event','ticketed_event')";
$sql .= " AND enabled=1 AND hidden=0";
$sql .= " AND start_date > ".time();
$sql .= " ORDER BY start_date ASC";
if ($n) { $sql .= " LIMIT 0,$n"; }
$events = $wpdb->get_results( $sql, ARRAY_A );
// if json="1" attribute is set, render as JSON object
if (isset($atts['json']) && $atts['json']) {
foreach($events as $index => $event) {
$event['date'] = isset($event['start_date']) ? date($date_format, $event['start_date']) : '(No Date)';
$event['link']= isset($event['browser_url']) ? $event['browser_url'] : site_url();
$event['id'] = isset($event['wp_id']) ? $event['wp_id'] : 0;
$location_json = isset($event['location']) ? unserialize( $event['location'] ) : new stdClass();
$event['location'] = isset($event['location'])? _actionnetwork_render_location( $event['location'] ) : '';
$event['link'] = $link_format ? _actionnetwork_calendar_render( $link_format, $event) : $event['link'];
$event['location_json'] = $location_json;
$events[$index] = $event;
}
$json = json_encode($events);
$output = '<script type="text/javascript">';
$output .= "\n";
$output .= 'actionNetworkEvents = '.$json;
$output .= ";\n";
$output .= '</script>';
return $output;
}
$output = $pre;
if (count($events)) {
foreach ($events as $event) {
$event_data['id'] = isset($event['wp_id']) ? $event['wp_id'] : 0;
$event_data['title'] = isset($event['title']) ? $event['title'] : '(Event Title)';
$event_data['date'] = isset($event['start_date']) ? date($date_format, $event['start_date']) : '(Date)';
$event_data['link'] = isset($event['browser_url']) ? $event['browser_url'] : site_url();
$event_data['link'] = $link_format ? _actionnetwork_calendar_render( $link_format, $event_data) : $event_data['link'];
$event_data['location'] = isset($event['location']) ? _actionnetwork_render_location($event['location']) : '';
$event_data['description'] = isset($event['description']) ? $event['description'] : '';
$output .= _actionnetwork_calendar_render( $row, $event_data );
}
} else {
$output .= $no_events;
}
$output .= $post;
// $output .= '<pre>' . print_r($wp,1) . '</pre>';
return $output;
}
add_shortcode( 'actionnetwork_calendar', 'actionnetwork_calendar_shortcode' );
/**
* Helper function for calendar shortcode
* Renders a very simplistic version of twig (http://twig.sensiolabs.org/)
*/
function _actionnetwork_calendar_render( $twig, $event ) {
$output = $twig;
foreach ($event as $k => $v) {
$output = str_replace('{{ event.'.$k.' }}', $v, $output);
}
return $output;
}
/**
* Helper function to render a location hash
*/
function _actionnetwork_render_location( $location_hash ) {
$location = unserialize( $location_hash );
if ( isset( $location->html ) && $location->html ) { return wpautop( $location->html ); }
$location_string = '';
$location_string .= ( isset( $location->venue ) && $location->venue ) ? $location->venue . "\n" : '';
$location_string .= ( isset( $location->address_lines ) && is_array( $location->address_lines ) && count ( $location->address_lines ) ) ? $location->address_lines[0] . "\n" : '';
$location_string .= ( isset( $location->locality ) && $location->locality ) ? $location->locality . ', ' : '';
$location_string .= isset( $location->region ) ? $location->region . ' ' : '';
$location_string .= isset( $location->postal_code ) ? $location->postal_code : '';
return wpautop( $location_string );
}
/**
* Helper function to get embed code by style
*/
function _actionnetwork_get_embed_code( $action, $embed_style = '', $autop = true ) {
$embed_fields = array(
'embed_standard_layout_only_styles',
'embed_full_layout_only_styles',
'embed_standard_no_styles',
'embed_full_no_styles',
'embed_standard_default_styles',
'embed_full_default_styles',
);
$output = null;
// validate embed_style
if (!in_array( $embed_style, $embed_fields )) { $embed_style = 'embed_standard_layout_only_styles'; }
if (isset($action[$embed_style]) && $action[$embed_style]) {
$output = $action[$embed_style];
} else {
foreach( $embed_fields as $embed_field_name) {
if ($action[$embed_field_name]) {
$output = $action[$embed_field_name];
}
}
}
if ((strpos($output, '<script') === FALSE) && $autop) {
$output = wpautop($output);
}
return $output;
}
/**
* Set up admin menu structure
* https://developer.wordpress.org/reference/functions/add_menu_page/
*/
function actionnetwork_admin_menu() {
$actionnetwork_admin_menu_hook = add_menu_page( __('Administer Action Network', 'actionnetwork'), 'Action Network', 'manage_options', 'actionnetwork', 'actionnetwork_admin_page', plugins_url('icon-action-network.png', __FILE__), 21);
add_action( 'load-' . $actionnetwork_admin_menu_hook, 'actionnetwork_admin_add_help' );
/*
// customize the first sub-menu link
$actionnetwork_admin_menu_hook = add_submenu_page( __('Administer Action Network'), __('Administer'), 'manage_options', 'actionnetwork-menu', 'actionnetwork_admin_page');
add_action( 'load-' . $actionnetwork_admin_menu_hook, 'actionnetwork_admin_add_help' );
*/
}
add_action( 'admin_menu', 'actionnetwork_admin_menu' );
/**
* Update sync daily via cron
*/
function actionnetwork_cron_sync() {
// initiate a background process by making a call to the "ajax" URL
$ajax_url = admin_url( 'admin-ajax.php' );
// since we're making this call from the server, we can't use a nonce
// because the user id could be different. so create a token
$timeint = time() / mt_rand( 1, 10 ) * mt_rand( 1, 10 );
$timestr = (string) $timeint;
$token = md5( $timestr );
update_option( 'actionnetwork_ajax_token', $token );
$body = array(
'action' => 'actionnetwork_process_queue',
'queue_action' => 'init',
'token' => $token,
);
$args = array( 'body' => $body, 'timeout' => 1 );
wp_remote_post( $ajax_url, $args );
}
add_action( 'actionnetwork_cron_daily', 'actionnetwork_cron_sync' );
/**
* Process ajax requests
*/
function actionnetwork_process_queue(){
// Don't lock up other requests while processing
session_write_close();
// check token
$token = isset($_REQUEST['token']) ? $_REQUEST['token'] : 'no token';
$stored_token = get_option( 'actionnetwork_ajax_token', '' );
if ($token != $stored_token) { wp_die(); }
delete_option( 'actionnetwork_ajax_token' );
$queue_action = isset($_REQUEST['queue_action']) ? $_REQUEST['queue_action'] : '';
$updated = isset($_REQUEST['updated']) ? $_REQUEST['updated'] : 0;
$inserted = isset($_REQUEST['inserted']) ? $_REQUEST['inserted'] : 0;
$new_only = isset($_REQUEST['new_only']) ? $_REQUEST['new_only'] : 0;
$status = get_option( 'actionnetwork_queue_status', 'empty' );
// error_log( "actionnetwork_process_queue called with the following _REQUEST args:\n\n" . print_r( $_REQUEST, 1) . "\n\nqueue_action: $queue_action\nstatus:$status\n\n", 0 );
// otherwise delete the ajax token
// only do something if status is empty & queue_action is init,
// or status is processing and queue_action is continue
if (
( ($queue_action == 'init') && ($status == 'empty') )
|| ( ($queue_action == 'continue') && ($status == 'processing') )
) {
$sync = new Actionnetwork_Sync();
$sync->updated = $updated;
$sync->inserted = $inserted;
$sync->new_only = $new_only;
if ($queue_action == 'init') { $sync->init(); }
$sync->processQueue();
// error_log("New Actionnetwork_Sync created; current state:\n\n" . print_r( $sync, 1), 0 );
}
wp_die();
}
add_action( 'wp_ajax_actionnetwork_process_queue', 'actionnetwork_process_queue' );
add_action( 'wp_ajax_nopriv_actionnetwork_process_queue', 'actionnetwork_process_queue' );
function actionnetwork_get_queue_status(){
check_ajax_referer( 'actionnetwork_get_queue_status', 'actionnetwork_ajax_nonce' );
$sync = new Actionnetwork_Sync();
$status = $sync->getQueueStatus();
$status['text'] = __('API Sync queue is '.$status['status'].'.', 'actionnetwork');
if ($status['status'] == 'processing') {
$status['text'] .= ' ' . __(
/* translators: first %d is number of items processed, second %d is total number of items in queue */
sprintf('%d of %d items processed.', $status['processed'], $status['total'])
);
}
// if status is "complete" or "empty," check if an admin notice has been set;
// if it has, return the admin notice as status.text & clear in options
if ( ($status['status'] == 'complete') || ($status['status'] == 'empty') ) {
$notices = get_option('actionnetwork_deferred_admin_notices', array());
if (isset($notices['api_sync_completed'])) {
$status['text'] = $notices['api_sync_completed'];
$status['status'] = 'complete';
// unset($notices['api_sync_completed']);
// update_option('actionnetwork_deferred_admin_notices', $notices);
}
}
wp_send_json($status);
wp_die();
}
add_action( 'wp_ajax_actionnetwork_get_queue_status', 'actionnetwork_get_queue_status' );
/**
* Helper function to handle administrative actions
*/
function _actionnetwork_admin_handle_actions(){
global $wpdb;
$return = array();
if ( !isset($_REQUEST['actionnetwork_admin_action']) || !check_admin_referer(
'actionnetwork_'.$_REQUEST['actionnetwork_admin_action'], 'actionnetwork_nonce_field'
) ) {
return false;
}
switch ($_REQUEST['actionnetwork_admin_action']) {
case 'update_api_key':
$debug = "update_api_key case matched\n";
$actionnetwork_api_key = sanitize_key($_REQUEST['actionnetwork_api_key']);
$debug .= "actionnetwork_api_key: $actionnetwork_api_key\n";
$queue_status = get_option( 'actionnetwork_queue_status', 'empty' );
$debug .= "queue_status: $queue_status\n";
// mail('[email protected]','debug report 1',$debug,"From: [email protected]\r\n");
if (get_option('actionnetwork_api_key', null) !== $actionnetwork_api_key) {
$debug .= "get_option did not match actionnetwork_api_key\n";
// don't allow API Key to be changed if a sync queue is processing
if ($queue_status != 'empty') {
$return['notices']['error'] = __( 'Cannot change API key while a sync queue is processing', 'actionnetwork' );
} else {
$debug .= "trying to change api key\n";
// mail('[email protected]','debug report 2',$debug,"From: [email protected]\r\n");
$actionnetwork_api_key_is_valid = false;
// empty API key is "valid"
if (!$actionnetwork_api_key) {
$actionnetwork_api_key_is_valid = true;
} else {
// validate API key
$ActionNetwork = new ActionNetwork($actionnetwork_api_key);
$validate = $ActionNetwork->call('petitions');
$debug .= "validation returned:\n\n" . print_r($validate,1) . "\n\n";
// mail('[email protected]','debug report 3',$debug,"From: [email protected]\r\n");
if (isset($validate->error)) {
if (substr($validate->error,0,30) == 'API Key invalid or not present') {
$return['notices']['error'][] = __( 'Invalid API key:', 'actionnetwork' ).' '.$actionnetwork_api_key;
} else {
$return['notices']['error'][] = __( 'Error validating API key:', 'actionnetwork' ).' '.$actionnetwork_api_key;
}
} else {
$actionnetwork_api_key_is_valid = true;
}
}
$debug .= $actionnetwork_api_key_is_valid ? "actionnetwork_api_key is valid\n" : "actionnetwork_api_key is not valid\n";
// mail('[email protected]','debug report 4',$debug,"From: [email protected]\r\n");
if ($actionnetwork_api_key_is_valid) {
update_option('actionnetwork_api_key', $actionnetwork_api_key);
update_option('actionnetwork_cache_timestamp', 0);
$deleted = $wpdb->query("DELETE FROM {$wpdb->prefix}actionnetwork WHERE an_id != ''");
if ($actionnetwork_api_key) {
// initiate a background process by making a call to the "ajax" URL
$ajax_url = admin_url( 'admin-ajax.php' );
// since we're making this call from the server, we can't use a nonce
// because the user id would be different. so create a token
$timeint = time() / mt_rand( 1, 10 ) * mt_rand( 1, 10 );
$timestr = (string) $timeint;
$token = md5( $timestr );
update_option( 'actionnetwork_ajax_token', $token );
$body = array(
'action' => 'actionnetwork_process_queue',
'queue_action' => 'init',
'token' => $token,
);
$args = array( 'body' => $body, 'timeout' => 1 );
wp_remote_post( $ajax_url, $args );
$queue_status = 'processing';
$return['queue_status'] = $queue_status;
$return['notices']['updated']['sync-started'] = $deleted ? __('API key has been updated, actions synced via previous API key have been removed, and sync with new API key has been started', 'actionnetwork') : __('API key has been updated and sync with new API key has been started', 'actionnetwork');
} else {
$return['notices']['updated'][] = $deleted ? __('API key and actions synced via API have been removed', 'actionnetwork') : __('API key has been removed', 'actionnetwork');
}
}
}
}
break;
case 'update_sync':
// error_log( 'actionnetwork_admin_action=update_sync called', 0 );
$queue_status = get_option( 'actionnetwork_queue_status', 'empty' );
if ($queue_status != 'empty') {
$return['notices']['error'][] = __( 'Sync currently in progress', 'actionnetwork' );
} else {
// initiate a background process by making a call to the "ajax" URL
$ajax_url = admin_url( 'admin-ajax.php' );
// since we're making this call from the server, we can't use a nonce
// because the user id would be different. so create a token
$timeint = time() / mt_rand( 1, 10 ) * mt_rand( 1, 10 );
$timestr = (string) $timeint;
$token = md5( $timestr );
update_option( 'actionnetwork_ajax_token', $token );
$body = array(
'action' => 'actionnetwork_process_queue',
'queue_action' => 'init',
'token' => $token,
);
$args = array( 'body' => $body, 'timeout' => 1 );
wp_remote_post( $ajax_url, $args );
// error_log( "wp_remote_post url called: $ajax_url, args:\n\n".print_r($args,1), 0 );
$return['notices']['updated']['sync-started'] = __( 'Sync started', 'actionnetwork' );
$queue_status = 'processing';
}
$return['queue_status'] = $queue_status;
break;
case 'edit_event':
$embed_wp_id = isset($_REQUEST['actionnetwork_event_wp_id']) ? (int) $_REQUEST['actionnetwork_event_wp_id'] : 0;
if ($embed_wp_id) {
$table_name = $wpdb->prefix . 'actionnetwork';
$sql = "SELECT * FROM $table_name WHERE wp_id=".$embed_wp_id;
$event = $wpdb->get_row( $sql, ARRAY_A );
// only edit if wp_id refers to an existing event or tickted_event which is not API-synced
if ( ($event == null) || $event['an_id'] ||
(!in_array($event['type'],array('event','ticketed_event')))) {
break;
}
// if we're posting, then get the title, date & code from $_POST
$update = false;
if (isset($_POST['postback']) && $_POST['postback']) {
$update = true;
$embed_title = isset($_REQUEST['actionnetwork_add_embed_title']) ? stripslashes($_REQUEST['actionnetwork_add_embed_title']) : '';
$embed_date_string = isset($_REQUEST['actionnetwork_add_embed_date']) ? stripslashes($_REQUEST['actionnetwork_add_embed_date']) : '';
$embed_date_time_hour = isset($_REQUEST['actionnetwork_add_embed_date_time_hour']) ? intval($_REQUEST['actionnetwork_add_embed_date_time_hour']) : 12;
$embed_date_time_minutes = isset($_REQUEST['actionnetwork_add_embed_date_time_minutes']) ? intval($_REQUEST['actionnetwork_add_embed_date_time_minutes']) : 0;
if ($embed_date_time_minutes < 10) { $embed_date_time_minutes = '0' . $embed_date_time_minutes; }
$embed_date_time_ampm = isset($_REQUEST['actionnetwork_add_embed_date_time_ampm']) ? _actionnetwork_validate_ampm($_REQUEST['actionnetwork_add_embed_date_time_ampm']) : 'am';
$embed_code = isset($_REQUEST['actionnetwork_add_embed_code']) ? stripslashes($_REQUEST['actionnetwork_add_embed_code']) : '';
$location = isset($_REQUEST['actionnetwork_add_location']) ? stripslashes($_REQUEST['actionnetwork_add_location']) : '';
// make sure title & embed_code are not empty, add error messages;
if (!$embed_title) {
$return['notices']['error'][] = __('You must give your action a title', 'actionnetwork');
$return['errors']['#actionnetwork_add_embed_title'] = true;
$update = false;
}
if (!$embed_code) {
$return['notices']['error'][] = __('You must enter an embed code or description', 'actionnetwork');
$return['errors']['#actionnetwork_add_embed_code'] = true;
$update = false;
}
} else {
$embed_title = esc_attr($event['title']);
$embed_date_string = date('Y-m-d', $event['start_date']);
$embed_date_time_hour = date('h', $event['start_date']);
$embed_date_time_minutes = date('i', $event['start_date']);
$embed_date_time_ampm = date('a', $event['start_date']);
$embed_code = _actionnetwork_get_embed_code( $event, '', false );
$location_object = unserialize( $event['location'] );
$location = isset( $location_object->html ) ? $location_object->html : '';
}
if ($update) {
$event['title'] = $embed_title;
$embed_date_string .= ' '.$embed_date_time_hour.':'.$embed_date_time_minutes.' '.$embed_date_time_ampm;
$event['start_date'] = strtotime($embed_date_string);
$event['modified_date'] = time();
// parse embed code
$embed_style_matched = preg_match_all("/<link href='https:\/\/actionnetwork\.org\/css\/style-embed(-whitelabel)?\.css' rel='stylesheet' type='text\/css' \/>/", $embed_code, $embed_style_matches, PREG_SET_ORDER);
$embed_script_matched = preg_match_all("|<script src='https://actionnetwork\.org/widgets/v2/([a-z_]+)/([-a-z0-9]+)\?format=js&source=widget(&style=full)?'>|", $embed_code, $embed_script_matches, PREG_SET_ORDER);
$embed_style = $embed_style_matched ? ( isset($embed_style_matches[0][1]) && $embed_style_matches[0][1] ? 'layout_only' : 'default' ) : 'no';
$embed_size = isset($embed_script_matches[0][3]) && $embed_script_matches[0][3] ? 'full' : 'standard';
$embed_field_name = 'embed_'.$embed_size.'_'.$embed_style.'_styles';
// clear out all possible embed codes, in case it has changed
$event['embed_standard_layout_only_styles'] = '';
$event['embed_full_layout_only_styles'] = '';
$event['embed_standard_no_styles'] = '';
$event['embed_full_no_styles'] = '';
$event['embed_standard_default_styles'] = '';
$event['embed_full_default_styles'] = '';
$event[$embed_field_name] = $embed_code;
// serialize location
$location_object = new stdClass();
$location_object->html = $location;
$event['location'] = serialize($location_object);
$wpdb->update($table_name, $event, array( 'wp_id' => $embed_wp_id ) );
$return['notices']['updated'][] = sprintf(
/* translators: %s is title of event */
__('%s has been updated', 'actionnetwork'), $embed_title
);
// $return['notices']['error'][] = '$embed_date_string: '.$embed_date_string.'<br /><br />$_REQUEST:<br /><br /><pre>'.print_r($_REQUEST,1).'</pre>';
// otherwise, build an edit form
} else {
$admin_url = admin_url('admin.php?page=actionnetwork');
$text_actions = __('Actions', 'actionnetwork');
$text_edit_event = __('Edit Event', 'actionnetwork');
$text_settings = __('Settings', 'actionnetwork');
$form_action = admin_url('admin.php?page=actionnetwork');
$nonce_field = wp_nonce_field( 'actionnetwork_edit_event', 'actionnetwork_nonce_field', true, false );
$text_title = __('Title', 'actionnetwork');
$text_required = __('This field is required', 'actionnetwork');
$error_title_required = isset($return['errors']['#actionnetwork_add_embed_title']) && $return['errors']['#actionnetwork_add_embed_title'] ? ' error' : '';
$text_date = __('Date (if event)', 'actionnetwork');
$input_time = _actionnetwork_build_time_input( $embed_date_time_hour, $embed_date_time_minutes, $embed_date_time_ampm );
$text_embed_code = __('Embed Code/Event Description', 'actionnetwork');
$error_embed_code_required = isset($return['errors']['#actionnetwork_add_embed_code']) && $return['errors']['#actionnetwork_add_embed_code'] ? ' error' : '';
$text_location = __('Event location', 'actionnetwork');
$text_location_description = __('If you are entering a description above (instead of an embed code), make sure the title, date and location (if relevant) are included in the description as well.');
$text_update_event = __('Update event', 'actionnetwork');
$return['edit_event_form'] = <<<EOHTML
<h2 class="nav-tab-wrapper">
<a href="$admin_url#actionnetwork-actions" class="nav-tab">
$text_actions
</a>
<span class="nav-tab nav-tab-active">
$text_edit_event
</span>
<a href="$admin_url#actionnetwork-settings" class="nav-tab">
$text_settings
</a>
</h2>
<h2>$text_edit_event</h2>
<form method="post" action="$form_action">
$nonce_field
<input type="hidden" name="actionnetwork_admin_action" value="edit_event" />
<input type="hidden" name="actionnetwork_event_wp_id" value="$embed_wp_id" />
<input type="hidden" name="postback" value="1" />
<table class="form-table"><tbody>
<tr valign="top">
<th scope="row"><label for="actionnetwork_add_embed_title">$text_title <span class="required" title="$text_required">*</span></label></th>
<td>
<input id="actionnetwork_add_embed_title" name="actionnetwork_add_embed_title" class="required$error_title_required" type="text" value="$embed_title" />
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="actionnetwork_add_embed_date">$text_date</label></th>
<td>
<input id="actionnetwork_add_embed_date" name="actionnetwork_add_embed_date" type="date" value="$embed_date_string" /> $input_time
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="actionnetwork_add_embed_code">$text_embed_code <span class="required" title="$text_required">*</span></label></th>
<td>
<textarea id="actionnetwork_add_embed_code" name="actionnetwork_add_embed_code" class="required$error_embed_code_required">$embed_code</textarea>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="actionnetwork_add_location">$text_location</label></th>
<td>
<textarea id="actionnetwork_add_location" name="actionnetwork_add_location">$location</textarea>
<p>$text_location_description</p>
</td>
</tr>
</tbody></table>
<p class="submit"><input type="submit" id="actionnetwork-add-embed-form-submit" class="button-primary" value="$text_update_event" /></p>
</form>
EOHTML;
}
// update
}
break;
case 'add_embed':
$embed_title = isset($_REQUEST['actionnetwork_add_embed_title']) ? stripslashes($_REQUEST['actionnetwork_add_embed_title']) : '';
$embed_date_string = isset($_REQUEST['actionnetwork_add_embed_date']) ? stripslashes($_REQUEST['actionnetwork_add_embed_date']) : '';
$embed_date_time_hour = isset($_REQUEST['actionnetwork_add_embed_date_time_hour']) ? intval($_REQUEST['actionnetwork_add_embed_date_time_hour']) : 12;
$embed_date_time_minutes = isset($_REQUEST['actionnetwork_add_embed_date_time_minutes']) ? intval($_REQUEST['actionnetwork_add_embed_date_time_minutes']) : 0;
if ($embed_date_time_minutes < 10) { $embed_date_time_minutes = '0' . $embed_date_time_minutes; }
$embed_date_time_ampm = isset($_REQUEST['actionnetwork_add_embed_date_time_ampm']) ? _actionnetwork_validate_ampm($_REQUEST['actionnetwork_add_embed_date_time_ampm']) : 'am';
$embed_code = isset($_REQUEST['actionnetwork_add_embed_code']) ? stripslashes($_REQUEST['actionnetwork_add_embed_code']) : '';
$location = isset($_REQUEST['actionnetwork_add_location']) ? stripslashes($_REQUEST['actionnetwork_add_location']) : '';
$embed_wp_id = isset($_REQUEST['actionnetwork_embed_wp_id']) ? (int) $_REQUEST['actionnetwork_embed_wp_id'] : 0;
$embed_valid = true;
// parse embed code
$embed_style_matched = preg_match_all("/<link href='https:\/\/actionnetwork\.org\/css\/style-embed(-whitelabel)?\.css' rel='stylesheet' type='text\/css' \/>/", $embed_code, $embed_style_matches, PREG_SET_ORDER);
$embed_script_matched = preg_match_all("|<script src='https://actionnetwork\.org/widgets/v2/([a-z_]+)/([-a-z0-9]+)\?format=js&source=widget(&style=full)?'>|", $embed_code, $embed_script_matches, PREG_SET_ORDER);
$embed_style = $embed_style_matched ? ( isset($embed_style_matches[0][1]) && $embed_style_matches[0][1] ? 'layout_only' : 'default' ) : 'no';
$embed_type = isset($embed_script_matches[0][1]) ? $embed_script_matches[0][1] : '';
if ($embed_type == 'letter') { $embed_type = 'advocacy_campaign'; }
if ($embed_type == 'fundraising') { $embed_type = 'fundraising_page'; }
$embed_size = isset($embed_script_matches[0][3]) && $embed_script_matches[0][3] ? 'full' : 'standard';
if (!$embed_title) {
if (isset($embed_script_matches[0][2]) && $embed_script_matches[0][2]) {
$embed_title = ucwords(str_replace('-',' ',$embed_script_matches[0][2]));
} else {
$return['notices']['error'][] = __('You must give your action a title', 'actionnetwork');
$return['errors']['#actionnetwork_add_embed_title'] = true;
$return['actionnetwork_add_embed_date'] = $embed_date_string;
$return['actionnetwork_add_embed_date_time_hour'] = $embed_date_time_hour;
$return['actionnetwork_add_embed_date_time_minutes'] = $embed_date_time_minutes;
$return['actionnetwork_add_embed_date_time_ampm'] = $embed_date_time_ampm;
$return['actionnetwork_add_embed_code'] = $embed_code;
$return['actionnetwork_add_location'] = $location;
$embed_valid = false;
}
}
if (!$embed_code) {
// TODO: validate the embed code instead of just checking for it being non-empty
$return['notices']['error'][] = __('You must enter an embed code or description', 'actionnetwork');
$return['errors']['#actionnetwork_add_embed_code'] = true;
$return['actionnetwork_add_embed_date'] = $embed_date_string;
$return['actionnetwork_add_embed_date_time_hour'] = $embed_date_time_hour;
$return['actionnetwork_add_embed_date_time_minutes'] = $embed_date_time_minutes;
$return['actionnetwork_add_embed_date_time_ampm'] = $embed_date_time_ampm;
$return['actionnetwork_add_embed_title'] = $embed_title;
$return['actionnetwork_add_location'] = $location;
$embed_valid = false;
}
// if there is an $embed_date, but no embed type, treat as an event
if ($embed_date_string && !$embed_type) {
$embed_type = 'event';
}
// if there's no valid embed type, then the embed code is not valid
if (!in_array( $embed_type, array(
'petition','advocacy_campaign','event','ticketed_event','fundraising_page','form'
))) {
$return['notices']['error'][] = __('This does not seem to be a valid Action Network embed code', 'actionnetwork');
$return['actionnetwork_add_embed_date'] = $embed_date_string;
$return['actionnetwork_add_embed_date_time_hour'] = $embed_date_time_hour;
$return['actionnetwork_add_embed_date_time_minutes'] = $embed_date_time_minutes;
$return['actionnetwork_add_embed_date_time_ampm'] = $embed_date_time_ampm;
$return['actionnetwork_add_embed_title'] = $embed_title;
$return['actionnetwork_add_embed_code'] = $embed_code;
$return['actionnetwork_add_location'] = $location;
$return['errors']['#actionnetwork_add_embed_code'] = true;
$embed_valid = false;
}
if ($embed_valid) {
// if the type is event or ticketed_event, give a warning if there is no start_date
if ( ($embed_type == 'event' || $embed_type == 'ticketed_event') && !$embed_date_string) {
$return['notices']['updated'][] = __('Notice: if you do not add a start date to your event, it will not display on the calendar widget', 'actionnetwork');
}
// if the type is *not* event or ticketed_event, and there is a date, give a warning that it won't be used
if ( ($embed_type != 'event') && ($event_type != 'ticketed_event') && $embed_date_string) {
$embed_date_string = '';
$return['notices']['updated'][] = __('Notice: the date entered in the "start date" field is not used for actions that are not events or ticketed events', 'actionnetwork');
}
// serialize location
$location_object = new stdClass();
$location_object->html = $location;
$location_serialized = serialize($location_object);
// save to action
$table_name = $wpdb->prefix . 'actionnetwork';
$embed_field_name = 'embed_'.$embed_size.'_'.$embed_style.'_styles';
$data = array(
'type' => $embed_type,
'title' => $embed_title,
$embed_field_name => $embed_code,
'location' => $location_serialized,
'enabled' => 1,
'created_date' => time(),
'modified_date' => time(),
);
if ($embed_date_string) {
$embed_date_string .= ' '.$embed_date_time_hour.':'.$embed_date_time_minutes.' '.$embed_date_time_ampm;
$data['start_date'] = strtotime($embed_date_string);
}
$wpdb->insert($table_name, $data, array ( '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d' ) );
$__copy = __('Copy', 'actionnetwork');
$shortcode_copy = <<<EOHTML
<span class="copy-wrapper">
<input type="text" class="copy-text" readonly="readonly" id="shortcode-new-{$wpdb->insert_id}" value="[actionnetwork id={$wpdb->insert_id}]" /><button data-copytarget="#shortcode-new-{$wpdb->insert_id}" class="copy">$__copy</button>
</span>
EOHTML;
$return['notices']['updated'][] = sprintf(
/* translators: %s: The shortcode for the saved embed code */
__('Action saved. Shortcode: %s', 'actionnetwork'),
$shortcode_copy