-
Notifications
You must be signed in to change notification settings - Fork 51
/
leyka-core.php
2418 lines (1857 loc) · 92 KB
/
leyka-core.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 if( !defined('WPINC') ) die;
/** Core class. */
class Leyka extends Leyka_Singleton {
protected static $_instance;
/**
* Unique identifier for the plugin.
*
* Use this value (not the variable name) as the text domain when internationalizing strings of text. It should
* match the Text Domain file header in the main plugin file.
* @var string
*/
protected $_plugin_slug = 'leyka';
/**
* Templates order.
* @var array
*/
protected $_templates_order = ['need-help', 'star', 'revo', 'neo', 'toggles', 'radios',];
/**
* Gateways list.
* @var array
*/
protected $_gateways = [];
/** @var array Of WP_Error instances. */
protected $_form_errors = [];
/** @var string Gateway URL to process payment data. */
protected $_payment_url = '';
/** @var mixed Donation form submission redirect type.
* Possible values:
* - 'auto' to submit via POST,
* - 'redirect' to submit via GET,
* - boolean false to turn off auto-submitting
*/
protected $_submission_redirect_type = 'auto';
/** @var integer Currently submitted donation ID. */
protected $_submitted_donation_id = 0;
/** @var array Of key => value pairs of payment form vars to send to the Gateway URL. */
protected $_payment_vars = [];
/**
* Template list.
* @var array
*/
protected $_templates = null;
/** * @var array */
protected $_extensions = [];
/** @var bool|null */
protected $_form_is_screening = false;
/** Initialize the plugin by setting up localization, filters, administration functions etc. */
protected function __construct() {
if( !get_option('leyka_permalinks_flushed') ) {
add_action('init', function(){
flush_rewrite_rules(false);
update_option('leyka_permalinks_flushed', 1);
});
}
add_filter('leyka_option_value', function($value, $option_id){ // If LEYKA_DEBUG const is set, use its value
return $option_id === 'plugin_debug_mode' ?
(defined('LEYKA_DEBUG') && LEYKA_DEBUG !== 'inherit' ? !!LEYKA_DEBUG : $value) : $value;
}, 10, 2);
// By default, we'll assume some errors in the payment form, so redirect will get us back to it:
$this->_payment_url = wp_get_referer();
// Add GTM & UA e-commerce dataLayer if needed:
if( in_array(leyka_options()->opt('use_gtm_ua_integration'), ['simple', 'enchanced', 'enchanced_ua_only']) ) {
add_action('wp_head', [$this, 'add_gtm_data_layer_ua_'.leyka_options()->opt('use_gtm_ua_integration')], -1000);
}
$this->load_public_cssjs();
add_action('init', [$this, 'register_post_types'], 1);
add_action('init', [$this, 'register_user_capabilities'], 1);
add_action('init', [$this, 'register_taxonomies'], 1);
// Leyka rewrite rules - Donor's account pages endpoint:
add_action('init', function(){
add_rewrite_endpoint('donor-account', EP_ROOT, 'leyka-screen');
add_rewrite_endpoint('donor_account', EP_ROOT, 'leyka-screen');
});
add_filter('request', function($query_vars){
if(isset($query_vars['leyka-screen']) && empty($query_vars['leyka-screen'])) {
$query_vars['leyka-screen'] = 'account';
}
return $query_vars;
});
// Leyka rewrite rules - Campaigns & Donations archives:
add_filter('rewrite_rules_array', [$this, 'insert_rewrite_rules']);
add_filter('query_vars', [$this, 'insert_rewrite_query_vars']);
/** @todo Try to make all service URLs via "leyka/service" endpoint */
add_action('parse_request', [$this, 'parse_request']); // Service URLs handlers
if(get_option('leyka_plugin_stats_option_needs_sync')) {
function leyka_sync_stats_option() {
$stats_option_synch_result = leyka_sync_plugin_stats_option();
if(is_wp_error($stats_option_synch_result)) {
return $stats_option_synch_result;
}
return delete_option('leyka_plugin_stats_option_needs_sync')
&& update_option('leyka_plugin_stats_option_sync_done', time());
}
add_action('admin_init', 'leyka_sync_stats_option');
}
// Change the new recurring Donation purpose if it's Campaign is closed:
add_action('leyka_donation_funded_status_changed', function($donation_id, $old_status, $new_status){
$donation = Leyka_Donations::get_instance()->get($donation_id);
if($donation->type !== 'rebill') {
return;
}
$campaign = new Leyka_Campaign($donation->campaign_id);
if($campaign->is_finished) {
$donation->payment_title = apply_filters(
'leyka_finished_campaign_new_recurring_donation_purpose',
__('Charity donation', 'leyka'),
$donation,
$campaign
);
}
}, 10, 3);
add_action('admin_bar_menu', [$this, 'add_toolbar_menu'], 999);
// For Donors management:
if(get_option('leyka_donor_management_available')) {
// Disable logging in if Donor is the only user's role (and user doesn't have an Account access capability):
add_filter('authenticate', function($user, $username, $pass) {
if($user && is_wp_error($user)) {
return $user;
}
if( !$user ) {
$logged_in_user = get_user_by('login', $username);
if(
$logged_in_user
&& leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true, $logged_in_user)
&& !$logged_in_user->has_cap(Leyka_Donor::DONOR_ACCOUNT_ACCESS_CAP)
) {
remove_filter('authenticate', 'wp_authenticate_username_password', 20);
return null;
}
}
return $user;
}, 1000, 3);
// Refuse the login for Donors without Accounts:
add_action('wp_login', function($login, $user){
if( !$user || !is_a($user, 'WP_User') || wp_doing_ajax() ) {
return;
}
/** @var $user WP_User */
if(
leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true, $user)
&& !$user->has_cap(Leyka_Donor::DONOR_ACCOUNT_ACCESS_CAP)
) {
wp_logout();
wp_redirect(home_url());
exit;
}
}, 1000, 2);
// Logout Donors if needed:
add_action('init', function(){
$user = wp_get_current_user();
if(
leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true, $user)
&& !$user->has_cap(Leyka_Donor::DONOR_ACCOUNT_ACCESS_CAP)
) {
wp_logout();
wp_redirect(home_url());
exit;
}
});
}
// For Donor accounts management:
if(get_option('leyka_donor_accounts_available')) {
// Don't show admin bar if Donor is the only user's role:
add_action('init', function(){ // Don't show admin bar
if(leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true)) {
add_filter('show_admin_bar', '__return_false');
}
}, 9);
// If Donor resets his password via WordPress login page, add him an Account capability:
add_action('after_password_reset', function(WP_User $user){
if( !$user || !is_a($user, 'WP_User') || wp_doing_ajax() ) {
return;
}
if(
leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true, $user)
&& !$user->has_cap(Leyka_Donor::DONOR_ACCOUNT_ACCESS_CAP)
) {
Leyka_Donor::update_account_access($user, true);
}
});
// If Donor is successfully logged in, redirect him/her to the Account page:
add_filter('login_redirect', function($redirect_to, $requested_redirect_to, $user){
if( !$user || !is_a($user, 'WP_User') || wp_doing_ajax() ) {
return $redirect_to;
}
/** @var $user WP_User */
return leyka_user_has_role(Leyka_Donor::DONOR_USER_ROLE, true, $user)
&& $user->has_cap(Leyka_Donor::DONOR_ACCOUNT_ACCESS_CAP) ?
site_url('/donor-account/') : $redirect_to;
}, 1000, 3);
add_action('leyka_donor_account_created', [$this, 'handle_non_init_recurring_donor_registration'], 10, 2);
add_action('leyka_donor_account_not_created', [$this, 'handle_donor_account_creation_error'], 10, 2);
}
// Donors management & Donors' accounts fields logical link:
add_action('leyka_set_donor_accounts_available_option_value', function($option_value){
if($option_value) {
update_option('leyka_donor_management_available', true);
}
});
if(is_admin()) { // Admin area only
require_once(LEYKA_PLUGIN_DIR.'inc/settings/allocators/leyka-class-options-allocator.php');
require_once(LEYKA_PLUGIN_DIR.'inc/leyka-settings-rendering-utils.php');
require_once(LEYKA_PLUGIN_DIR.'inc/leyka-admin.php');
require_once(LEYKA_PLUGIN_DIR.'inc/leyka-usage-stats-functions.php');
require_once(LEYKA_PLUGIN_DIR.'inc/leyka-class-portlet-controller.php');
Leyka_Admin_Setup::get_instance();
if(get_option('leyka_init_wizard_redirect')) {
delete_option('leyka_init_wizard_redirect');
add_action('admin_init', function(){
wp_redirect(admin_url('admin.php?page=leyka_settings_new&screen=wizard-init'));
exit;
});
}
} else { // Public (non-admin) area only
function leyka_get_posts(WP_Query $query) {
if(is_admin() || !$query->is_main_query()) {
return;
}
if($query->is_post_type_archive(Leyka_Donation_Management::$post_type)) {
$query->set('post_status', 'funded');
if(get_query_var('leyka_campaign_filter')) {
$campaign = get_posts([
'post_type' => Leyka_Campaign_Management::$post_type,
'name' => get_query_var('leyka_campaign_filter'),
'posts_per_page' => 1,
]);
if( !$campaign ) {
return;
}
$campaign = reset($campaign);
$query->set('meta_query', [['key' => 'leyka_campaign_id', 'value' => $campaign->ID,],]);
}
}
}
add_action('pre_get_posts', 'leyka_get_posts', 1);
function leyka_success_page_widget_template($content) {
if( !is_page(leyka_options()->opt('success_page')) ) {
return $content;
}
$donation_id = leyka_remembered_data('donation_id');
if( !$donation_id ) {
return $content;
}
$donation = Leyka_Donations::get_instance()->get($donation_id);
$campaign_id = $donation ? $donation->campaign_id : null;
$campaign = new Leyka_Campaign($campaign_id);
if( !$campaign->id ) {
return $content;
}
$form_template = $campaign->template;
if( !$form_template ) {
$form_template = leyka_remembered_data('template_id');
}
if(
is_main_query()
&& leyka_options()->opt_template('show_success_widget_on_success', $form_template ? : 'default')
) {
$form_template_suffix = $form_template === 'star' || $form_template === 'need-help' ? '-star' : '';
ob_start();
include LEYKA_PLUGIN_DIR.'templates/service/leyka-template-success-widget'.$form_template_suffix.'.php';
$content = ob_get_clean();
if($form_template === 'star') {
$content .= get_the_content();
}
}
return $content;
}
add_filter('the_content', 'leyka_success_page_widget_template', 1);
function leyka_failure_page_widget_template($content) {
if(
is_main_query()
&& leyka_options()->opt_template('show_failure_widget_on_failure')
&& is_page(leyka_options()->opt('failure_page'))
) {
ob_start();
include(LEYKA_PLUGIN_DIR.'templates/service/leyka-template-failure-widget.php');
$content = ob_get_clean();
}
return $content;
}
add_filter('the_content', 'leyka_failure_page_widget_template', 1);
add_action('wp_head', 'leyka_inline_scripts');
function leyka_inline_scripts(){
$colors = ['#1db318', '#1aa316', '#acebaa']; // Leyka green ?>
<script>
document.documentElement.classList.add("leyka-js");
</script>
<style>
:root {
--color-main: <?php echo esc_attr( $colors[0] );?>;
--color-main-dark: <?php echo esc_attr( $colors[1] );?>;
--color-main-light: <?php echo esc_attr( $colors[2] );?>;
}
</style>
<?php
}
function leyka_template_init_include(WP_Query $query) { // Include template init script
if( // Can't use $query->is_singular(Leyka_Campaign_Management::$post_type) here,
// because there is no $query->get_queried_object_id() value at this point
$query->is_main_query()
&& $query->is_singular()
&& $query->get('post_type') === Leyka_Campaign_Management::$post_type
&& $query->get('name')
) {
$campaign_post = get_posts([
'post_type' => Leyka_Campaign_Management::$post_type,
'name' => $query->get('name'),
'posts_per_page' => 1,
]);
$campaign_post = $campaign_post ? $campaign_post[0] : [];
if( !$campaign_post ) {
return;
}
$campaign = new Leyka_Campaign($campaign_post);
$template = leyka_get_current_template_data($campaign);
if($template && isset($template['file'])) {
$init_file = LEYKA_PLUGIN_DIR.'templates/leyka-' . $template['id'] . '/leyka-' . $template['id'] . '-init';
if( file_exists( $init_file . '.php' ) ) {
require_once( $init_file . '.php' );
}
}
}
}
add_action('pre_get_posts', 'leyka_template_init_include'); // add_action('wp_head', 'leyka_template_init_include');
add_filter('template_include', function($template){
// Embed campaign URL handler:
/** @todo Check if it's still needed feature, or it may be removed. */
if(is_main_query() && is_singular(Leyka_Campaign_Management::$post_type) && !empty($_GET['embed_object'])) {
$new_template = leyka_get_current_template_data(false, 'embed_'.$_GET['embed_object'], true);
if($new_template && !empty($new_template['file'])) {
$template = $new_template['file'];
}
} else {
// Donor's account templates:
$leyka_screen = get_query_var('leyka-screen');
if( !$leyka_screen ) {
return $template;
}
switch($leyka_screen) {
case 'account':
$template = LEYKA_PLUGIN_DIR.'templates/account/account.php';
break;
case 'login':
$template = LEYKA_PLUGIN_DIR.'templates/account/login.php';
break;
case 'reset-password':
$template = LEYKA_PLUGIN_DIR.'templates/account/reset-password.php';
break;
case 'cancel-subscription':
$template = LEYKA_PLUGIN_DIR.'templates/account/cancel-subscription.php';
break;
default:
}
}
return $template;
}, 100);
add_action('template_redirect', [$this, 'gateway_redirect_page'], 1, 1);
}
$this->apply_content_formatting(); // Internal formatting filters
// Plugin data placeholders in the Terms of service / Terms of PD pages content:
add_filter('the_content', [$this, 'apply_terms_pages_content_placeholders'], 100);
if(class_exists('Leyka_Options_Controller')) {
add_action('leyka_do_procedure', [$this, '_do_procedure'], 10, 2);
}
add_action('wp_loaded', [$this, 'refresh_donors_data'], 100);
do_action('leyka_initiated');
}
public function __get($param) {
switch($param) {
case 'v':
case 'version': return LEYKA_VERSION;
case 'plugin_slug': return $this->_plugin_slug;
case 'payment_url': return $this->_payment_url;
case 'payment_vars': return $this->_payment_vars;
case 'submitted_donation_id':
case 'donation_id': return $this->_submitted_donation_id;
case 'auto_redirect': return $this->_submission_redirect_type === 'auto';
case 'redirect_type':
case 'submission_redirect_type':
return $this->_submission_redirect_type;
case 'form_is_screening': return !!$this->_form_is_screening;
case 'extensions': return !!$this->_extensions;
case 'storage_mode':
case 'storage_type':
case 'donations_storage_type':
$storage_type = get_option('leyka_donations_storage_type');
return in_array($storage_type, ['sep', 'post']) ? $storage_type : 'post';
default: return '';
}
}
public function __set($name, $value) {
switch($name) {
case 'form_is_screening':
case 'form_is_displaying':
case 'form_displayed':
if( !$this->_form_is_screening && !!$value ) {
$this->_form_is_screening = !!$value;
}
break;
default:
}
}
/** Fired when the plugin is manually activated. NOT FIRED ON UPDATES. */
public static function activate() {
$leyka_last_ver = get_option('leyka_last_ver');
if( !$leyka_last_ver || version_compare($leyka_last_ver, '3.18', '<=') ) {
leyka_create_separate_donations_db_tables(); // Create plugin-specific DB tables if needed
}
}
public static function deactivate() {
delete_option('leyka_permalinks_flushed');
}
/**
* A shorthand wrapper for the options getter method.
* @param $option_id string
* @param $new_value mixed
* @return mixed
*/
public function opt($option_id, $new_value = null) {
return leyka_options()->opt($option_id, $new_value);
}
public function get_extension_by_id($extension_id) {
$extension_id = trim($extension_id);
return empty($this->_extensions[$extension_id]) ? false : $this->_extensions[$extension_id];
}
/**
* @param boolean|NULL $activation_status If given, get only Extensions with it. NULL to get all Extensions.
* @return array Of Leyka_Extension objects.
*/
public function get_extensions($activation_status = null) {
if( !$activation_status ) {
return $this->_extensions;
}
if( !in_array($activation_status, ['active', 'inactive', 'activating']) ) {
return [];
}
$extensions = [];
foreach($this->_extensions as $extension) { /** @var $extension Leyka_Extension */
if($extension->get_activation_status() === $activation_status) {
$extensions[] = $extension;
}
}
return $extensions;
}
/**
* @param $extension_id string
*
* @throws Exception
* @return boolean True if given Extension has given activation status, false otherwise.
*/
public function extension_is_active($extension_id) {
return leyka_options()->is_multi_value_checked('extensions_active', trim($extension_id));
}
public function refresh_donors_data() {
if( !leyka_options()->opt('donor_management_available') ) {
return;
}
$donations_ordered = get_transient('leyka_donations2refresh_donor_data_cache');
if(is_array($donations_ordered)) {
foreach($donations_ordered as $donation_id) {
$donation = Leyka_Donations::get_instance()->get($donation_id);
if( !$donation ) {
return;
}
// Donor's data cache refresh:
if($donation->donor_user_id) {
try {
Leyka_Donor::calculate_donor_metadata(new Leyka_Donor($donation->donor_user_id));
} catch(Exception $e) {
// ...
}
}
}
delete_transient('leyka_donations2refresh_donor_data_cache');
}
}
public function add_gtm_data_layer_ua_simple() {
if( !is_main_query() || !is_page(leyka()->opt('success_page')) ) {
return;
}
$donation_id = leyka_remembered_data('donation_id');
if( !$donation_id ) {
return;
}
$donation = Leyka_Donations::get_instance()->get($donation_id);
$campaign_id = $donation ? $donation->campaign_id : null;
$campaign = new Leyka_Campaign($campaign_id);
if( !$campaign->id ) {
return;
}
$donation_amount_total = round((float)$donation->amount_total, 2);?>
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'donorEmail': '<?php echo esc_attr(sanitize_email( $donation->donor_email ));?>',
'transactionId': '<?php echo esc_attr( (int)$donation_id );?>',
'transactionAffiliation': '<?php echo esc_attr( get_bloginfo('name') );?>',
'transactionTotal': <?php echo esc_attr( $donation_amount_total );?>,
'transactionTax': 0,
'transactionShipping': 0,
'transactionProducts': [{
'sku': '<?php echo esc_attr( (int)$campaign_id );?>',
'name': '<?php echo esc_attr($campaign->title);?>',
'category': '<?php echo esc_attr($donation->type_label);?>',
'price': <?php echo esc_attr( $donation_amount_total );?>,
'quantity': 1
}],
'donationCampaignPaymentTitle': '<?php echo esc_attr($campaign->payment_title);?>',
'donationFundedDate': '<?php echo esc_attr($donation->date_funded);?>',
'donationGateway': '<?php echo esc_attr($donation->gateway_label);?>',
'donationPm': '<?php echo esc_attr($donation->pm_label);?>',
'donationType': '<?php echo esc_attr($donation->type_label);?>',
'donationAmount': <?php echo esc_attr($donation->amount);?>,
'donationCurrency': '<?php echo esc_attr($donation->currency_label);?>'
});
</script>
<?php }
public function add_gtm_data_layer_ua_enchanced() {
if( !is_main_query() ) {
return;
}
if(is_singular(Leyka_Campaign_Management::$post_type)) {
// Single campaign display - use "detail" e-commerce measurement:
$campaign = new Leyka_Campaign(get_the_ID());
if( !$campaign->id ) {
return;
}?>
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
dataLayer.push({
event: "view_item",
ecommerce: {
currency: "RUB",
value: 0,
items: [{
item_name: '<?php echo esc_attr( $campaign->title ); ?>',
item_id: '<?php echo esc_attr( $campaign->id ); ?>',
price: 0,
item_brand: "donate",
item_category: '<?php esc_html_e('Donations', 'leyka');?>',
quantity: 1
}]
}
});
console.log("action: view_item")
</script>
<?php } else if(is_page(leyka()->opt('success_page'))) {
// Success page display - use "purchase" e-commerce measurement:
$donation_id = leyka_remembered_data('donation_id');
if( !$donation_id ) {
return;
}
$donation = Leyka_Donations::get_instance()->get($donation_id);
$campaign_id = $donation ? $donation->campaign_id : null;
$campaign = new Leyka_Campaign($campaign_id);
if( !$campaign->id ) {
return;
}
$donation_amount_total = round((float)$donation->amount_total, 2);?>
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
dataLayer.push({
event: "purchase",
ecommerce: {
transaction_id: '<?php echo esc_attr( $donation->id ); ?>',
affiliation: '<?php echo esc_attr( $campaign->title ); ?>',
value: '<?php echo esc_attr( $donation_amount_total ); ?>',
tax: "0",
shipping: "0",
currency: "RUS",
items: [{
item_name: '<?php echo esc_attr( $campaign->title ); ?>',
item_id: '<?php echo esc_attr( $donation->id ); ?>',
price: '<?php echo esc_attr( $donation_amount_total ); ?>',
item_brand: '<?php echo esc_html( get_bloginfo('name') ); ?>',
item_category: '<?php echo esc_attr( $donation->type_label ); ?>',
quantity: 1
}]
}
});
console.log("action: purchase")
</script>
<?php }
// Donation form submit click - "add" e-commerce measurement used in JS 'submit.leyka' handlers ?>
<?php }
public function add_gtm_data_layer_ua_enchanced_ua_only() {
if( !is_main_query()) {
return;
}
if(is_singular(Leyka_Campaign_Management::$post_type)) {
if( // GUA direct integration - "detail" event:
leyka_options()->opt('use_gtm_ua_integration') === 'enchanced_ua_only'
&& leyka_options()->opt('gtm_ua_tracking_id')
&& in_array('detail', leyka_options()->opt('gtm_ua_enchanced_events'))
) {
require_once LEYKA_PLUGIN_DIR.'vendor/autoload.php';
$campaign = new Leyka_Campaign(get_the_ID());
$analytics = new TheIconic\Tracking\GoogleAnalytics\Analytics(true);
$analytics // Main params:
->setProtocolVersion('1')
->setTrackingId(leyka_options()->opt('gtm_ua_tracking_id'))
->setClientId(leyka_gua_get_client_id())
->setDocumentLocationUrl(get_permalink($campaign->id))
// Transaction params:
->addProduct([ // Campaign params
'name' => $campaign->payment_title,
'brand' => get_bloginfo('name'), // Mb, it won't work with it
])
->setProductActionToDetail()
->setEventCategory('Checkout')
->setEventAction('Detail')
->sendEvent();
}
// GUA direct integration - "detail" event END
}
}
/** @todo Create a procedure to get actual currencies rates and save them in the plugin options values */
public function do_currencies_rates_refresh() {
}
public function load_public_cssjs() {
add_action('wp_enqueue_scripts', [$this, 'enqueue_styles']);
add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
add_action('wp_enqueue_scripts', [$this, 'localize_scripts']);
}
public function parse_request() {
if(stristr($_SERVER['REQUEST_URI'], 'leyka/service') !== false) { // Leyka service URL
$request = explode('leyka/service', $_SERVER['REQUEST_URI']);
$request = explode('/', trim($request[1], '/'));
if($request[0] === 'do_recurring') { // Active recurring shortcut URL
do_action('leyka_do_procedure', 'active-recurring');
} else if($request[0] === 'cancel_recurring' && !empty($request[1]) && !empty($request[2])) {
$donation = Leyka_Donations::get_instance()->get_donation($request[1]);
$hash = md5($donation->id.'_'.$donation->init_recurring_donation_id.'_leyka_cancel_recurring_subscription');
if($donation && $hash === $request[2]) {
do_action("leyka_{$donation->gateway_id}_cancel_recurring_subscription_by_link", $donation);
}
} else if($request[0] === 'update_recurring_subscriptions') {
do_action('leyka_do_procedure', 'update-recurring-subscriptions');
} else if($request[0] === 'refresh_currencies_rates') {
do_action('leyka_do_procedure', 'refresh-currencies-rates');
} else if($request[0] === 'do_campaigns_targets_reaching_mailout') {
// Campaigns target reached mailout shortcut URL:
do_action(
'leyka_do_procedure',
'campaigns-targets-reaching-mailout',
empty($request[1]) ? [] : array((int)$request[1])
);
} else if(isset($request[0], $request[1]) && mb_stristr($request[0], 'procedure') !== false) {
// Common procedure call URL,
// like some-website.org/leyka/service/procedure/{procedure_name}[/{param_1}/{param_2}/...]
// E.g.:
// * some-website.org/leyka/service/procedure/active-recurring
// * some-website.org/leyka/service/procedure/campaigns-targets-reaching-mailout/123
do_action('leyka_do_procedure', $request[1], array_slice($request, 2));
} else if($request[0] === 'get_usage_stats') {
echo '';
/* Statistics collection disabled
// The file bin/sodium-compat.phar was removed in version 3.31.4
// Plugin check: Phar files are not permitted.
require_once LEYKA_PLUGIN_DIR.'bin/sodium-compat.phar';
if( !$this->_outer_request_allowed() ) {
exit;
}
echo empty($_GET['tst']) ?
\Sodium\crypto_box_seal(
wp_json_encode($this->_get_usage_stats($_REQUEST)),
\Sodium\hex2bin(get_option('leyka_stats_sipher_public_key'))
) :
'<pre>'.print_r($this->_get_usage_stats($_REQUEST), 1).'</pre>';
*/
} else { // Gateway callback URL
// Callback URLs are: some-website.org/leyka/service/{gateway_id}/{action_name}/
// E.g., some-website.org/leyka/service/yandex/check_order/
if( !empty($request[1]) && stristr($request[1], '?') !== false ) { // Remove GET params from the callback
$request[1] = mb_substr($request[1], 0, stripos($request[1], '?'));
}
// $request[0] - Gateway ID, $request[1] - service action:
do_action('leyka_service_call-'.$request[0], empty($request[1]) ? '' : $request[1]);
}
exit();
}
}
public function add_toolbar_menu(WP_Admin_Bar $wp_admin_bar) {
if( !current_user_can('leyka_manage_donations') ) {
return;
}
$wp_admin_bar->add_node([
'id' => 'leyka-toolbar-menu',
'title' => __('Leyka', 'leyka'),
'href' => admin_url('admin.php?page=leyka'),
]);
$wp_admin_bar->add_node([
'id' => 'leyka-toolbar-desktop',
'title' => __('Desktop', 'leyka'),
'parent' => 'leyka-toolbar-menu',
'href' => admin_url('admin.php?page=leyka'),
]);
$wp_admin_bar->add_node([
'id' => 'leyka-toolbar-donations',
'title' => __('Donations', 'leyka'),
'parent' => 'leyka-toolbar-menu',
'href' => admin_url('admin.php?page=leyka_donations'),
]);
$wp_admin_bar->add_node([
'id' => 'leyka-toolbar-campaigns',
'title' => __('Campaigns', 'leyka'),
'parent' => 'leyka-toolbar-menu',
'href' => admin_url('edit.php?post_type='.Leyka_Campaign_Management::$post_type),
]);
if(current_user_can('leyka_manage_options')) {
$wp_admin_bar->add_node([
'id' => 'leyka-toolbar-settings',
'title' => __('Settings', 'leyka'),
'parent' => 'leyka-toolbar-menu',
'href' => admin_url('admin.php?page=leyka_settings'),
]);
}
}
/** @todo Make it a procedure */
public function _do_currency_rates_refresh() {
foreach(leyka_get_actual_currency_rates() as $currency => $rate) {
update_option('leyka_currency_rur2'.mb_strtolower($currency), $rate);
}
}
public function _do_procedure($procedure_id, $params = []) {
$procedure_id = mb_stristr($procedure_id, 'leyka-') !== false ? str_replace('leyka-', '', $procedure_id) : $procedure_id;
do_action('leyka_before_procedure', $procedure_id, $params);
// Via URL: some-website.org/leyka/service/procedure/campaigns-targets-reaching-mailout/123
// Via PHP CLI: php [-f] /absolute/address/to/leyka/procedures/leyka-campaigns-target-reaching-mailout.php -- 123
$procedure_script = apply_filters(
'leyka_procedure_address',
LEYKA_PLUGIN_DIR.'procedures/leyka-'.$procedure_id.'.php',
$procedure_id,
$params
);
if(file_exists($procedure_script)) {