-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPricing Table Shortcode.php
More file actions
2460 lines (2247 loc) · 112 KB
/
Pricing Table Shortcode.php
File metadata and controls
2460 lines (2247 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
/**
* BrightLeaf Pricing Table — Single‑file Shortcode Snippet
*
* Goal
* - Make it easy to add a clear, modern pricing table to any page with simple shortcodes.
* - Keep everything in one place: the layout, styles, and behavior live in this single file.
* - Optionally connect to Freemius for checkout and, if you want, automatically load your plans and prices.
*
* Features
* - Clean pricing cards with a Monthly/Annual toggle.
* - One or more plans, each with license tiers, a short description, and a feature list.
* - Site count selector that stays in sync across all plans.
* - Optional Freemius checkout (Buy and Trial buttons), including license count and billing cycle.
* - Optional “Automatic” mode to pull plans and prices from your Freemius account.
* - All CSS and JS are included right here and only appear once per page.
*
* Requirements
* - WordPress page or post where you can paste shortcodes.
* - For Freemius checkout (manual plan entry): your product’s Public Key, Product ID, and each plan’s Plan ID.
* - For Freemius “Automatic” mode: your Freemius Product ID and a token stored in a PHP constant.
*
* How To Use
* 1) Parent shortcode
* Place the parent shortcode on the page. It controls product information, Freemius options, and overall behavior.
*
* [gopricingtable
* public_key="pk_XXXX"
* product_name="Your Product"
* product_id="12345"
* freemius=""|"manual"|"automatic"
* buy_url="https://example.com/buy"
* trial_url="https://example.com/trial"
* product_prefix="your-product"
* currency="usd|eur|gbp"
* cache_ttl="21600"
* site_tiers_label="Single Site|Up to 3 Sites|Up to 10 Sites"
* bearer_constant="FS_API_TOKEN"
* coupon="123,456"
* discount="$10" | "15%"
* ]
* ...one or more child plan shortcodes...
* [/gopricingtable]
*
* Parent attributes (plain language reference):
* - public_key
* What: Your Freemius public key.
* When required: Required when freemius="manual" (for checkout). Optional when freemius is empty (no checkout). In freemius="automatic", it can be filled automatically from your account.
* - product_name
* What: Shown in checkout and used for button IDs if you don’t set a prefix.
* When required: Optional, but recommended so buyers see a friendly name.
* - product_id
* What: Your Freemius product ID.
* When required: Required for freemius="manual" and freemius="automatic". Optional when freemius is empty.
* - freemius
* What: Turns Freemius features on.
* Values: "" (off), "manual" (checkout on, you enter plans), "automatic" (checkout on, plans/prices loaded for you).
* - buy_url / trial_url
* What: Where the buttons go when freemius is empty.
* When required: Optional. Add one or both so the buttons have a destination when not using Freemius.
* - product_prefix
* What: A short ID added to button IDs (helps with analytics and testing).
* When required: Optional. If omitted, a neat prefix is created from your product name.
* - currency
* What: Currency to show when using freemius="automatic".
* Values: usd (default), eur, gbp.
* - cache_ttl
* What: How long to keep automatic pricing (in seconds). Default: 21600 (6 hours). Use 0 to always refresh.
* - coupon
* What: Optional comma-separated list of Freemius coupon IDs to apply (automatic Freemius mode only). They will be stacked in the order provided.
* - discount
* What: Manual/empty modes only. Discount to show in pricing and banners. Use "$10" for flat or "15%" for percentage. Can be overridden per plan.
* - site_tiers_label
* What: Optional list of labels for the site tiers in automatic mode (pipe‑separated).
* Example: "Single Site|Up to 3 Sites|Up to 10 Sites".
* - bearer_constant
* What: The name of a PHP constant that holds your Freemius token for automatic mode.
* When required: Required for freemius="automatic". Example: define('FS_API_TOKEN', 'your_token_here');
*
* 2) Child plan shortcode
* Add one child for each plan (these act as settings; they don’t print anything by themselves).
*
* [go_plan_column
* plan_name="Pro"
* plan_id="111"
* site_tiers_label="Single Site|Up to 3 Sites"
* site_tiers="1|3"
* monthly="9.99|14.99"
* annual="89.99|134.99"
* plan_desc="Great for individuals"
* plan_features="Feature A|Feature B|Feature C"
* best_value="true"
* has_trial="true"
* ]
*
* Child attributes (plain language reference):
* - plan_name
* What: The name shown on the card (e.g., Pro, Premium, Agency).
* When required: Yes.
* - plan_id
* What: The plan’s ID in Freemius (used by checkout).
* When required: Required when freemius is on (manual or automatic). Optional when freemius is off.
* - site_tiers_label
* What: The labels people see for each site tier (pipe‑separated).
* Example: "Single Site|Up to 3 Sites".
* - site_tiers
* What: The matching site counts (pipe‑separated numbers).
* Example: "1|3".
* - monthly / annual
* What: Prices for each tier (pipe‑separated to match your tiers). You can provide one or both. If both are present, Annual highlights the per‑month savings.
* Examples: monthly="9.99|14.99" and/or annual="89.99|134.99".
* - plan_desc
* What: Short sentence under the buttons.
* When required: Optional.
* - plan_features
* What: Bullet points for the feature list (pipe‑separated).
* Example: "Feature A|Feature B|Feature C".
* - best_value
* What: Mark true for the plan you want highlighted as “Best Value”. If you don’t pick one, the table may highlight a plan based on savings.
* Values: true or false. Optional.
* - has_trial
* What: Show or hide the “Free Trial” button for this plan.
* Values: true (default) or false.
*
* Examples
* - Manual plans with Freemius checkout:
* [gopricingtable public_key="pk_XXXX" product_name="My Add‑on" product_id="12345" freemius="manual"]
* [go_plan_column plan_name="Pro" plan_id="111" site_tiers_label="Single Site|Up to 3 Sites" site_tiers="1|3" monthly="9.99|14.99" annual="89.99|134.99" plan_desc="For individual sites" plan_features="Feature A|Feature B|Feature C"]
* [go_plan_column plan_name="Premium" plan_id="222" best_value="true" site_tiers_label="Single Site|Up to 3 Sites" site_tiers="1|3" monthly="14.99|24.99" annual="134.99|224.99" plan_desc="For growing teams" plan_features="Everything in Pro|Priority support"]
* [/gopricingtable]
*
* - Automatic plans (no child plans needed):
* [gopricingtable freemius="automatic" product_id="15834" currency="usd" bearer_constant="FS_API_TOKEN"]
* Tip: Define your token once, for example in wp-config.php: define('FS_API_TOKEN', 'your_token_here');
*
* Behavior Notes
* - Monthly/Annual toggle: When Annual is selected, each plan shows the average per‑month price and the yearly total underneath.
* - Site tiers: Picking a site count updates all plans so visitors compare fairly.
* - Buttons: When Freemius is on, Buy and Trial open checkout with the selected site count and billing cycle. When Freemius is off, buttons go to your links with helpful details added to the URL.
* - Best Value badge: Use it to guide visitors to the plan you recommend.
*
* Accessibility
* - Keyboard‑friendly controls with visible focus outlines.
* - Clear labels and logical order of information.
* - Good color contrast aimed at comfortable reading.
*
* Helpful Tips
* - Keep feature lists short and benefit‑focused.
* - Use consistent site tiers across plans so comparisons are easy.
* - If you only sell yearly on a plan, you can leave out the monthly price.
* - Set a friendly product_name so the checkout panel looks polished.
* - If you share snippets with your team, add a product_prefix to make button IDs easy to find in analytics.
*
* Support & Troubleshooting
* - If nothing appears, double‑check that at least one child plan is inside the parent (unless you’re using automatic mode).
* - If buttons do nothing, confirm you set freemius and provided the required product details, or that your links are correct when freemius is off.
* - In automatic mode, make sure the token constant exists and has the right value.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class responsible for managing and rendering a pricing table.
*/
class Bld_Go_PricingTable {
/**
* Singleton instance.
*
* @var Bld_Go_PricingTable|null
*/
private static $instance = null;
/**
* Whether the assets have already been printed.
*
* @var bool
*/
private $assets_printed = false;
/**
* Retrieves the singleton instance of the class.
*
* @return self The single instance of the class.
*/
public static function get() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Registers the 'init' action hook.
*
* Adds the 'on_init' method to the WordPress 'init' action hook.
*
* @return void
*/
public function register() {
add_action( 'init', [ $this, 'on_init' ] );
}
/**
* Initializes shortcodes used by the class.
*
* @return void
*/
public function on_init() {
add_shortcode( 'gopricingtable', [ $this, 'render_parent' ] );
// Child becomes a no-op; parent will parse its attributes directly.
add_shortcode( 'go_plan_column', '__return_empty_string' );
}
// --- Utilities ---
/**
* Parses a pipe-separated string and returns an array of trimmed, decoded elements.
*
* @param mixed $raw The raw pipe-separated string to be parsed.
* @return array An array of trimmed and HTML entity-decoded elements. If the input string is empty or contains only whitespace, an empty array is returned.
*/
public function parse_pipe_list( $raw ) {
$raw = (string) $raw;
if ( '' === trim( $raw ) ) {
return [];
}
$parts = explode( '|', $raw );
$out = [];
foreach ( $parts as $p ) {
$p = trim( $p );
if ( '' !== $p ) {
$out[] = html_entity_decode( $p, ENT_QUOTES );
}
}
return $out;
}
/**
* Converts a formatted money string into a float.
*
* @param string $s The money string to convert, which may include symbols, commas, or spaces.
* @return float The numeric representation of the money string. Returns 0.0 if the input is not numeric.
*/
public function money_to_float( $s ): float {
$s = str_replace( [ '$', ',', ' ' ], '', trim( (string) $s ) );
return is_numeric( $s ) ? (float) $s : 0.0;
}
/**
* Fetches the Freemius pricing table for a given product.
*
* @param string $product_id The Freemius product ID.
* @param string $currency The currency code (default is 'USD'). Supported values are 'USD', 'EUR', and 'GBP'.
* @param int $cache_ttl The time-to-live for the cached response in seconds (default is 21600).
* @param string $bearer The Freemius API token for authentication.
*
* @return array|WP_Error The pricing table as an associative array on success, or a WP_Error object on failure.
*/
public function fetch_freemius_pricing_table( $product_id, $currency = 'USD', $cache_ttl = 21600, $bearer = '' ) {
$product_id = trim( $product_id );
if ( '' === $product_id ) {
return new WP_Error( 'go_pt_fs_missing_product', 'Missing Freemius product_id.' );
}
if ( '' === trim( $bearer ) ) {
return new WP_Error( 'go_pt_fs_missing_token', 'Missing Freemius API token.' );
}
$endpoint = sprintf( 'https://api.freemius.com/v1/products/%s/pricing.json', rawurlencode( $product_id ) );
$currency = strtoupper( trim( $currency ) );
if ( ! in_array( $currency, [ 'USD', 'EUR', 'GBP' ], true ) ) {
return new WP_Error( 'go_pt_fs_invalid_currency', 'Invalid currency code. Supported: USD, EUR, GBP.' );
}
$url = add_query_arg(
[
'currency' => $currency,
'type' => 'visible',
'is_enriched' => 'true',
],
$endpoint
);
$cache_key = 'bld_go_pt_fs_' . md5( $url );
if ( $cache_ttl > 0 ) {
$cached = get_transient( $cache_key );
if ( $cached ) {
return $cached;
}
}
$args = [
'timeout' => 20,
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $bearer,
],
];
$resp = wp_remote_get( $url, $args );
if ( is_wp_error( $resp ) ) {
return $resp;
}
$code = (int) wp_remote_retrieve_response_code( $resp );
if ( $code < 200 || $code >= 300 ) {
return new WP_Error( 'go_pt_fs_http_' . $code, 'Freemius API error: HTTP ' . $code );
}
$body = wp_remote_retrieve_body( $resp );
$data = json_decode( $body, true );
if ( ! is_array( $data ) ) {
return new WP_Error( 'go_pt_fs_bad_json', 'Freemius API returned invalid JSON.' );
}
if ( $cache_ttl > 0 ) {
set_transient( $cache_key, $data, $cache_ttl );
}
return $data;
}
/**
* Fetch a single Freemius coupon (enriched) for the given product.
*
* @param string $product_id The Freemius product ID.
* @param string $coupon_id The Freemius coupon ID.
* @param string $currency The currency code (default is 'USD'). Supported values are 'USD', 'EUR', and 'GBP'.
* @param int $cache_ttl The time-to-live for the cached response in seconds (default is 21600).
* @param string $bearer The Freemius API token for authentication.
*
* @return array|WP_Error The coupon details as an associative array on success, or a WP_Error object on failure.
*/
public function fetch_freemius_coupon( $product_id, $coupon_id, $currency = 'USD', $cache_ttl = 21600, $bearer = '' ) {
$product_id = trim( $product_id );
$coupon_id = trim( $coupon_id );
if ( '' === $product_id || '' === $coupon_id ) {
return new WP_Error( 'go_pt_fs_coupon_missing_params', 'Missing Freemius product_id or coupon_id.' );
}
if ( '' === trim( $bearer ) ) {
return new WP_Error( 'go_pt_fs_coupon_missing_token', 'Missing Freemius API token.' );
}
$endpoint = sprintf(
'https://api.freemius.com/v1/products/%s/coupons/%s.json',
rawurlencode( $product_id ),
rawurlencode( $coupon_id )
);
$currency = strtoupper( trim( $currency ) );
if ( ! in_array( $currency, [ 'USD', 'EUR', 'GBP' ], true ) ) {
$currency = 'USD';
}
$url = add_query_arg(
[
'is_enriched' => 'true',
'currency' => $currency,
],
$endpoint
);
$cache_key = 'bld_go_pt_fs_coupon_' . md5( $url );
if ( $cache_ttl > 0 ) {
$cached = get_transient( $cache_key );
if ( $cached ) {
return $cached;
}
}
$args = [
'timeout' => 20,
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $bearer,
],
];
$resp = wp_remote_get( $url, $args );
if ( is_wp_error( $resp ) ) {
return $resp;
}
$code = (int) wp_remote_retrieve_response_code( $resp );
if ( $code < 200 || $code >= 300 ) {
return new WP_Error( 'go_pt_fs_coupon_http_' . $code, 'Freemius API error: HTTP ' . $code );
}
$body = wp_remote_retrieve_body( $resp );
$data = json_decode( $body, true );
if ( ! is_array( $data ) ) {
return new WP_Error( 'go_pt_fs_coupon_bad_json', 'Freemius API returned invalid JSON for coupon.' );
}
if ( $cache_ttl > 0 ) {
set_transient( $cache_key, $data, $cache_ttl );
}
return $data;
}
/**
* Parse a comma-separated list of coupon IDs.
*
* @param string $raw Raw string.
* @return array Sanitized list of coupon IDs (strings).
*/
public function parse_coupon_ids( $raw ) {
$out = [];
foreach ( explode( ',', (string) $raw ) as $id ) {
$id = trim( $id );
if ( '' === $id ) {
continue;
}
$out[] = $id;
}
return array_values( array_unique( $out ) );
}
/**
* Parse a discount string like "$10" or "15%".
*
* @param string $raw Raw discount string.
* @return array|null Array with keys type ('dollar'|'percentage') and amount (float) or null if invalid.
*/
public function parse_discount_string( $raw ) {
$raw = trim( (string) $raw );
if ( '' === $raw ) {
return null;
}
if ( preg_match( '/^\\$\\s*([0-9]+(?:\\.[0-9]+)?)$/', $raw, $m ) ) {
return [
'type' => 'dollar',
'amount' => (float) $m[1],
];
}
if ( preg_match( '/^([0-9]+(?:\\.[0-9]+)?)\\s*%$/', $raw, $m ) ) {
return [
'type' => 'percentage',
'amount' => (float) $m[1],
];
}
return null;
}
/**
* Normalize a coupon response into a structured array for evaluation.
*
* @param array $coupon Raw coupon array.
*
* @return array Normalized coupon details.
*/
public function normalize_coupon_record( $coupon ) {
if ( ! is_array( $coupon ) ) {
return [ 'is_valid' => false ];
}
$discount_type = strtolower( (string) ( $coupon['discount_type'] ?? '' ) );
if ( ! in_array( $discount_type, [ 'percentage', 'dollar' ], true ) ) {
$discount_type = '';
}
$discount_val = $this->money_to_float( $coupon['discount'] ?? 0 );
$discount_map = [];
if ( isset( $coupon['discounts'] ) && is_array( $coupon['discounts'] ) ) {
foreach ( [ 'usd', 'eur', 'gbp' ] as $cur ) {
if ( isset( $coupon['discounts'][ $cur ] ) ) {
$discount_map[ $cur ] = $this->money_to_float( $coupon['discounts'][ $cur ] );
}
}
}
$plans_raw = isset( $coupon['plans'] ) ? explode( ',', (string) $coupon['plans'] ) : [];
$plans_list = [];
foreach ( $plans_raw as $pid ) {
$pid = trim( $pid );
if ( '' !== $pid ) {
$plans_list[] = $pid;
}
}
$licenses_raw = isset( $coupon['licenses'] ) ? explode( ',', (string) $coupon['licenses'] ) : [];
$licenses_list = [];
foreach ( $licenses_raw as $lic ) {
$lic = trim( $lic );
if ( '' !== $lic ) {
$licenses_list[] = (int) $lic;
}
}
$cycles_raw = isset( $coupon['billing_cycles'] ) ? explode( ',', (string) $coupon['billing_cycles'] ) : [];
$cycles = [];
foreach ( $cycles_raw as $c ) {
$c = trim( $c );
if ( '' === $c ) {
continue;
}
$label = $this->coupon_cycle_label_from_value( $c );
if ( $label ) {
$cycles[] = $label;
}
}
$start_ts = null;
if ( ! empty( $coupon['start_date'] ) ) {
$tmp = strtotime( (string) $coupon['start_date'] );
if ( false !== $tmp ) {
$start_ts = $tmp;
}
}
$end_ts = null;
if ( ! empty( $coupon['end_date'] ) ) {
$tmp = strtotime( (string) $coupon['end_date'] );
if ( false !== $tmp ) {
$end_ts = $tmp;
}
}
$redemptions = (int) ( $coupon['redemptions'] ?? 0 );
$redemptions_limit = isset( $coupon['redemptions_limit'] ) ? (int) $coupon['redemptions_limit'] : null;
$is_active = ! empty( $coupon['is_active'] );
$now = time();
if ( $start_ts && $now < $start_ts ) {
$is_active = false;
}
if ( $end_ts && $now > $end_ts ) {
$is_active = false;
}
if ( null !== $redemptions_limit && $redemptions >= $redemptions_limit ) {
$is_active = false;
}
$code = (string) ( $coupon['code'] ?? '' );
return [
'is_valid' => $is_active && '' !== $code && '' !== $discount_type && ( $discount_val > 0 || ! empty( $discount_map ) ),
'id' => (string) ( $coupon['id'] ?? '' ),
'code' => $code,
'discount_type' => $discount_type,
'discount' => $discount_val,
'discounts' => $discount_map,
'plans' => $plans_list,
'licenses' => $licenses_list,
'cycles' => $cycles,
'redemptions_limit' => $redemptions_limit,
'redemptions' => $redemptions,
'start_ts' => $start_ts,
'end_ts' => $end_ts,
];
}
/**
* Map Freemius billing cycle values to internal labels.
*
* @param string|int $val Billing cycle value.
* @return string|null
*/
private function coupon_cycle_label_from_value( $val ) {
$val = (string) $val;
if ( '1' === $val || 'monthly' === strtolower( $val ) ) {
return 'Monthly';
}
if ( '12' === $val || 'annual' === strtolower( $val ) || 'yearly' === strtolower( $val ) ) {
return 'Annual';
}
return null;
}
/**
* Determine if a coupon applies to a plan.
*
* @param array $coupon Normalized coupon data.
* @param string $plan_id Current plan ID.
* @return bool
*/
private function coupon_supports_plan( $coupon, $plan_id ) {
if ( empty( $coupon['plans'] ) ) {
return true;
}
return in_array( (string) $plan_id, $coupon['plans'], true );
}
/**
* Determine if a coupon applies to the requested licenses count.
*
* @param array $coupon Normalized coupon data.
* @param int $licenses License count.
* @return bool
*/
private function coupon_supports_license( $coupon, $licenses ) {
if ( empty( $coupon['licenses'] ) ) {
return true;
}
if ( in_array( 0, $coupon['licenses'], true ) ) {
return true;
}
return in_array( (int) $licenses, $coupon['licenses'], true );
}
/**
* Determine if a coupon applies to the billing cycle.
*
* @param array $coupon Normalized coupon data.
* @param string $cycle Cycle label ('Monthly'|'Annual').
* @return bool
*/
private function coupon_supports_cycle( $coupon, $cycle ) {
if ( empty( $coupon['cycles'] ) ) {
return true;
}
return in_array( $cycle, $coupon['cycles'], true );
}
/**
* Get the fixed discount value for a currency, if present.
*
* @param array $coupon Normalized coupon data.
* @param string $currency Currency code (lowercase).
* @return float
*/
private function coupon_fixed_amount( $coupon, $currency ) {
if ( isset( $coupon['discounts'][ $currency ] ) ) {
return (float) $coupon['discounts'][ $currency ];
}
return (float) ( $coupon['discount'] ?? 0 );
}
/**
* Apply stacked coupons to plan pricing.
*
* @param array $plans Plans array.
* @param array $coupons Normalized coupon array.
* @param string $currency Currency code (lowercase).
* @return array Adjusted pricing map.
*/
public function apply_coupons_to_pricing( $plans, $coupons, $currency = 'usd' ) {
$currency = strtolower( $currency );
$out = [];
foreach ( $plans as $pl ) {
$plan_id = (string) ( $pl['plan_id'] ?? '' );
if ( '' === $plan_id ) {
continue;
}
$out[ $plan_id ] = [];
foreach ( $pl['terms'] as $licenses => $term_row ) {
$current_monthly = isset( $term_row['Monthly'] ) ? $this->money_to_float( $term_row['Monthly'] ) : null;
$current_annual = isset( $term_row['Annual'] ) ? $this->money_to_float( $term_row['Annual'] ) : null;
$licenses_int = (int) $licenses;
foreach ( [ 'Monthly', 'Annual' ] as $cycle ) {
if ( 'Monthly' === $cycle && null === $current_monthly ) {
continue;
}
if ( 'Annual' === $cycle && null === $current_annual ) {
continue;
}
$base_price = ( 'Monthly' === $cycle ) ? $current_monthly : $current_annual;
$final = $base_price;
$applied = [];
foreach ( $coupons as $coupon ) {
if ( empty( $coupon['is_valid'] ) ) {
continue;
}
if ( ! $this->coupon_supports_plan( $coupon, $plan_id ) ) {
continue;
}
if ( ! $this->coupon_supports_license( $coupon, $licenses_int ) ) {
continue;
}
if ( ! $this->coupon_supports_cycle( $coupon, $cycle ) ) {
continue;
}
$amount_off = 0.0;
if ( 'percentage' === $coupon['discount_type'] ) {
$amount_off = $final * ( (float) ( $coupon['discount'] ?? 0 ) / 100 );
} elseif ( 'dollar' === $coupon['discount_type'] ) {
$amount_off = $this->coupon_fixed_amount( $coupon, $currency );
}
$amount_off = max( 0.0, $amount_off );
$amount_off = min( $final, $amount_off );
$final -= $amount_off;
if ( $amount_off > 0 ) {
$applied[] = [
'id' => $coupon['id'],
'code' => $coupon['code'],
'type' => $coupon['discount_type'],
'scope' => empty( $coupon['plans'] ) ? 'global' : 'plan',
'amount_off' => $amount_off,
'cycle' => $cycle,
'license' => $licenses_int,
'plan_id' => $plan_id,
'base_price' => $base_price,
'final_price' => $final,
];
}
}
$out[ $plan_id ][ $licenses ][ $cycle ] = [
'base' => $base_price,
'final' => $final,
'applied' => $applied,
];
}
}
}
return $out;
}
/**
* Transforms Freemius pricing data into a structured format for product plans.
*
* @param array $fs_data The Freemius data containing product and pricing information.
* @param array $labels_override Optional. An associative array of custom label overrides for site tiers.
*
* @return array An associative array containing 'product' details and 'plans' information.
*/
public function transform_fs_pricing_to_plans( $fs_data, $labels_override = [] ) {
$product = [
'product_name' => '',
'public_key' => '',
];
if ( isset( $fs_data['plugin'] ) && is_array( $fs_data['plugin'] ) ) {
$product['product_name'] = (string) ( $fs_data['plugin']['title'] ?? '' );
$product['public_key'] = (string) ( $fs_data['plugin']['public_key'] ?? '' );
}
$plans_out = [];
$best_plan_idx = -1;
$best_plan_pct = -1;
$plans = $fs_data['plans'] ?? [];
foreach ( $plans as $idx => $pl ) {
if ( ! is_array( $pl ) ) {
continue;
}
$plan_id = isset( $pl['id'] ) ? (string) $pl['id'] : '';
$plan_title = (string) ( $pl['title'] ?? ( $pl['name'] ?? '' ) );
if ( '' === $plan_id || '' === $plan_title ) {
continue;
}
$pricing = is_array( $pl['pricing'] ?? null ) ? $pl['pricing'] : [];
$site_tiers = [];
$terms = [];
foreach ( $pricing as $p_idx => $p ) {
if ( ! is_array( $p ) ) {
continue;
}
$licenses = (int) ( $p['licenses'] ?? 0 );
if ( $licenses <= 0 ) {
continue;
}
if ( isset( $labels_override[ $p_idx ] ) ) {
$label = (string) $labels_override[ $p_idx ];
} else {
$label = ( 1 === $licenses ) ? 'Single Site' : ( 'Up to ' . $licenses . ' Sites' );
}
$site_tiers[ $label ] = (string) $licenses;
$row = [];
if ( isset( $p['monthly_price'] ) && '' !== $p['monthly_price'] ) {
$row['Monthly'] = (float) $p['monthly_price'];
}
if ( isset( $p['annual_price'] ) && '' !== $p['annual_price'] ) {
$row['Annual'] = (float) $p['annual_price'];
}
if ( ! empty( $row ) ) {
$terms[ (string) $licenses ] = $row;
}
}
if ( empty( $terms ) ) {
continue;
}
$has_trial = false;
if ( isset( $pl['trial_period'] ) ) {
$has_trial = ( (int) $pl['trial_period'] ) > 0;
}
$plan_pct = 0;
foreach ( $terms as $row ) {
if ( isset( $row['Monthly'], $row['Annual'] ) && $row['Monthly'] > 0 && $row['Annual'] > 0 ) {
$pct = round( max( 0, ( $row['Monthly'] * 12 ) - $row['Annual'] ) / ( $row['Monthly'] * 12 ) * 100 );
if ( $pct > $plan_pct ) {
$plan_pct = $pct;
}
}
}
$desc = (string) ( $pl['description'] ?? '' );
$features = [];
if ( isset( $pl['features'] ) && is_array( $pl['features'] ) ) {
foreach ( $pl['features'] as $f ) {
if ( is_array( $f ) ) {
$title = (string) ( $f['title'] ?? ( $f['name'] ?? '' ) );
if ( '' !== $title ) {
$features[] = $title;
}
}
}
}
$is_featured = ! empty( $pl['is_featured'] );
if ( ! $is_featured && $plan_pct > $best_plan_pct ) {
$best_plan_pct = $plan_pct;
$best_plan_idx = $idx;
}
$plans_out[] = [
'plan_name' => $plan_title,
'plan_id' => $plan_id,
'best_value' => $is_featured,
'site_tiers' => $site_tiers,
'terms' => $terms,
'desc' => $desc,
'features' => $features,
'has_trial' => $has_trial,
];
}
$any_featured = false;
foreach ( $plans_out as $p ) {
if ( ! empty( $p['best_value'] ) ) {
$any_featured = true;
break;
}
}
if ( ! $any_featured && $best_plan_idx >= 0 && isset( $plans_out[ $best_plan_idx ] ) ) {
$plans_out[ $best_plan_idx ]['best_value'] = true;
}
return [
'product' => $product,
'plans' => $plans_out,
];
}
/**
* Parses the provided content to extract and process child shortcodes, generating structured data for plans.
*
* @param string $content Content string to parse for child shortcodes.
* @return array An array of parsed plan details, including metadata, features, site tiers, terms, and other attributes.
*/
protected function parse_child_shortcodes( $content ) {
if ( '' === trim( $content ) ) {
return [];
}
$plans = [];
$pattern = get_shortcode_regex( [ 'go_plan_column' ] );
if ( preg_match_all( '/' . $pattern . '/s', $content, $matches, PREG_SET_ORDER ) ) {
foreach ( $matches as $m ) {
// $m[3] is the attributes string, $m[5] is the inner content (unused here)
$atts_raw = $m[3] ?? '';
$atts = shortcode_parse_atts( $atts_raw );
if ( ! is_array( $atts ) ) {
$atts = [];
}
// Normalize keys to lowercase to make attributes case-insensitive.
$norm = [];
foreach ( $atts as $k => $v ) {
$norm[ strtolower( (string) $k ) ] = is_scalar( $v ) ? (string) $v : '';
}
$plan_name = $norm['plan_name'] ?? '';
$plan_id = $norm['plan_id'] ?? '';
$site_tiers_label = $norm['site_tiers_label'] ?? ( $norm['site_tierslabel'] ?? '' );
$site_tiers_vals = $norm['site_tiers'] ?? ( $norm['site_tiersvalue'] ?? '' );
$monthly = $norm['monthly'] ?? '';
$annual = $norm['annual'] ?? '';
$plan_desc = $norm['plan_desc'] ?? '';
$plan_features = $norm['plan_features'] ?? '';
$best_value_raw = $norm['best_value'] ?? '';
$has_trial_raw = $norm['has_trial'] ?? 'true';
$plan_coupon = $norm['coupon'] ?? '';
$plan_discount = $norm['discount'] ?? '';
$labels = array_map( 'trim', $this->parse_pipe_list( $site_tiers_label ) );
$tiers = array_map( 'trim', $this->parse_pipe_list( $site_tiers_vals ) );
$monthly_a = array_map( 'trim', $this->parse_pipe_list( $monthly ) );
$annual_a = array_map( 'trim', $this->parse_pipe_list( $annual ) );
$features = $this->parse_pipe_list( $plan_features );
$site_tiers_map = [];
$count = max( count( $labels ), count( $tiers ) );
for ( $i = 0; $i < $count; $i++ ) {
$label = $labels[ $i ] ?? ( $tiers[ $i ] ?? (string) ( $i + 1 ) );
$val = $tiers[ $i ] ?? (string) ( $i + 1 );
$site_tiers_map[ $label ] = $val;
}
$terms = [];
$max_terms = max( count( $tiers ), count( $monthly_a ), count( $annual_a ) );
for ( $i = 0; $i < $max_terms; $i++ ) {
$site = isset( $tiers[ $i ] ) ? (string) $tiers[ $i ] : (string) ( $i + 1 );
$row = [];
if ( isset( $monthly_a[ $i ] ) && '' !== $monthly_a[ $i ] ) {
$row['Monthly'] = $monthly_a[ $i ];
}
if ( isset( $annual_a[ $i ] ) && '' !== $annual_a[ $i ] ) {
$row['Annual'] = $annual_a[ $i ];
}
if ( ! empty( $row ) ) {
$terms[ $site ] = $row;
}
}
$best_value = false;
if ( '' !== $best_value_raw ) {
$bv = strtolower( trim( $best_value_raw ) );
$best_value = in_array( $bv, [ '1', 'true', 'yes', 'on' ], true );
}
$has_trial = true;
if ( '' !== $has_trial_raw ) {
$ht = strtolower( trim( $has_trial_raw ) );
$has_trial = ! in_array( $ht, [ '0', 'false', 'no', 'off' ], true );
}
$plan = [
'plan_name' => (string) $plan_name,
'plan_id' => (string) $plan_id,
'best_value' => $best_value,
'site_tiers' => $site_tiers_map,
'terms' => $terms,
'desc' => (string) $plan_desc,
'features' => $features,
'has_trial' => $has_trial,
'coupon' => (string) $plan_coupon,
'discount' => (string) $plan_discount,
];
if ( '' !== $plan['plan_id'] || '' !== $plan['plan_name'] ) {
$plans[] = $plan;
}
}
}
return $plans;
}
// --- Rendering ---
/**
* Renders the parent pricing table with various configuration options.
*
* @param array $atts {
* Array of attributes for configuring the pricing table.
* - public_key (string): The public key used for Freemius integration.
* - product_name (string): The name of the product being showcased.
* - product_id (string): The unique identifier for the product.
* - freemius (string): Defines Freemius mode, options are '', 'manual', or 'automatic'.
* - buy_url (string): The URL used for purchasing the product when Freemius mode is empty.
* - trial_url (string): The URL for a trial option when Freemius mode is empty.
* - product_prefix (string): Prefix used to generate predictable button IDs.
* - currency (string): The pricing currency for automatic mode. Default is 'usd'.
* - cache_ttl (int): Cache duration (in seconds) for automatic mode API data. Default is 21600 (6 hours).
* - site_tiers_label (string): Optional override for site tier labels in automatic mode.
* - bearer_constant (string): The name of a constant storing the Freemius Bearer token for authentication.
* }.
* @param string|null $content Content passed to child shortcodes. Used in manual Freemius mode.
* @return string The generated HTML for the pricing table or an error message if configuration is invalid.
*/
public function render_parent( $atts, $content = null ) {
$a = shortcode_atts(
[
'public_key' => '',
'product_name' => '',
'product_id' => '',
'freemius' => '', // '', 'manual', 'automatic'
'buy_url' => '', // used when freemius is empty. requires full url including http(s)://
'trial_url' => '', // used when freemius is empty. requires full url including http(s)://
'product_prefix' => '', // used to generate predictable button IDs
// Automatic mode optional controls:
'currency' => 'usd', // pricing currency for automatic mode
'cache_ttl' => '21600', // seconds (6h) for automatic mode API cache
'site_tiers_label' => '', // optional global labels override for automatic mode
'bearer_constant' => '', // name of a defined() constant that stores the Freemius Bearer token
'coupon' => '', // comma-separated Freemius coupon IDs (automatic mode only)
'discount' => '', // manual/empty mode: "$10" or "15%" global discount
'redirect_url' => '', // redirect URL after purchase (skips confirmation dialog)
'show_annual_monthly' => 'yes',
],
$atts,
'gopricingtable'
);
$freemius_mode = strtolower( trim( (string) $a['freemius'] ) );
if ( in_array( $freemius_mode, [ 'manual', 'automatic' ], true ) ) {
wp_enqueue_script( 'freemius-checkout', 'https://checkout.freemius.com/js/v1/', [], null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
}
$auto_product_name = '';
$auto_public_key = '';
$currency = 'usd';
$coupon_meta = [