-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpercentagepricesetfield.php
More file actions
1167 lines (1078 loc) · 43.9 KB
/
Copy pathpercentagepricesetfield.php
File metadata and controls
1167 lines (1078 loc) · 43.9 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
require_once 'percentagepricesetfield.civix.php';
use CRM_Percentagepricesetfield_ExtensionUtil as E;
define('PERCENTAGEPRICESETFIELD_PLACEHOLDER_LABEL', 'ERROR: percentagepricesetfield_NFMbsQAQVpVZkamC (Hint: Is the Percentage Price Set Field extension enabled?)');
/**
* Implements hook_civicrm_copy().
*/
function percentagepricesetfield_civicrm_copy($objectName, &$object, $original_id = NULL) {
if (strtolower($objectName) == 'set') {
if (!$original_id) {
// If we don't know the original price set id, we cannot copy the
// Percentage Price Fields configurations. Therefore, alert the user and
// skip any further action.
CRM_Core_Session::setStatus(E::ts('If the new Price Set contains any Percentage Price Set Fields, they were not fully configured. Please double-check the configuration of any such fields in the new Price Set.'), 'Caution.', 'error');
return;
}
// Get all percentage fields in the source prices set:
$source_percentage_field_ids = _percentagepricesetfield_get_percentage_field_ids($original_id, FALSE);
foreach ($source_percentage_field_ids as $field_id) {
// Get the percentage price field values for this field.
$source_percentage_values = _percentagepricesetfield_get_settings($field_id, FALSE);
// Get the price field values for this field; we need its 'name' value.
$params = array(
'id' => $field_id,
);
CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $source_price_field_values);
// Now find the like-named checkbox field in the new price set. We need its ID.
$params = array(
'price_set_id' => $object->id,
'name' => $source_price_field_values['name'],
'html_type' => 'CheckBox',
);
CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $new_price_field_values);
// Use the source percentage values to mark the new field as a percentage field.
$source_percentage_values['field_id'] = $new_price_field_values['id'];
_percentagepricesetfield_create_field($source_percentage_values);
}
}
}
/**
* Implements hook_civicrm_buildAmount().
*/
function percentagepricesetfield_civicrm_buildAmount($pageType, &$form, &$amount) {
if (!empty($form->_priceSetId)) {
$field_ids = _percentagepricesetfield_get_percentage_field_ids($form->_priceSetId, TRUE);
if (empty($field_ids)) {
// This form doesn't use a priceset with percentage fields. Just return.
return;
}
$field_id = array_pop($field_ids);
if (!empty($form->_submitValues)) {
// If this form is being submitted, we'll adjust the line item label, if
// the price set contains a percentage field.
foreach ($amount[$field_id]['options'] as $option_id => &$option) {
// Apply percentage if "percentage" checkbox was checked.
if (!empty($form->_submitValues["price_{$field_id}"][$option_id])) {
$option['amount'] = _percentagepricesetfield_calculate_additional_amount($form);
$option['tax_amount'] = $option['amount'] * ($option['tax_rate'] / 100);
$percent = _percentagepricesetfield_get_percentage($form->_priceSetId);
$option['label'] = $percent . '%';
}
}
}
}
}
/**
* Implements hook_civicrm_buildForm().
*/
function percentagepricesetfield_civicrm_buildForm($formName, &$form) {
switch ($formName) {
case 'CRM_Price_Form_Field':
_percentagepricesetfield_buildForm_AdminPriceField($form);
break;
case 'CRM_Event_Form_ParticipantFeeSelection':
case 'CRM_Event_Form_Registration_Register':
case 'CRM_Contribute_Form_Contribution_Main':
case 'CRM_Contribute_Form_Contribution':
case 'CRM_Event_Form_Participant':
case 'CRM_Event_Form_Registration_AdditionalParticipant':
case 'CRM_Price_Form_Preview':
case 'CRM_Member_Form_Membership':
_percentagepricesetfield_buildForm_public_price_set_form($form);
break;
}
}
/**
* Implements hook_civicrm_postProcess().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postProcess
*/
function percentagepricesetfield_civicrm_postProcess($formName, &$form) {
if ($formName == 'CRM_Price_Form_Field') {
_percentagepricesetfield_postProcess_AdminPriceField($form);
}
}
/**
* Implements hook_civicrm_config().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
*/
function percentagepricesetfield_civicrm_config(&$config) {
_percentagepricesetfield_civix_civicrm_config($config);
}
/**
* Implements hook_civicrm_install().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
*/
function percentagepricesetfield_civicrm_install() {
_percentagepricesetfield_civix_civicrm_install();
}
/**
* Implements hook_civicrm_enable().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
*/
function percentagepricesetfield_civicrm_enable() {
_percentagepricesetfield_civix_civicrm_enable();
}
/**
* Implements hook_civicrm_alterContent().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterContent
*/
function percentagepricesetfield_civicrm_alterContent(&$content, $context, $tplName, &$object) {
if ($context !== 'form') {
return;
}
if (!in_array(
get_class($object),
[
'CRM_Price_Form_Field',
'CRM_Event_Form_ParticipantFeeSelection',
'CRM_Event_Form_Registration_Register',
'CRM_Contribute_Form_Contribution_Main',
'CRM_Contribute_Form_Contribution',
'CRM_Event_Form_Participant',
'CRM_Event_Form_Registration_AdditionalParticipant',
'CRM_Price_Form_Preview',
])
) {
return;
}
$args = func_get_args();
$args['_get'] = $_GET;
if ($func = call_user_func_array('_percentagepricesetfield_get_content_pricesetid_function', $args)) {
if (function_exists($func)) {
$price_set_id = call_user_func_array($func, $args);
}
}
if (!empty($price_set_id)) {
$allow_hide_and_force = _percentagepricesetfield_allow_hide_and_force($content, $context, $tplName, $object, $_GET);
$field_ids = _percentagepricesetfield_get_percentage_field_ids($price_set_id, TRUE);
if (empty($field_ids)) {
// No enabled percentage fields were found for this form. Nothing to do.
return;
}
$field_id = array_pop($field_ids);
// This checkbox field should have exactly one option. We need that option
// value because the checkbox element's "id" attribute will be
// "price_[field_id]_[field_value]".
$field_value = _percentagepricesetfield_get_field_value($field_id);
if (!$field_value_id = ($field_value['id'] ?? NULL)) {
return;
}
$formObject = $args[3];
$taxRate = $formObject->_priceSet['fields'][$field_id]['options'][$field_value_id]['tax_rate'];
// Insert our JavaScript code and variables.
$vars = array(
'percentage' => _percentagepricesetfield_get_percentage($price_set_id),
'tax_rate' => $taxRate,
'percentage_checkbox_id' => "price_{$field_id}_{$field_value_id}",
'hide_and_force' => (int) ($allow_hide_and_force && _percentagepricesetfield_get_setting_value($field_id, 'hide_and_force')),
'is_default' => _percentagepricesetfield_get_setting_value($field_id, 'is_default'),
'disable_payment_methods' => _percentagepricesetfield_get_setting_value($field_id, 'disable_payment_methods'),
'apply_to_taxes' => _percentagepricesetfield_get_setting_value($field_id, 'apply_to_taxes'),
'payment_processor_id' => ($object->_paymentProcessor['id'] ?? NULL),
);
$resource = CRM_Core_Resources::singleton();
$content .= '<script type="text/javascript">';
$content .= 'CRM.vars.percentagepricesetfield = ' . json_encode($vars) . ';';
$content .= file_get_contents($resource->getPath('com.joineryhq.percentagepricesetfield', 'js/public_price_set_form.js'));
$content .= '</script>';
}
}
/**
* Implements hook_civicrm_pageRun().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_pageRun
*/
function percentagepricesetfield_civicrm_pageRun(&$page) {
$page_name = $page->getVar('_name');
if ($page_name == 'CRM_Price_Page_Field') {
// Get a list of all percentage fields in this price set.
$price_set_id = $page->getVar('_sid');
$field_ids = _percentagepricesetfield_get_percentage_field_ids($price_set_id, FALSE);
// Adjust the template variables for each percentage field, to hide certain
// checkbox-related functionality which is irrelevant to percentage fields.
$tpl = CRM_Core_Smarty::singleton();
$tpl_vars = $tpl->getTemplateVars();
foreach ($field_ids as $field_id) {
if (array_key_exists('priceField', $tpl_vars) && array_key_exists($field_id, $tpl_vars['priceField'])
) {
// Avoid printing 'Edit Price Options' link.
$tpl_vars['priceField'][$field_id]['html_type'] = 'Text';
// Display an intelligible value in the Field Type column.
$tpl_vars['priceField'][$field_id]['html_type_display'] = 'Percentage';
}
}
$tpl->assign('priceField', $tpl_vars['priceField']);
}
elseif ($page_name == 'CRM_Event_Page_EventInfo') {
$resource = CRM_Core_Resources::singleton();
$resource->addScriptFile('com.joineryhq.percentagepricesetfield', 'js/public_event_info.js', 100, 'page-footer');
$vars = array(
'PERCENTAGEPRICESETFIELD_PLACEHOLDER_LABEL' => PERCENTAGEPRICESETFIELD_PLACEHOLDER_LABEL,
);
$resource->addVars('percentagepricesetfield', $vars);
}
}
/**
* Implements hook_civicrm_validateForm().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_validateForm
*/
function percentagepricesetfield_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
if ($formName == 'CRM_Price_Form_Field') {
// If the field is set as is_percentagepricesetfield,
// make sure there are no (enabled) others already in this fieldset.
if (!empty($fields['is_percentagepricesetfield'])) {
$field_ids = _percentagepricesetfield_get_percentage_field_ids($fields['sid']);
$fid = ($fields['fid'] ?? NULL);
while (($fid_key = array_search($fid, $field_ids)) !== FALSE) {
unset($field_ids[$fid_key]);
}
if (!empty($field_ids)) {
$errors['is_percentagepricesetfield'] = E::ts('This price set already has a percentage field. Please disable or delete that field before creating a new one.');
}
// Ensure financial_type_id.
if (!CRM_Utils_Array::value('percentagepricesetfield_financial_type_id', $fields)) {
$errors['financial_type_id'] = E::ts('Financial Type is required.');
}
}
}
}
/**
* Get the field_ids of all percentage fields in the given price set.
*
* @param int $price_set_id The ID of the price set to check; if string 'ALL',
* return all percentage price fields regardlesss of price_set.
* @param bool $limit_enabled If TRUE, return IDs of only enabled percentage
* fields; otherwise return IDs of all percentage fields.
* @return Array of field ids
*/
function _percentagepricesetfield_get_percentage_field_ids($price_set_id, $limit_enabled = TRUE) {
// Static cache.
static $ret = array();
$key = serialize(func_get_args());
if (!array_key_exists($price_set_id, $ret)) {
$field_ids = array();
$dao = new CRM_Price_DAO_PriceField();
if ($price_set_id != 'ALL') {
$dao->price_set_id = $price_set_id;
}
if ($limit_enabled) {
$dao->is_active = 1;
}
$dao->find();
$ids = array();
while ($dao->fetch()) {
$ids[] = (int) $dao->id;
}
unset($dao);
if (!empty($ids)) {
$query = "
SELECT field_id
FROM civicrm_percentagepricesetfield
WHERE field_id IN (" . implode(',', $ids) . ")
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$field_ids[] = $dao->field_id;
}
}
$ret[$key] = $field_ids;
}
return $ret[$key];
}
/**
* Calculate the additional amount to add, based on selected price options and
* the percentage field.
*
* @param Object $form The form being processed.
* @return Float The additional amount to be added.
*/
function _percentagepricesetfield_calculate_additional_amount($form) {
// No need to run this twice, though buildAmount is sometimes called more than
// once per request.
static $additional_amount;
if (!isset($additional_amount)) {
$additional_amount = 0;
if ($form->_priceSetId) {
$field_ids = _percentagepricesetfield_get_percentage_field_ids($form->_priceSetId);
$field_id = array_shift($field_ids);
$base_total = 0;
$line_items = array();
$params = $form->_submitValues;
if (!empty($form->_values['fee'])) {
$fields = $form->_values['fee'];
}
else {
$fields = $form->_priceSet['fields'];
}
unset($fields[$field_id]);
CRM_Price_BAO_PriceSet::processAmount($fields, $params, $line_items);
// Calculate differently depending on "apply to taxes" setting.
if (_percentagepricesetfield_get_setting_value($field_id, 'apply_to_taxes')) {
// $params['amount'] holds the total with any taxes, so we can just use it.
$base_total = $params['amount'];
}
else {
$base_total = 0;
// If we're not configured to apply the percentage to taxes, then apply it
// to each line item individually.
foreach ($line_items as $line_item) {
if ($line_item['price_field_id'] != $field_id) {
$base_total += $line_item['line_total'];
}
}
}
$percentage = _percentagepricesetfield_get_percentage($form->_priceSetId);
$additional_amount = round(($base_total * $percentage / 100), 2);
}
}
return $additional_amount;
}
/**
* Get the specified value in the stored configuration settings for a given
* percentage field, incorporating any globally overriding settings.
*
* @param int $field_id The ID of the percentage field.
* @param string $setting_name The name of the value to retrieve.
* @return Bool
*/
function _percentagepricesetfield_get_setting_value($field_id, $setting_name) {
$value = _percentagepricesetfield_get_setting_value_override($setting_name);
if ($value === NULL) {
$values = _percentagepricesetfield_get_settings($field_id);
$value = ($values[$setting_name] ?? NULL);
if ($value === NULL) {
$field_value = _percentagepricesetfield_get_field_value($field_id);
$value = ($field_value[$setting_name] ?? NULL);
}
}
return $value;
}
/**
* Get the appropriate value from global settings for the given field setting
* name. Return any value that should override the given field setting, or NULL
* if there is no such value.
*
* @param string $setting_name
*/
function _percentagepricesetfield_get_setting_value_override($setting_name) {
switch ($setting_name) {
case 'hide_and_force':
// TODO: Refactor to something more re-usable.
$result = civicrm_api3(
'Setting', 'get', array(
'sequential' => 1,
'return' => array("percentagepricesetfield_hide_and_force_all"),
)
);
$value = ($result['values'][0]['percentagepricesetfield_hide_and_force_all'] ?? NULL);
if ((bool) $value) {
return $value;
}
else {
return NULL;
}
break;
}
}
/**
* Get the stored configuration settings for a given percentage field.
*
* @param Integer $field_id The ID of the percentage field.
* @return Array of setting values.
*/
function _percentagepricesetfield_get_settings($field_id, bool $preProcess = TRUE) {
static $ret = array();
if (!array_key_exists($field_id, $ret)) {
$values = array();
if (!$field_id) {
return $values;
}
$valid_fields = _percentagepricesetfield_get_valid_fields();
$field_names = array_keys($valid_fields);
$fields = implode(',', $field_names);
$query = "
SELECT $fields
FROM civicrm_percentagepricesetfield
WHERE
field_id = %1
";
$params = array(
1 => array($field_id, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
$dao->fetch();
if ($dao->N) {
foreach ($field_names as $field_name) {
if ($preProcess) {
$values[$field_name] = _percentagepricesetfield_preprocess_saved_value($field_name, $dao->$field_name);
}
else {
$values[$field_name] = $dao->$field_name;
}
}
}
$ret[$field_id] = $values;
}
return $ret[$field_id];
}
/**
* Get the configured percentage setting for the percentage field in a
* given price set.
*
* @param Integer $price_set_id
* @return Float
*/
function _percentagepricesetfield_get_percentage($price_set_id) {
$field_ids = _percentagepricesetfield_get_percentage_field_ids($price_set_id);
$field_id = array_shift($field_ids);
$values = _percentagepricesetfield_get_settings($field_id);
return $values['percentage'];
}
/**
* buildForm hook handler for public-facing forms containing price set fields
* (e.g., event registration forms, contribution pages)
*
* @param object $form
*/
function _percentagepricesetfield_buildForm_public_price_set_form($form) {
$field_id = _percentagepricesetfield_get_form_percentage_field_id($form);
if ($field_id) {
$field = & $form->_elements[$form->_elementIndex["price_{$field_id}"]];
// Get a reference to the last element in the $field->_elements array.
end($field->_elements);
$element = & $field->_elements[key($field->_elements)];
// Use the field label as the label for this checkbox element.
$element->_text = $field->_label;
// Set this checkbox's "price" to 0. This allows us to avoid having
// this checkbox affect that calculation, and we'll use our own
// JavaScript to adjust the total based on the percentage. CiviCRM
// uses a custom format for this attribute, parsing it later in
// JavaScript to auto-calculate the total (see
// CRM/Price/Form/Calculate.tpl).
// e.g., ["30","20||"]: change "20" to "0".
// e.g., [30,"20||"]: change "20" to "0".
// (Note: newer civicrm versions omit the double-quotes around the first value e.g. 30)
$priceAttribute = $element->_attributes['price'];
$newPriceAttribute = preg_replace('/(\["?[^"]+"?,")[^|]+(\|.+)$/', '${1}0${2}', $priceAttribute);
$element->_attributes['price'] = $newPriceAttribute;
$element_id = $field->_name . '_' . $element->_attributes['id'];
// Remove this field's label (we copied it to the checkbox itself a few lines
// above).
$field->_label = '';
// If disable-per-payment-method, we must ignore any "Required" setting for
// the percentage field.
// (https://github.com/twomice/com.joineryhq.percentagepricesetfield/issues/19)
if (!empty(_percentagepricesetfield_get_setting_value($field_id, 'disable_payment_methods'))) {
foreach ($form->_required as $id => $required_field) {
if ($required_field == "price_{$field_id}") {
unset($form->_required[$id]);
}
}
}
}
}
/**
* For a given form, get the HTML "id" attribute for the percentage price field,
* if any.
*
* @param Object $form An object extending CRM_Core_Form
* @return String "id" attribute, if any; otherwise FALSE.
*/
function _percentagepricesetfield_get_form_percentage_field_id($form) {
$formName = get_class($form);
$priceSetId = NULL;
if ($formName == 'CRM_Price_Form_Preview') {
// For the preview form, we have to get it from $_REQUEST.
$priceSetId = CRM_Utils_Request::retrieve('sid', 'Int');
}
else {
// For other forms, it's a property of the form.
$priceSetId = $form->_priceSetId;
}
if (!empty($priceSetId)) {
$field_ids = _percentagepricesetfield_get_percentage_field_ids($priceSetId, TRUE);
$field_id = array_shift($field_ids);
if ($field_id) {
if (array_key_exists("price_{$field_id}", $form->_elementIndex)) {
return $field_id;
}
}
}
return FALSE;
}
/**
* buildForm hook handler for /civicrm/admin/price/field.
*
* @param <type> $form
*/
function _percentagepricesetfield_buildForm_AdminPriceField(&$form) {
// If the form has been submitted to create a new percentage field, we'll want
// to massage the submitted values; we don't do this in hook_civicrm_postProcess()
// because that runs after the form is processed, whereas we need to modify
// these values before the form is processed.
if ($form->_flagSubmitted && !$form->_submitValues['fid'] && $form->_submitValues['html_type'] == 'CheckBox' && $form->_submitValues['is_percentagepricesetfield']
) {
// Auto-create the list of options to have a single option. This is necessary
// because the form validation for a new checkbox requires options to be
// defined.
$form->_submitValues['option_label'] = array(1 => '_');
$form->_submitValues['option_amount'] = array(1 => 1);
$form->_submitValues['option_financial_type_id'] = array(1 => $form->_submitValues['percentagepricesetfield_financial_type_id']);
$form->_submitValues['option_status'] = array(1 => 1);
for ($i = 2; $i <= 15; $i++) {
$form->_submitValues['option_label'][$i] = '';
$form->_submitValues['option_amount'][$i] = '';
$form->_submitValues['option_financial_type_id'][$i] = '';
$form->_submitValues['option_status'][$i] = '';
}
// Never display amount for a percentage field.
$form->_submitValues['is_display_amounts'] = 0;
}
// On submit, whether new or existing field:
if ($form->_flagSubmitted && $form->_submitValues['html_type'] == 'CheckBox' && $form->_submitValues['is_percentagepricesetfield']) {
// Remove the Required setting if the "disable for payment methods" is in use.
if ($form->_submitValues['percentagepricesetfield_disable_payment_methods'] ?? FALSE) {
$form->_submitValues['is_required'] = 0;
}
}
// Add our custom JavaScript file.
$resource = CRM_Core_Resources::singleton();
$resource->addScriptFile('com.joineryhq.percentagepricesetfield', 'js/admin_price_field.js', 100, 'page-footer');
$resource->addStyleFile('com.joineryhq.percentagepricesetfield', 'css/admin_price_field.css', 100, 'page-header');
// Define an array to hold field descriptions.
$descriptions = array();
// Add our own fields to this form, to handle percentage fields
$form->addElement('checkbox', 'is_percentagepricesetfield', E::ts('Field calculates "Automatic Additional Percentage"'));
$form->addElement('text', 'percentagepricesetfield_', E::ts('Short label for line item'));
$form->addElement('text', 'percentagepricesetfield_percentage', E::ts('Percentage'));
$form->addElement('checkbox', 'percentagepricesetfield_apply_to_taxes', E::ts('Apply percentage to tax amounts'));
$hide_and_force_element = $form->addElement('checkbox', 'percentagepricesetfield_hide_and_force', E::ts('Hide checkbox and force to "yes"'));
$descriptions['percentagepricesetfield_hide_and_force'] = E::ts('This option will force the additional percentage to be applied, and hide the check box, in front-end forms. (Additional percentage is always an option in back-office forms.)');
$is_default_element = $form->addElement('checkbox', 'percentagepricesetfield_is_default', E::ts('Checked by default'));
$descriptions['percentagepricesetfield_is_default'] = E::ts('Cause the check-box to be checked by default? This option is automatically selected if the above "Hide and force" option is selected.');
// Support global "hide and force" config option; if it's TRUE, then tell JS
// to freeze this field, and adjust its description.
// NOTE ON FREEZING HIDE-AND-FORCE: We don't use
// $element->freeze() because it will actually prevent the element from
// appearing in the DOM, and that will break javascript that relies on the
// field name (maybe it doesn't have to rely on the field name, but doing so
// covers a variety of edge cases that can't be handled with, e.g., id or
// label "for" attribute, as in the case of checkboxes/radios.)
$hide_and_force_element_freeze = FALSE;
if (_percentagepricesetfield_get_setting_value_override('hide_and_force')) {
$hide_and_force_element_freeze = TRUE;
$descriptions['percentagepricesetfield_hide_and_force'] = E::ts(
'<strong>This setting overridden by the site-wide configuration at <a href="%1">%2</a>.</strong> ', array(
1 => CRM_Utils_System::url('civicrm/admin/percentagepricesetfield/settings', 'reset=1'),
2 => E::ts('Percentage Price Set Field: Settings'),
'domain' => 'org.joineryhq.percentagepricesetfield',
)
) . $descriptions['percentagepricesetfield_hide_and_force'];
}
// Create a group of "disable for payment processors" with one checkbox per
// payment processor, plus "pay later"
$payment_method_checkboxes = array(
$form->createElement('checkbox', '0', 0, ' ' . E::ts('Pay later (check)')),
);
$result = civicrm_api3(
'PaymentProcessor', 'get', array(
'sequential' => 1,
'is_test' => 0,
'return' => array("name"),
'options' => array('sort' => "name"),
)
);
foreach ($result['values'] as $value) {
$payment_method_checkboxes[] = $form->createElement('checkbox', $value['id'], $value['id'], ' ' . $value['name']);
}
$form->addGroup($payment_method_checkboxes, 'percentagepricesetfield_disable_payment_methods', E::ts('Disable for payment methods'), '<br />');
$descriptions['percentagepricesetfield_disable_payment_methods'] = E::ts('Additional percentage option will be forced to "no" in front-end forms submitted with the selected payment method(s). (Additional percentage is always an option in back-office forms.)');
// Assign bhfe fields to the template.
$tpl = CRM_Core_Smarty::singleton();
$bhfe = $tpl->getTemplateVars('beginHookFormElements');
if (!$bhfe) {
$bhfe = array();
}
$bhfe[] = 'is_percentagepricesetfield';
$bhfe[] = 'percentagepricesetfield_percentage';
$bhfe[] = 'percentagepricesetfield_apply_to_taxes';
$bhfe[] = 'percentagepricesetfield_hide_and_force';
$bhfe[] = 'percentagepricesetfield_is_default';
$bhfe[] = 'percentagepricesetfield_disable_payment_methods';
$form->assign('beginHookFormElements', $bhfe);
// Set default values for our fields.
_percentagepricesetfield_setDefaults_adminPriceField($form);
// Pass some of these values to JavaScript.
$vars = array();
$vars['descriptions'] = $descriptions;
$vars['bhfe_fields'] = $bhfe;
$vars['hide_and_force_element_freeze'] = $hide_and_force_element_freeze;
$field_id = $form->getVar('_fid');
if ($field_id) {
$values = _percentagepricesetfield_get_settings($field_id);
$vars['values'] = $values;
}
$resource->addVars('percentagepricesetfield', $vars);
}
/**
* Set default values for percentage-field-related values on the given form.
*/
function _percentagepricesetfield_setDefaults_adminPriceField(&$form) {
$price_set_id = $form->getVar('_sid');
$field_id = $form->getVar('_fid');
$percentage_field_ids = _percentagepricesetfield_get_percentage_field_ids($price_set_id, FALSE);
if (!$field_id || in_array($field_id, $percentage_field_ids)) {
$defaults = array();
if (!$field_id) {
$defaults['percentagepricesetfield_apply_to_taxes'] = 1;
}
$values = _percentagepricesetfield_get_settings($field_id);
if (!empty($values)) {
$defaults['is_percentagepricesetfield'] = 1;
foreach ($values as $name => $value) {
$defaults['percentagepricesetfield_' . $name] = $value;
}
// The is_default property is stored in the price field option, not in the
// percentagepricesetfield table, so we have to fetch it specifically.
$defaults['percentagepricesetfield_is_default'] = _percentagepricesetfield_get_setting_value($field_id, 'is_default');
}
$form->setDefaults($defaults);
}
}
/**
* Ensure that price options are correct for a given set of percentage price
* field values.
*/
function _percentagepricesetfield_rectify_price_options($field_values) {
$field_id = $field_values['field_id'];
// Find all existing price field values for this field.
try {
$price_options = civicrm_api3(
'price_field_value', 'get', array(
'price_field_id' => $field_id,
'sequential' => 1,
)
);
}
catch (CRM_Core_Exception $e) {
$error = $e->getMessage();
CRM_Core_Error::fatal(ts('Percentage Price Set Field: fatal error (on line %1) while rectifying price options: %2', array(1 => __LINE__, 2 => $error)));
}
// Remove each price field value for this field.
foreach ($price_options['values'] as $value) {
try {
civicrm_api3(
'price_field_value', 'delete', array(
'id' => $value['id'],
)
);
}
catch (CRM_Core_Exception $e) {
$error = $e->getMessage();
CRM_Core_Error::fatal(ts('Percentage Price Set Field: fatal error (on line %1) while rectifying price options: %2', array(1 => __LINE__ . "|{$value['id']}", 2 => $error)));
}
}
// Create a single correct price_field_value entity for this price field.
try {
civicrm_api3(
'price_field_value', 'create', array(
'price_field_id' => $field_id,
'name' => '_',
'label' => PERCENTAGEPRICESETFIELD_PLACEHOLDER_LABEL,
'amount' => '1',
'financial_type_id' => $field_values['financial_type_id'],
'is_default' => $field_values['is_default'],
)
);
}
catch (CRM_Core_Exception $e) {
$error = $e->getMessage();
CRM_Core_Error::fatal(ts('Percentage Price Set Field: fatal error (on line %1) while rectifying price options: %2', array(1 => __LINE__, 2 => $error)));
}
}
/**
* postProcess handler for /civicrm/admin/price/field.
*/
function _percentagepricesetfield_postProcess_AdminPriceField($form) {
$values = $form->_submitValues;
$price_set_id = $values['sid'];
$field_id = $values['fid'];
if (array_key_exists('is_percentagepricesetfield', $values) && $values['is_percentagepricesetfield']) {
$field_values = array(
'percentage' => (float) $values['percentagepricesetfield_percentage'],
'financial_type_id' => (int) $values['percentagepricesetfield_financial_type_id'],
'apply_to_taxes' => (int) !empty($values['percentagepricesetfield_apply_to_taxes']),
'hide_and_force' => (int) !empty($values['percentagepricesetfield_hide_and_force']),
'is_default' => (int) !empty($values['percentagepricesetfield_is_default']),
'disable_payment_methods' => (
!empty($values['percentagepricesetfield_disable_payment_methods']) ?
CRM_Utils_Array::implodePadded(array_keys($values['percentagepricesetfield_disable_payment_methods'])) :
''
),
'field_id' => $field_id,
);
if ($field_id) {
// If the $field_id is known, then it's an existing field. Update it.
_percentagepricesetfield_update_field($field_values);
}
else {
// Otherwise, it's just been created. Find it by price_set_id and label.
// (This works only because CiviCRM enforces a unique label-per-price-set
// limitation.)
$bao = new CRM_Price_BAO_PriceField();
$bao->price_set_id = $price_set_id;
$bao->label = $values['label'];
$bao->find();
$bao->fetch();
$field_values['field_id'] = $bao->id;
_percentagepricesetfield_create_field($field_values);
}
_percentagepricesetfield_rectify_price_options($field_values);
}
else {
// If it's not marked as a percentage field...
if ($field_id) {
// ... and if it's not a newly created field,
// then make sure it's not recorded as a percentage field.
_percentagepricesetfield_remove_field_percentage($field_id);
}
}
}
/**
* Get a list of available data fields, each with its correct data type
*
*/
function _percentagepricesetfield_get_valid_fields() {
// Define fields with valid data types (as in CRM_Utils_Type::validate()).
$valid_fields = array(
'field_id' => 'Integer',
'percentage' => 'Float',
'financial_type_id' => 'Integer',
'apply_to_taxes' => 'Boolean',
'hide_and_force' => 'Boolean',
'disable_payment_methods' => 'String',
);
return $valid_fields;
}
/**
* Create a record of a given percentage field, using the provided values.
*
* @param array $field_values An array of values with keys matching those in
* _percentagepricesetfield_get_valid_fields().
*/
function _percentagepricesetfield_create_field($field_values) {
$valid_fields = _percentagepricesetfield_get_valid_fields();
$fields = $values = $params = array();
$param_key = 1;
foreach ($valid_fields as $valid_field => $data_type) {
if (array_key_exists($valid_field, $field_values)) {
$fields[] = $valid_field;
$values[] = "%{$param_key}";
$params[$param_key] = array($field_values[$valid_field], $data_type);
$param_key++;
}
}
$query = "
INSERT INTO `civicrm_percentagepricesetfield` (" . implode(',', $fields) . ")
VALUES (" . implode(',', $values) . ")
";
CRM_Core_DAO::executeQuery($query, $params);
}
/**
* Remove "percentage field" behavior from a given priceset field.
*
* @param int $field_id The field_id of the given priceset field.
*/
function _percentagepricesetfield_remove_field_percentage($field_id) {
$query = "
DELETE FROM `civicrm_percentagepricesetfield`
WHERE field_id = %1
";
$params = array(
1 => array($field_id, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
}
/**
* Update a record of a given percentage field, using the provided values.
*
* @param array $field_values An array of values with keys matching those in
* _percentagepricesetfield_get_valid_fields().
*/
function _percentagepricesetfield_update_field($field_values) {
$field_id = $field_values['field_id'];
// First ensure a field exists:
$query = "
INSERT IGNORE INTO `civicrm_percentagepricesetfield` (field_id) values (%1)
";
$params = array(
1 => array($field_id, 'Integer'),
);
CRM_Core_DAO::executeQuery($query, $params);
// Now update the record with relevant values.
$valid_fields = _percentagepricesetfield_get_valid_fields();
$updates = $params = array();
$param_key = 1;
unset($field_values['field_id']);
foreach ($valid_fields as $valid_field => $data_type) {
if (array_key_exists($valid_field, $field_values)) {
$updates[] = "$valid_field = %{$param_key}";
$params[$param_key] = array($field_values[$valid_field], $data_type);
$param_key++;
}
}
$params[$param_key] = array($field_id, 'Integer');
$query = "
UPDATE `civicrm_percentagepricesetfield` SET " . implode(',', $updates) . "
WHERE field_id = %{$param_key}
";
CRM_Core_DAO::executeQuery($query, $params);
}
/**
* Determine the correct callback function to call in order to retrieve the
* price set ID of the relevant percentage price field.
*
* @param string $content As in first argument to hook_civicrm_alterContent()
* @param string $context As in second argument to hook_civicrm_alterContent()
* @param string $tplName As in third argument to hook_civicrm_alterContent()
* @param object $object As in fourth argument to hook_civicrm_alterContent()
* @param array $_get Contents of $_GET.
*
* @return String The appropriate callback function name.
*/
function _percentagepricesetfield_get_content_pricesetid_function($content, $context, $tplName, $object, $_get) {
$url_path = implode('/', $object->urlPath);
if (
$context == 'page'
&& !empty($_get['priceSetId'])
&& CRM_Utils_Array::value('snippet', $_get) == 4
&& ($url_path == 'civicrm/contact/view/contribution' || $url_path == 'civicrm/contribute/add')
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_contribution_backoffice';
}
if ($context == 'page' && $url_path == 'civicrm/contact/view/participant' && CRM_Utils_Array::value('snippet', $_get) == 4
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_event_backoffice';
}
if ($context == 'form' && $url_path == 'civicrm/event/participant/feeselection' && CRM_Utils_Array::value('snippet', $_get) == 'json'
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_event_backoffice_edit';
}
if ($context == 'form' && !empty($object->_priceSetId) && $url_path == 'civicrm/contribute/transact'
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_contribution_public';
}
if ($context == 'form' && !empty($object->_priceSetId) && $url_path == 'civicrm/event/register'
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_event_public';
}
if ($context == 'page' && $url_path == 'civicrm/admin/price' && CRM_Utils_Array::value('sid', $_get)
) {
return '_percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_preview';
}
}
/**
* Callback function to retrieve price set ID for a price set preview.
* form.
*
* @param string $content As in first argument to hook_civicrm_alterContent()
* @param string $context As in second argument to hook_civicrm_alterContent()
* @param string $tplName As in third argument to hook_civicrm_alterContent()
* @param object $object As in fourth argument to hook_civicrm_alterContent()
* @param array $_get Contents of $_GET.
*
* @return String The price set ID, if any; otherwise NULL.
*/
function _percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_preview($content, $context, $tplName, $object, $_get) {
return ($_get['sid'] ?? NULL);
}
/**
* Callback function to retrieve price set ID for a back-office contribution
* form.
*
* @param string $content As in first argument to hook_civicrm_alterContent()
* @param string $context As in second argument to hook_civicrm_alterContent()
* @param string $tplName As in third argument to hook_civicrm_alterContent()
* @param object $object As in fourth argument to hook_civicrm_alterContent()
* @param array $_get Contents of $_GET.
*
* @return String The price set ID, if any; otherwise NULL.
*/
function _percentagepricesetfield_civicrm_alterContent_get_pricesetid_for_contribution_backoffice($content, $context, $tplName, $object, $_get) {
return ($_get['priceSetId'] ?? NULL);
}
/**
* Callback function to retrieve price set ID for a public-facing contribution
* form.
*
* @param string $content As in first argument to hook_civicrm_alterContent()
* @param string $context As in second argument to hook_civicrm_alterContent()
* @param string $tplName As in third argument to hook_civicrm_alterContent()
* @param object $object As in fourth argument to hook_civicrm_alterContent()
* @param array $_get Contents of $_GET.
*
* @return String The price set ID, if any; otherwise NULL.
*/