This repository has been archived by the owner on May 12, 2020. It is now read-only.
forked from longouyang/make-child-theme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
1490 lines (1249 loc) · 47.7 KB
/
functions.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 Make Child
*/
/**
* The theme version.
*/
define('TTFMAKE_CHILD_VERSION', '1.1.0');
/**
* Turn off the parent theme styles.
*
* If you would like to use this child theme to style Make from scratch, rather
* than simply overriding specific style rules, simply remove the '//' from the
* 'add_filter' line below. This will tell the theme not to enqueue the parent
* stylesheet along with the child one.
*/
//add_filter( 'make_enqueue_parent_stylesheet', '__return_false' );
/**
* Add your custom theme functions here.
*/
/* redirect users to blog page after login */
function redirect_to_front_page()
{
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
//$redirect_to = get_option('siteurl');
$redirect_to = '/blog';
}
}
add_action('login_form', 'redirect_to_front_page');
add_action('wp_logout', 'auto_redirect_after_logout');
function auto_redirect_after_logout()
{
wp_redirect(home_url());
exit();
}
add_action('woocommerce_before_my_account', 'show_signed_forms');
function show_signed_forms()
{
echo signed_forms_html();
}
$membership_forms = array('amt-membership' => array('membership_agreement_date','liability_waiver_date','emergency_contact_date'),
'monster-corps-membership' => array('membership_agreement_date','liability_waiver_date','emergency_contact_date'),
'bot-bot-program-membership' => array('liability_waiver_date'),
'ops-membership' => array('membership_agreement_date','liability_waiver_date','emergency_contact_date')
);
// other membership types: ops-membership
// this function doesn't emit anything; instead it returns a string of html
// that's because this is used as a *filter* (not a hook) for woocommerce_memberships_thank_you_message
function signed_forms_html()
{
$user_id = get_current_user_id();
$umeta = get_user_meta($user_id);
$user_memberships = array();
$pretty_plan_names = array();
$html = "";
foreach (wc_memberships_get_membership_plans() as $plan) {
$slug = $plan->slug;
$name = $plan->name;
$pretty_plan_names[$slug] = $name;
if (wc_memberships_is_user_active_member($user_id, $slug)) {
array_push($user_memberships, $slug);
}
}
global $membership_forms;
$first_name = $umeta['first_name'][0];
$last_name = $umeta['last_name'][0];
$full_name = $first_name . " " . $last_name;
$packet_url_data = array('amt-membership' => array('PowerFormId' => '7fa50c17-c7e1-4578-aefd-ac5261e64b33',
'Member – Regular_UserName' => $full_name,
'EnvelopeField_user_id' => $user_id,
'EnvelopeField_packet_name' => 'amt-membership',
'EnvelopeField_server_hostname' => $_SERVER['HTTP_HOST']),
'bot-bot-program-membership' => array('PowerFormId' => '5e80fcde-bdb3-452e-a464-3286cb485530',
'Day Member_UserName' => $full_name,
'EnvelopeField_user_id' => $user_id,
'EnvelopeField_packet_name' => 'bot-bot-program-membership',
'EnvelopeField_server_hostname' => $_SERVER['HTTP_HOST']),
'monster-corps-membership' => array('PowerFormId' => '7fa50c17-c7e1-4578-aefd-ac5261e64b33',
'Member – Regular_UserName' => $full_name,
'EnvelopeField_user_id' => $user_id,
'EnvelopeField_packet_name' => 'monster-corps-membership',
'EnvelopeField_server_hostname' => $_SERVER['HTTP_HOST']),
'ops-membership' => array('PowerFormId' => '7fa50c17-c7e1-4578-aefd-ac5261e64b33',
'Member – Regular_UserName' => $full_name,
'EnvelopeField_user_id' => $user_id,
'EnvelopeField_packet_name' => 'ops-membership',
'EnvelopeField_server_hostname' => $_SERVER['HTTP_HOST'])
);
function make_packet_url($data)
{
$docusign_prefix = 'https://na3.docusign.net/Member/PowerFormSigning.aspx?';
$url = $docusign_prefix . http_build_query($data);
return $url;
}
$html .= ('<div class="signed-forms">');
$html .= ('<h2>Signed forms</h2>');
if ( is_user_logged_in() ) {
$picture = get_user_meta( get_current_user_id(), 'amt_directory_picture', true );
if ( ! $picture ) {
?>
<div class="notice">
You don't have a profile picture.
Please <a href="<?php echo site_url(); ?>/wp-admin/profile.php">set your profile picture</a>
</div>
<?php
}
}
$all_packets_signed = true;
$pretty_field_names = array('membership_agreement_date' => 'Membership Agreement',
'liability_waiver_date' => 'Liability Waiver',
'emergency_contact_date' => 'Emergency Contact'
);
//$html .= "<pre>" . $user_memberships . "</pre>";
$table_str = '<table><tr><th>Forms for</th><th>Date signed</th></tr>';
foreach ($user_memberships as $plan_name) {
$field_names = $membership_forms[$plan_name];
$packet_url = make_packet_url($packet_url_data[$plan_name]);
$dates_signed = array();
$this_packet_signed = true;
foreach ($field_names as $field_name) {
$form_date = get_user_meta($user_id, $field_name, true);
if ($form_date) {
$dates_signed[$field_name] = $form_date;
} else {
$dates_signed[$field_name] = null;
$this_packet_signed = false;
$all_packets_signed = false;
}
}
$date_display = "";
$smiley_emoji = ":D";
$sad_emoji = ":(";
foreach ($dates_signed as $field_name => $date) {
$pretty_field_name = $pretty_field_names[$field_name];
if (is_null($date)) {
$date_display .= $sad_emoji . ' ' . $pretty_field_name . ": not signed<br />";
} else {
$date_display .= $smiley_emoji . ' ' . $pretty_field_name . ": " . $date . "<br />";
}
}
if (!$this_packet_signed) {
$date_display .= "<a target='_blank' href='" . $packet_url . "'>Sign forms here</a>";
}
$table_str .= '<tr><td>' . $pretty_plan_names[$plan_name] . '</td><td>' . $date_display . '</td></tr>';
}
$table_str .= '</table>';
if (!$all_packets_signed) {
$html .= "<span style='font-weight: bold'>To keep your membership active, you must sign the liability/information forms below</span>";
}
$html .= $table_str;
$html .= '</div>';
if (!$all_packets_signed) {
$html = "<div style='border: 20px solid indianred; padding: 0.5em; background-color: indianred; color: white'>" . $html . "</div>";
}
return $html;
}
add_action('woocommerce_before_my_account', 'my_laser_usage');
function my_laser_usage()
{
print("<hr><h2>Laser Cutter Usage</h2>\n");
$userid = get_current_user_id();
$auth = md5($userid."3e532d5d228f9594c55d72978e3d3663ef32ed64dad4d078236ebd24c6a1a2d4fb872d4ef9a84eca78ffeb449afd98a6b4080cecb4124a9cb0dbd3188bf80415");
$data = json_decode(file_get_contents("https://ssl.acemonstertoys.org/member/mylaserfees.php?userid=$userid&auth=$auth"), true);
if (!isset($data['ok'])) {
print("Error loading laser cutter usage, sorry!<br>");
return;
}
if (!isset($data['rows']) || count($data['rows']) == 0) {
print("No laser cutter usage found under this account. Updates hourly.<br>");
return;
}
print("<table border=1>");
print("<thead>");
print("<tr>");
print("<th>date</th>");
print("<th>usage minutes</th>");
print("<th>fee</th>");
print("<th>billed</th>");
print("<th>note</th>");
print("</tr>");
print("</thead>");
foreach ($data['rows'] as $row) {
print("<tr>");
print("<td>");
print(implode("</td><td>", $row));
print("</td>");
print("</tr>");
}
print("</table>");
}
// after completing purchase of a new membership, show signed forms status
function filter_prepend_signed_forms($content)
{
if (strpos($content, 'purchasing a membership') !== false) {
return $content . signed_forms_html();
} else {
return $content;
}
}
add_filter('woocommerce_memberships_thank_you_message', 'filter_prepend_signed_forms');
// return true if a given RFID is a member
function is_member($rfid, $opts = array())
{
$args = array( 'meta_key' => 'member_rfid', 'meta_value' => $rfid );
$user_query = new WP_User_Query(array_merge($args, $opts));
return !empty($user_query->results);
}
//////////////// API ///////////////////////
// Find user ID associated with rfid
function find_member_ids_from_rfid($rfid)
{ #API2
$args = array( 'meta_key' => 'member_rfid', 'meta_value' => $rfid );
$user_query = new WP_User_Query($args);
$ids = array();
//
//$test_query = new WP_User_Query( array( 'number' => 200) );
//echo var_export($test_query->results, true);
//
//echo var_export(get_field('member_rfid', 'user_149'), true);
//echo var_export($user_query->results,true);
foreach ($user_query->results as $user) {
array_push($ids, $user->ID);
}
return $ids;
}
// Get all memberships as slugs
function membership_plan_slugs()
{ #API3
$plan_slugs = array();
foreach (wc_memberships_get_membership_plans() as $plan) {
if ($plan->slug == "bot-bot-program-membership") {
continue;
} // ignore box bot plan
array_push($plan_slugs, $plan->slug);
}
return $plan_slugs;
}
// Check if a given user ID is active or not
function is_member_active($user_id, $slugs=null)
{ #API2
$active = false;
if(!$slugs)
$slugs = membership_plan_slugs();
foreach ($slugs as $slug) {
if (wc_memberships_is_user_active_member($user_id, $slug)) {
$active = true;
}
}
return $active;
}
// Check if a given RFID is good or not
function rfid_status($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
$success = false;
$rfid = $request->get_params('id');
//still handle one rfid assigned to multiple users
$user_ids = find_member_ids_from_rfid($rfid);
foreach ($user_ids as $user_id) {
if (is_member_active($user_id)) {
$success = true;
}
}
return $success;
};
function rfid_status_int($rfid)
{ #API
$success = false;
//still handle one rfid assigned to multiple users
$user_ids = find_member_ids_from_rfid($rfid);
foreach ($user_ids as $user_id) {
if (is_member_active($user_id)) {
$success = true;
}
}
return $success;
};
// Get the RFID for a specific user given their UserID
function rfid_for_user($user_id)
{ #API2
// $args = array( 'meta_key' => 'member_rfid', 'user_id' => $user_id );
// $user_query = new WP_User_Query( $args );
// $rfid = $user_query->results;
$rfid = get_user_meta($user_id, 'member_rfid', true);
return $rfid;
}
function checkcerts($request)
{
if (!validate_request($request)) {
return invalid_request_response();
}
$requestobj = get_user_for_rfid($request);
$returnData->active = rfid_status_int($request[id]);
if (strstr($requestobj, 'Could not find')) {
$returnData->name = 'not_found';
$returnData->certs = 'not_found';
// $returnData->to_vend = 'not_found';
} else {
$returnData->name = get_user_by('id', $requestobj['ID'])->first_name." ".get_user_by('id', $requestobj['ID'])->last_name;
$returnData->certs = get_field('has_taken_laser_class', 'user_'.$requestobj['ID']);
$newQuery = wc_get_orders(array(
'customer' => $requestobj['ID'],
'status' => 'to-vend'
));
// $orders = array();
// if ($newQuery) {
// foreach ($newQuery as $key => $value) {
// array_push($orders, $value->id);
// }
// $returnData->to_vend = $orders;
// } else {
// $returnData->to_vend = 'no-vend-order';
// }
}
return $returnData;
}
function get_vendable_orders($request)
{
if (!validate_request($request)) {
return invalid_request_response();
}
$requestobj = get_user_for_rfid($request);
if (strstr($requestobj, 'Could not find')) {
$returnData->name = 'not_found';
$returnData->to_vend = 'no-orders';
$returnData->disbursed = 'no-orders';
} else {
$returnData->name = get_user_by('id', $requestobj['ID'])->first_name." ".get_user_by('id', $requestobj['ID'])->last_name;
$vendQuery = wc_get_orders(array(
'customer' => $requestobj['ID'],
'status' => 'to-vend'
));
$vendOrders = array();
if ($vendQuery) {
foreach ($vendQuery as $key => $value) {
array_push($vendOrders, $value->id);
}
$returnData->to_vend = $vendOrders;
} else {
$returnData->to_vend = 'no-orders';
}
$disbursedQuery = wc_get_orders(array(
'customer' => $requestobj['ID'],
'status' => 'disbursed'
));
$disbOrders = array();
if ($disbursedQuery) {
foreach ($disbursedQuery as $key => $value) {
array_push($disbOrders, $value->id);
}
$returnData->disbursed = $disbOrders;
} else {
$returnData->disbursed = 'no-orders';
}
}
return $returnData;
}
function view_vend_order($request)
{
if (!validate_request($request)) {
return invalid_request_response();
}
$order = wc_get_order($request[order_id]);
if ( $order==false ) {
$returnData->items = 'could_not_find_order';
$returnData->status = 'could_not_find_order';
return $returnData;
} elseif ($order->get_status()) {
$returnData->items = array();
foreach ($order->get_items() as $item_id => $item_data) {
array_push($returnData->items, $item_data['name']);
}
$returnData->status = $order->get_status();
return $returnData;
}
}
function disburse_vendable_order($request)
{
if (!validate_request($request)) {
return invalid_request_response();
}
$order = wc_get_order($request[order_id]);
if ( $order==false ) {
$returnData->status = 'could_not_find_order';
return $returnData;
} elseif ($order->get_status()=='to-vend') {
$returnData->items = array();
foreach ($order->get_items() as $item_id => $item_data) {
$next_item = array();
array_push($next_item, $item_data['name']);
$product = wc_get_product($item_data['product_id']);
array_push($next_item, $product->get_attribute('vend_bay'));
array_push($returnData->items, $next_item);
$order->update_status('disbursed');
$returnData->status = 'marking_as_disbursed';
}
return $returnData;
} elseif ($order->get_status()=='disbursed') {
$returnData->status = 'already_disbursed';
return $returnData;
} else {
$returnData->status = 'could_not_find_order';
return $returnData;
}
}
function get_product_info($request)
{
if (!validate_request($request)) {
return invalid_request_response();
}
//
// Built current list of vending items
//
$vend_items = array();
$the_query = new WP_Query(array( 'product_cat' => 'vend-item' ));
while ($the_query->have_posts()) {
$the_query->the_post();
$product = wc_get_product(get_the_ID());
$vend_bay = $product->get_attribute('vend_bay');
if($vend_bay == $request['vend_bay']) {
$returnData->vend_bay = $vend_bay;
$returnData->title = $product->get_title();
$returnData->image_url = $product->get_image();
$returnData->desc = $product->get_description();
return $returnData;
}
}
return "Couldn't find that bay";
}
function get_expiration_schedule()
{
$time = time();
echo $time . "\n";
//$next_scheduled = wp_next_scheduled( 'amt_expire_user_role' );
//if (! $next_scheduled || $next_scheduled < $time) {
// wp_schedule_event($time, 'hourly', 'amt_expire_user_role');
//}
return wp_next_scheduled('amt_expire_user_role');
//return expire_user_role();
}
// Loop over all users, find someone whose membership has expired,
// then if they are 'author' or 'customer', set their role to 'subscriber' instead
function expire_user_role()
{
if (! wp_next_scheduled('amt_expire_user_role')) {
wp_schedule_event(time(), 'hourly', 'amt_expire_user_role');
}
// Get the list of valid membership plans
$plan_slugs = membership_plan_slugs();
$out = array();
@file_get_contents("http://acemonstertoys.org/tmp-logger/logger.php?called=1");
foreach (get_users() as $user) {
$activePlan = false;
// loop over all the plans, see if the member has one
foreach ($plan_slugs as $slug) {
if (wc_memberships_is_user_active_member($user->ID, $slug)) {
$activePlan = true;
$sslug = $slug;
break;
}
}
$activeRole = false;
$adminRole = false;
$rrole = $user->roles[0];
$arole = "--";
// loop over all the user's roles, look for a role that is not author or customer
foreach ($user->roles as $role) {
if ($role == 'author' || $role == 'editor') {
$activeRole = true;
$rrole = $role;
}
if ($role == 'shop_manager' || $role == 'administrator') {
$adminRole = true;
$arole = $role;
}
}
// Big logic tree of all possible combinations of active/inactive/etc
if ($activePlan) {
if ($adminRole) { // active membership & is admin -> skip
$out[] = array('id'=>$user->user_email, 'r'=>"active $sslug admin $arole");
continue;
}
if (!$activeRole) { // active membership, no active role -> upgrade to active role
$out[] = array('id'=>$user->user_email, 'r'=>'UPGRADE');
$user->set_role('author');
// log it on the admin site
//@file_get_contents("http://acemonstertoys.org/member/changerole.php?up=1&msg=".urlencode($user->user_email));
@file_get_contents("http://acemonstertoys.org/tmp-logger/logger.php?up=1&msg=".urlencode($user->user_email));
continue;
}
// active membership, active role -> skip
$out[] = array('id'=>$user->user_email, 'r'=>"active $sslug role $rrole");
continue;
} else {
if ($adminRole) { // no active membership & is admin -> skip
$out[] = array('id'=>$user->user_email, 'r'=>"inactive admin $arole");
continue;
}
if (!$activeRole) { // no active membership & no active role -> skip
$out[] = array('id'=>$user->user_email, 'r'=>"inactive role $rrole");
continue;
}
// no active membership but active role -> downgrade role
$out[] = array('id'=>$user->user_email, 'r'=>'DOWNGRADE');
$user->set_role('subscriber');
// log it on the admin site
@file_get_contents("http://acemonstertoys.org/tmp-logger/logger.php?down=1&msg=".urlencode($user->user_email));
}
}
return $out;
}
// Slurp all users and their info
function get_all_users_info($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
$out = array();
// Get all the plans (so we can put their names & slugs into the results without looking up each time)
$plans_in = wc_memberships_get_membership_plans();
$plans = array();
foreach ($plans_in as $plan) {
$plans[$plan->id] = $plan;
}
foreach (get_users() as $user) {
$umeta = get_user_meta($user->ID);
$meta = array();
// List of fields from user metadata that we'd like to pull
$fields = array('nickname','description','wp_capabilities','wp_user_level','ing_phone','ing_email','member_rfid','member_door_code','amt_membership_legal','amt_status_handle','membership_date','membership_agreement_date','liability_waiver_date','has_taken_laser_class','twitter_handle','billing_first_name','billing_last_name','billing_company','billing_address_1','billing_address_2','billing_city','billing_postcode','billing_country','billing_state','billing_phone','billing_email','shipping_first_name','shipping_last_name','shipping_company','shipping_address_1','shipping_address_2','shipping_city','shipping_postcode','shipping_country','shipping_state','account_status','role','_stripe_customer_id','_order_count','_money_spent','paying_customer');
foreach ($fields as $field) {
if (isset($umeta[$field])) {
if (is_array($umeta[$field])) {
$meta[$field] = $umeta[$field][0];
} else {
$meta[$field] = $umeta[$field];
}
}
}
// List of fields from the user object we'd like to pull
$fields = array('ID','user_login','user_nicename','user_email','user_url','display_name','first_name','last_name');
foreach ($fields as $field) {
if (isset($user, $field)) {
$meta[$field] = $user->{$field};
}
}
// Get this guy's WC memberships
$uplans_in = wc_memberships_get_user_memberships($user->ID);
$uplans = array();
// Pull out the data for each plan that we are interested in
foreach ($uplans_in as $uplan_in) {
$uplan = array();
$uplan['id'] = $uplan_in->plan_id;
$uplan['status'] = $uplan_in->get_status();
$uplan['name'] = $plans[$uplan_in->plan_id]->name;
$uplan['slug'] = $plans[$uplan_in->plan_id]->slug;
$uplan['end'] = $uplan_in->get_end_date('timestamp');
$uplans[] = $uplan;
}
$meta['plans'] = $uplans;
$out[] = $meta;
}
return $out;
}
// Return list of all active RFIDs
function active_rfids($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
$rfids = array();
foreach (get_users() as $user) {
$user_id = $user->ID;
if (is_member_active($user_id)) {
$rfid = rfid_for_user($user_id);
if (!empty($rfid)) {
array_push($rfids, $rfid);
}
}
}
$out = array("OK",$rfids);
return $out;
}
// Returns list of all rfids that are active and have a given certification
// Requires auth
// input: cert=certification id
// output: [ "OK", ["0123ABC", "0123ABC" ], "cert" ]
function get_cert_rfids($request) {
if (!validate_request($request)) {
return invalid_request_response();
}
$slugs = membership_plan_slugs();
$rfids = [];
$cert = $request['cert'];
foreach (get_users() as $user) {
$user_id = $user->ID;
if (is_member_active($user_id, $slugs)) {
$rfid = rfid_for_user($user_id);
if (!empty($rfid)) {
$certs = get_field('has_taken_laser_class', 'user_'.$user_id);
if(in_array($cert, $certs))
array_push($rfids, $rfid);
}
}
}
return ["OK", $rfids, $cert];
}
// Counts the number of active, inactive, and operator users
function count_active_users($request)
{ #API
$countA = $countI = $countO = 0;
foreach (get_users() as $user) {
if (wc_memberships_is_user_active_member($user->ID, 'ops-membership')) {
$countO++;
} elseif (is_member_active($user->ID)) {
$countA++;
} else {
$countI++;
}
}
return array($countA, $countI, $countO);
}
// Authenticates the request (just check if they have the right password)
function validate_request($request)
{ #API2
$header = $request->get_header('X-Amt-Auth');
/* FIXME: move to someplace not here */
return $header == "3e532d5d228f9594c55d72978e3d3663ef32ed64dad4d078236ebd24c6a1a2d4fb872d4ef9a84eca78ffeb449afd98a6b4080cecb4124a9cb0dbd3188bf80415";
// return true;
}
// Standard error for wrong pass
function invalid_request_response()
{ #API2
return "['ERROR: Request is invalid']";
}
// Find the user associated with a given RFID
function get_user_for_rfid($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
$rfid = trim($request->get_param('id'));
$member_id = find_member_ids_from_rfid($rfid);
if (empty($member_id)) {
return "Could not find user with ".var_export($rfid, true);
} else {
$member_id = $member_id[0];
} // hopefully there aren't multiple, but maybe there are, pick first
$amtStatusHandle = get_field('amt_status_handle', 'user_'.$member_id);
$userData = get_user_by('ID', $member_id)->to_array();
$userData["amt_status_handle"] = $amtStatusHandle;
return $userData;
}
// Set the end date for a user's membership
// Pass in:
// 'email' (can be email address or userID)
// 'time' unix timestamp to set end date. Must set it in the future for
function set_user_end_date($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
if (!isset($request['email'])) {
return "ERROR: Missing email";
}
if (!isset($request['time'])) {
return "ERROR: Missing end time";
}
$userid = trim($request['email']);
$date = trim($request['time']);
if (isset($request['slug'])) {
$searchslug = $request['slug'];
} else {
$searchslug = 'legacy';
}
$user = get_user_by('ID', $userid);
if (!$user) {
$user = get_user_by('email', $userid);
}
if (!$user) {
return "ERROR: Cannot find user '$userid'";
}
// Get all plans up front so we can look at info about them later
$plans_in = wc_memberships_get_membership_plans();
$plans = array();
foreach ($plans_in as $plan) {
$plans[$plan->id] = $plan;
}
$slugs = array();
foreach ($plans as $plan) {
$slugs[$plan->id] = $plan->slug;
}
// Get all the memberships belonging to the user
$uplans = wc_memberships_get_user_memberships($user->ID);
$out = array();
// Look for plans that are active and match the slug we are searching for, then cancel them
foreach ($uplans as &$plan) {
$status = $plan->get_status();
$slug = $plans[$plan->plan_id]->slug;
if ($status == 'active' && $slug == $searchslug) {
$out[] = array('id'=>$plan->plan_id, 'slug'=>$plans[$plan->plan_id]->slug, 'end'=>$date);
$plan->set_end_date($date);
$plan->cancel_membership("Expired on old site");
}
}
return array('id'=>$user->id, 'email'=>$user->user_email, 'plans_updated'=>$out, 'searchslug'=>$searchslug);
}
// Send out customer invoice email for an order
// Pass in:
// 'orderid'
function send_customer_invoice($request)
{ #API
if (!validate_request($request)) {
return invalid_request_response();
}
if (!isset($request['orderid'])) {
return "ERROR: Missing email";
}
$order = wc_get_order(absint($request['orderid']));
if (!$order) {
return "ERROR: Couldn't find order '".$request['orderid']."'";
}
$wc = WC();
if (!$wc) {
return "ERROR: Couldn't get WC?";
}
$mailer = $wc->mailer();
if (!$mailer) {
return "ERROR: Couldn't get mailer?";
}
$mailer->customer_invoice($order);
return "Probably OK";
}
// Check if current user has any past due orders
function check_unpaid_orders()
{
$orders = wc_get_orders(array(
'status'=>'wc-pending',
'customer'=>get_current_user_id()
));
if (count($orders) > 0) {
return true;
} else {
return false;
}
}
// Logs an rfid action
// input:
// rfid 10-digit RFID tag
// timestamp date/time of the log record
// device the device from the <certs> list
// action list of actions taken by the fobbox
// value value associated with that action
//
function log_rfid($request) {
global $wpdb;
global $amt_db_version;
if (!validate_request($request)) {
return invalid_request_response();
}
$installed_ver = get_option('amt_db_version');
$installed = amt_db_install();
$userid = find_member_ids_from_rfid($request['rfid']);
$table_name = $wpdb->prefix . 'amt_rfid_log';
$wpdb->query( $wpdb->prepare(
"
INSERT INTO $table_name
( timestamp, rfid, userid, device, action, value )
VALUES ( FROM_UNIXTIME(%d), %s, %d, %s, %s, %s )
",
$request['timestamp'],
$request['rfid'],
$userid,
$request['device'],
urldecode($request['action']),
urldecode($request['value'])
) );
$id = $wpdb->insert_id;
$out = [
$id,
$request['rfid'],
$request['timestamp'],
$request['device'],
urldecode($request['action']),
urldecode($request['value']),
$userid,
$installed,
$amt_db_version,
$installed_ver,
$table_name
];
return $out;
}
global $amt_db_version;
$amt_db_version = '1.0';
function amt_db_install() {
global $wpdb;
global $amt_db_version;
$installed_ver = get_option('amt_db_version');
if($installed_ver != $amt_db_version) {
$table_name = $wpdb->prefix . 'amt_rfid_log';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id int(9) NOT NULL AUTO_INCREMENT,
timestamp datetime NOT NULL,
rfid varchar(20),
userid int(9),
device varchar(100),
action varchar(1000),
value varchar(1000),
PRIMARY KEY (id),
KEY timestamp_i (timestamp),
KEY rfid_i (rfid),
KEY userid_i (userid)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$res = dbDelta( $sql );
update_option( 'amt_db_version', $amt_db_version );
return $res;
}
return false;
}
// Map API URLs to PHP methods
add_action('rest_api_init', function () {
register_rest_route('amt/v1', '/rfid/(?P<id>[a-zA-Z0-9]+)/certs', array(
'methods' => 'GET',
'callback' => 'checkcerts'
));
register_rest_route('amt/v1', '/rfid/(?P<id>[a-zA-Z0-9]+)', array(
'methods' => 'GET',
'callback' => 'rfid_status'
));
register_rest_route('amt/v1', '/rfids/active', array(
'methods' => 'GET',