-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathForm.php
2549 lines (2313 loc) · 82.2 KB
/
Form.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
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This is our base form. It is part of the Form/Controller/StateMachine
* trifecta. Each form is associated with a specific state in the state
* machine. Each form can also operate in various modes
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
require_once 'HTML/QuickForm/Page.php';
/**
* Class CRM_Core_Form
*/
class CRM_Core_Form extends HTML_QuickForm_Page {
/**
* The state object that this form belongs to
* @var object
*/
protected $_state;
/**
* The name of this form
* @var string
*/
protected $_name;
/**
* The title of this form
* @var string
*/
protected $_title = NULL;
/**
* The default values for the form.
*
* @var array
*/
public $_defaults = [];
/**
* (QUASI-PROTECTED) The options passed into this form
*
* This field should marked `protected` and is not generally
* intended for external callers, but some edge-cases do use it.
*
* @var mixed
*/
public $_options = NULL;
/**
* (QUASI-PROTECTED) The mode of operation for this form
*
* This field should marked `protected` and is not generally
* intended for external callers, but some edge-cases do use it.
*
* @var int
*/
public $_action;
/**
* Available payment processors.
*
* As part of trying to consolidate various payment pages we store processors here & have functions
* at this level to manage them.
*
* @var array
* An array of payment processor details with objects loaded in the 'object' field.
*/
protected $_paymentProcessors;
/**
* Available payment processors (IDS).
*
* As part of trying to consolidate various payment pages we store processors here & have functions
* at this level to manage them. An alternative would be to have a separate Form that is inherited
* by all forms that allow payment processing.
*
* @var array
* An array of the IDS available on this form.
*/
public $_paymentProcessorIDs;
/**
* Default or selected processor id.
*
* As part of trying to consolidate various payment pages we store processors here & have functions
* at this level to manage them. An alternative would be to have a separate Form that is inherited
* by all forms that allow payment processing.
*
* @var int
*/
protected $_paymentProcessorID;
/**
* Is pay later enabled for the form.
*
* As part of trying to consolidate various payment pages we store processors here & have functions
* at this level to manage them. An alternative would be to have a separate Form that is inherited
* by all forms that allow payment processing.
*
* @var int
*/
protected $_is_pay_later_enabled;
/**
* The renderer used for this form
*
* @var object
*/
protected $_renderer;
/**
* An array to hold a list of datefields on the form
* so that they can be converted to ISO in a consistent manner
*
* @var array
*
* e.g on a form declare $_dateFields = array(
* 'receive_date' => array('default' => 'now'),
* );
* then in postProcess call $this->convertDateFieldsToMySQL($formValues)
* to have the time field re-incorporated into the field & 'now' set if
* no value has been passed in
*/
protected $_dateFields = [];
/**
* Cache the smarty template for efficiency reasons
*
* @var CRM_Core_Smarty
*/
static protected $_template;
/**
* Indicate if this form should warn users of unsaved changes
* @var bool
*/
protected $unsavedChangesWarn;
/**
* What to return to the client if in ajax mode (snippet=json)
*
* @var array
*/
public $ajaxResponse = [];
/**
* Url path used to reach this page
*
* @var array
*/
public $urlPath = [];
/**
* Context of the form being loaded.
*
* 'event' or null
*
* @var string
*/
protected $context;
/**
* @var bool
*/
public $submitOnce = FALSE;
/**
* @return string
*/
public function getContext() {
return $this->context;
}
/**
* Set context variable.
*/
public function setContext() {
$this->context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
}
/**
* @var CRM_Core_Controller
*/
public $controller;
/**
* Constants for attributes for various form elements
* attempt to standardize on the number of variations that we
* use of the below form elements
*
* @var const string
*/
const ATTR_SPACING = ' ';
/**
* All checkboxes are defined with a common prefix. This allows us to
* have the same javascript to check / clear all the checkboxes etc
* If u have multiple groups of checkboxes, you will need to give them different
* ids to avoid potential name collision
*
* @var string|int
*/
const CB_PREFIX = 'mark_x_', CB_PREFIY = 'mark_y_', CB_PREFIZ = 'mark_z_', CB_PREFIX_LEN = 7;
/**
* @var array
* @internal to keep track of chain-select fields
*/
private $_chainSelectFields = [];
/**
* Extra input types we support via the "add" method
* @var array
*/
public static $html5Types = [
'number',
'url',
'email',
'color',
];
/**
* Constructor for the basic form page.
*
* We should not use QuickForm directly. This class provides a lot
* of default convenient functions, rules and buttons
*
* @param object $state
* State associated with this form.
* @param \const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
* @param string $method
* The type of http method used (GET/POST).
* @param string $name
* The name of the form if different from class name.
*
* @return \CRM_Core_Form
*/
public function __construct(
$state = NULL,
$action = CRM_Core_Action::NONE,
$method = 'post',
$name = NULL
) {
if ($name) {
$this->_name = $name;
}
else {
// CRM-15153 - FIXME this name translates to a DOM id and is not always unique!
$this->_name = CRM_Utils_String::getClassName(CRM_Utils_System::getClassName($this));
}
parent::__construct($this->_name, $method);
$this->_state =& $state;
if ($this->_state) {
$this->_state->setName($this->_name);
}
$this->_action = (int) $action;
$this->registerRules();
// let the constructor initialize this, should happen only once
if (!isset(self::$_template)) {
self::$_template = CRM_Core_Smarty::singleton();
}
// Workaround for CRM-15153 - give each form a reasonably unique css class
$this->addClass(CRM_Utils_System::getClassName($this));
$this->assign('snippet', CRM_Utils_Array::value('snippet', $_GET));
$this->setTranslatedFields();
}
/**
* Set translated fields.
*
* This function is called from the class constructor, allowing us to set
* fields on the class that can't be set as properties due to need for
* translation or other non-input specific handling.
*/
protected function setTranslatedFields() {}
/**
* Add one or more css classes to the form.
*
* @param string $className
*/
public function addClass($className) {
$classes = $this->getAttribute('class');
$this->setAttribute('class', ($classes ? "$classes " : '') . $className);
}
/**
* Register all the standard rules that most forms potentially use.
*/
public function registerRules() {
static $rules = [
'title',
'longTitle',
'variable',
'qfVariable',
'phone',
'integer',
'query',
'url',
'wikiURL',
'domain',
'numberOfDigit',
'date',
'currentDate',
'asciiFile',
'htmlFile',
'utf8File',
'objectExists',
'optionExists',
'postalCode',
'money',
'positiveInteger',
'xssString',
'fileExists',
'settingPath',
'autocomplete',
'validContact',
];
foreach ($rules as $rule) {
$this->registerRule($rule, 'callback', $rule, 'CRM_Utils_Rule');
}
}
/**
* Simple easy to use wrapper around addElement.
*
* Deal with simple validation rules.
*
* @param string $type
* @param string $name
* @param string $label
* @param string|array $attributes (options for select elements)
* @param bool $required
* @param array $extra
* (attributes for select elements).
* For datepicker elements this is consistent with the data
* from CRM_Utils_Date::getDatePickerExtra
*
* @return HTML_QuickForm_Element
* Could be an error object
*/
public function &add(
$type, $name, $label = '',
$attributes = '', $required = FALSE, $extra = NULL
) {
// Fudge some extra types that quickform doesn't support
$inputType = $type;
if ($type == 'wysiwyg' || in_array($type, self::$html5Types)) {
$attributes = ($attributes ? $attributes : []) + ['class' => ''];
$attributes['class'] = ltrim($attributes['class'] . " crm-form-$type");
if ($type == 'wysiwyg' && isset($attributes['preset'])) {
$attributes['data-preset'] = $attributes['preset'];
unset($attributes['preset']);
}
$type = $type == 'wysiwyg' ? 'textarea' : 'text';
}
// Like select but accepts rich array data (with nesting, colors, icons, etc) as option list.
if ($inputType == 'select2') {
$type = 'text';
$options = $attributes;
$attributes = ($extra ? $extra : []) + ['class' => ''];
$attributes['class'] = ltrim($attributes['class'] . " crm-select2 crm-form-select2");
$attributes['data-select-params'] = json_encode(['data' => $options, 'multiple' => !empty($attributes['multiple'])]);
unset($attributes['multiple']);
$extra = NULL;
}
// @see http://wiki.civicrm.org/confluence/display/CRMDOC/crmDatepicker
if ($type == 'datepicker') {
$attributes = ($attributes ? $attributes : []);
$attributes['data-crm-datepicker'] = json_encode((array) $extra);
if (!empty($attributes['aria-label']) || $label) {
$attributes['aria-label'] = CRM_Utils_Array::value('aria-label', $attributes, $label);
}
$type = "text";
}
if ($type == 'select' && is_array($extra)) {
// Normalize this property
if (!empty($extra['multiple'])) {
$extra['multiple'] = 'multiple';
}
else {
unset($extra['multiple']);
}
unset($extra['size'], $extra['maxlength']);
// Add placeholder option for select
if (isset($extra['placeholder'])) {
if ($extra['placeholder'] === TRUE) {
$extra['placeholder'] = $required ? ts('- select -') : ts('- none -');
}
if (($extra['placeholder'] || $extra['placeholder'] === '') && empty($extra['multiple']) && is_array($attributes) && !isset($attributes[''])) {
$attributes = ['' => $extra['placeholder']] + $attributes;
}
}
}
$element = $this->addElement($type, $name, $label, $attributes, $extra);
if (HTML_QuickForm::isError($element)) {
CRM_Core_Error::fatal(HTML_QuickForm::errorMessage($element));
}
if ($inputType == 'color') {
$this->addRule($name, ts('%1 must contain a color value e.g. #ffffff.', [1 => $label]), 'regex', '/#[0-9a-fA-F]{6}/');
}
if ($required) {
if ($type == 'file') {
$error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'uploadedfile');
}
else {
$error = $this->addRule($name, ts('%1 is a required field.', [1 => $label]), 'required');
}
if (HTML_QuickForm::isError($error)) {
CRM_Core_Error::fatal(HTML_QuickForm::errorMessage($element));
}
}
// Add context for the editing of option groups
if (isset($extra['option_context'])) {
$context = json_encode($extra['option_context']);
$element->setAttribute('data-option-edit-context', $context);
}
return $element;
}
/**
* Preprocess form.
*
* This is called before buildForm. Any pre-processing that
* needs to be done for buildForm should be done here.
*
* This is a virtual function and should be redefined if needed.
*/
public function preProcess() {
}
/**
* Called after the form is validated.
*
* Any processing of form state etc should be done in this function.
* Typically all processing associated with a form should be done
* here and relevant state should be stored in the session
*
* This is a virtual function and should be redefined if needed
*/
public function postProcess() {
}
/**
* Main process wrapper.
*
* Implemented so that we can call all the hook functions.
*
* @param bool $allowAjax
* FIXME: This feels kind of hackish, ideally we would take the json-related code from this function.
* and bury it deeper down in the controller
*/
public function mainProcess($allowAjax = TRUE) {
$this->postProcess();
$this->postProcessHook();
// Respond with JSON if in AJAX context (also support legacy value '6')
if ($allowAjax && !empty($_REQUEST['snippet']) && in_array($_REQUEST['snippet'], [
CRM_Core_Smarty::PRINT_JSON,
6,
])) {
$this->ajaxResponse['buttonName'] = str_replace('_qf_' . $this->getAttribute('id') . '_', '', $this->controller->getButtonName());
$this->ajaxResponse['action'] = $this->_action;
if (isset($this->_id) || isset($this->id)) {
$this->ajaxResponse['id'] = isset($this->id) ? $this->id : $this->_id;
}
CRM_Core_Page_AJAX::returnJsonResponse($this->ajaxResponse);
}
}
/**
* The postProcess hook is typically called by the framework.
*
* However in a few cases, the form exits or redirects early in which
* case it needs to call this function so other modules can do the needful
* Calling this function directly should be avoided if possible. In general a
* better way is to do setUserContext so the framework does the redirect
*/
public function postProcessHook() {
CRM_Utils_Hook::postProcess(get_class($this), $this);
}
/**
* This virtual function is used to build the form.
*
* It replaces the buildForm associated with QuickForm_Page. This allows us to put
* preProcess in front of the actual form building routine
*/
public function buildQuickForm() {
}
/**
* This virtual function is used to set the default values of various form elements.
*
* @return array|NULL
* reference to the array of default values
*/
public function setDefaultValues() {
return NULL;
}
/**
* This is a virtual function that adds group and global rules to the form.
*
* Keeping it distinct from the form to keep code small
* and localized in the form building code
*/
public function addRules() {
}
/**
* Performs the server side validation.
* @since 1.0
* @return bool
* true if no error found
* @throws HTML_QuickForm_Error
*/
public function validate() {
$error = parent::validate();
$this->validateChainSelectFields();
$hookErrors = [];
CRM_Utils_Hook::validateForm(
get_class($this),
$this->_submitValues,
$this->_submitFiles,
$this,
$hookErrors
);
if (!empty($hookErrors)) {
$this->_errors += $hookErrors;
}
return (0 == count($this->_errors));
}
/**
* Core function that builds the form.
*
* We redefine this function here and expect all CRM forms to build their form in the function
* buildQuickForm.
*/
public function buildForm() {
$this->_formBuilt = TRUE;
$this->preProcess();
CRM_Utils_Hook::preProcess(get_class($this), $this);
$this->assign('translatePermission', CRM_Core_Permission::check('translate CiviCRM'));
if (
$this->controller->_key &&
$this->controller->_generateQFKey
) {
$this->addElement('hidden', 'qfKey', $this->controller->_key);
$this->assign('qfKey', $this->controller->_key);
}
// _generateQFKey suppresses the qfKey generation on form snippets that
// are part of other forms, hence we use that to avoid adding entryURL
if ($this->controller->_generateQFKey && $this->controller->_entryURL) {
$this->addElement('hidden', 'entryURL', $this->controller->_entryURL);
}
$this->buildQuickForm();
$defaults = $this->setDefaultValues();
unset($defaults['qfKey']);
if (!empty($defaults)) {
$this->setDefaults($defaults);
}
// call the form hook
// also call the hook function so any modules can set their own custom defaults
// the user can do both the form and set default values with this hook
CRM_Utils_Hook::buildForm(get_class($this), $this);
$this->addRules();
//Set html data-attribute to enable warning user of unsaved changes
if ($this->unsavedChangesWarn === TRUE
|| (!isset($this->unsavedChangesWarn)
&& ($this->_action & CRM_Core_Action::ADD || $this->_action & CRM_Core_Action::UPDATE)
)
) {
$this->setAttribute('data-warn-changes', 'true');
}
if ($this->submitOnce) {
$this->setAttribute('data-submit-once', 'true');
}
}
/**
* Add default Next / Back buttons.
*
* @param array $params
* Array of associative arrays in the order in which the buttons should be
* displayed. The associate array has 3 fields: 'type', 'name' and 'isDefault'
* The base form class will define a bunch of static arrays for commonly used
* formats.
*/
public function addButtons($params) {
$prevnext = $spacing = [];
foreach ($params as $button) {
if (!empty($button['submitOnce'])) {
$this->submitOnce = TRUE;
}
$attrs = ['class' => 'crm-form-submit'] + (array) CRM_Utils_Array::value('js', $button);
if (!empty($button['class'])) {
$attrs['class'] .= ' ' . $button['class'];
}
if (!empty($button['isDefault'])) {
$attrs['class'] .= ' default';
}
if (in_array($button['type'], ['upload', 'next', 'submit', 'done', 'process', 'refresh'])) {
$attrs['class'] .= ' validate';
$defaultIcon = 'fa-check';
}
else {
$attrs['class'] .= ' cancel';
$defaultIcon = $button['type'] == 'back' ? 'fa-chevron-left' : 'fa-times';
}
if ($button['type'] === 'reset') {
$prevnext[] = $this->createElement($button['type'], 'reset', $button['name'], $attrs);
}
else {
if (!empty($button['subName'])) {
if ($button['subName'] == 'new') {
$defaultIcon = 'fa-plus-circle';
}
if ($button['subName'] == 'done') {
$defaultIcon = 'fa-check-circle';
}
if ($button['subName'] == 'next') {
$defaultIcon = 'fa-chevron-right';
}
}
if (in_array($button['type'], ['next', 'upload', 'done']) && $button['name'] === ts('Save')) {
$attrs['accesskey'] = 'S';
}
$icon = CRM_Utils_Array::value('icon', $button, $defaultIcon);
if ($icon) {
$attrs['crm-icon'] = $icon;
}
$buttonName = $this->getButtonName($button['type'], CRM_Utils_Array::value('subName', $button));
$prevnext[] = $this->createElement('submit', $buttonName, $button['name'], $attrs);
}
if (!empty($button['isDefault'])) {
$this->setDefaultAction($button['type']);
}
// if button type is upload, set the enctype
if ($button['type'] == 'upload') {
$this->updateAttributes(['enctype' => 'multipart/form-data']);
$this->setMaxFileSize();
}
// hack - addGroup uses an array to express variable spacing, read from the last element
$spacing[] = CRM_Utils_Array::value('spacing', $button, self::ATTR_SPACING);
}
$this->addGroup($prevnext, 'buttons', '', $spacing, FALSE);
}
/**
* Getter function for Name.
*
* @return string
*/
public function getName() {
return $this->_name;
}
/**
* Getter function for State.
*
* @return object
*/
public function &getState() {
return $this->_state;
}
/**
* Getter function for StateType.
*
* @return int
*/
public function getStateType() {
return $this->_state->getType();
}
/**
* Getter function for title.
*
* Should be over-ridden by derived class.
*
* @return string
*/
public function getTitle() {
return $this->_title ? $this->_title : ts('ERROR: Title is not Set');
}
/**
* Setter function for title.
*
* @param string $title
* The title of the form.
*/
public function setTitle($title) {
$this->_title = $title;
CRM_Utils_System::setTitle($title);
}
/**
* Assign billing type id to bltID.
*
* @throws CRM_Core_Exception
*/
public function assignBillingType() {
$this->_bltID = CRM_Core_BAO_LocationType::getBilling();
$this->set('bltID', $this->_bltID);
$this->assign('bltID', $this->_bltID);
}
/**
* @return int
*/
public function getPaymentProcessorID() {
return $this->_paymentProcessorID;
}
/**
* This if a front end form function for setting the payment processor.
*
* It would be good to sync it with the back-end function on abstractEditPayment & use one everywhere.
*
* @param bool $isPayLaterEnabled
*
* @throws \CRM_Core_Exception
*/
protected function assignPaymentProcessor($isPayLaterEnabled) {
$this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors(
[ucfirst($this->_mode) . 'Mode'],
$this->_paymentProcessorIDs
);
if ($isPayLaterEnabled) {
$this->_paymentProcessors[0] = CRM_Financial_BAO_PaymentProcessor::getPayment(0);
}
if (!empty($this->_paymentProcessors)) {
foreach ($this->_paymentProcessors as $paymentProcessorID => $paymentProcessorDetail) {
if (empty($this->_paymentProcessor) && $paymentProcessorDetail['is_default'] == 1 || (count($this->_paymentProcessors) == 1)
) {
$this->_paymentProcessor = $paymentProcessorDetail;
$this->assign('paymentProcessor', $this->_paymentProcessor);
// Setting this is a bit of a legacy overhang.
$this->_paymentObject = $paymentProcessorDetail['object'];
}
}
// It's not clear why we set this on the form.
$this->set('paymentProcessors', $this->_paymentProcessors);
}
else {
throw new CRM_Core_Exception(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
}
}
/**
* Format the fields in $this->_params for the payment processor.
*
* In order to pass fields to the payment processor in a consistent way we add some renamed
* parameters.
*
* @param array $fields
*
* @return array
*/
protected function formatParamsForPaymentProcessor($fields) {
$this->_params = $this->prepareParamsForPaymentProcessor($this->_params);
$fields = array_merge($fields, ['first_name' => 1, 'middle_name' => 1, 'last_name' => 1]);
return $fields;
}
/**
* Format the fields in $params for the payment processor.
*
* In order to pass fields to the payment processor in a consistent way we add some renamed
* parameters.
*
* @param array $params Payment processor params
*
* @return array $params
*/
protected function prepareParamsForPaymentProcessor($params) {
// also add location name to the array
$params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
$params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
// Add additional parameters that the payment processors are used to receiving.
if (!empty($params["billing_state_province_id-{$this->_bltID}"])) {
$params['state_province'] = $params["state_province-{$this->_bltID}"] = $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
}
if (!empty($params["billing_country_id-{$this->_bltID}"])) {
$params['country'] = $params["country-{$this->_bltID}"] = $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
}
list($hasAddressField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($params, $this->_bltID);
if ($hasAddressField) {
$params = array_merge($params, $addressParams);
}
// How does this relate to similar code in CRM_Contact_BAO_Contact::addBillingNameFieldsIfOtherwiseNotSet()?
$nameFields = ['first_name', 'middle_name', 'last_name'];
foreach ($nameFields as $name) {
if (array_key_exists("billing_$name", $params)) {
$params[$name] = $params["billing_{$name}"];
$params['preserveDBName'] = TRUE;
}
}
// For legacy reasons we set these creditcard expiry fields if present
if (isset($params['credit_card_exp_date'])) {
$params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
$params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
}
// Assign IP address parameter
$params['ip_address'] = CRM_Utils_System::ipAddress();
return $params;
}
/**
* Handle Payment Processor switching for contribution and event registration forms.
*
* This function is shared between contribution & event forms & this is their common class.
*
* However, this should be seen as an in-progress refactor, the end goal being to also align the
* backoffice forms that action payments.
*
* This function overlaps assignPaymentProcessor, in a bad way.
*/
protected function preProcessPaymentOptions() {
$this->_paymentProcessorID = NULL;
if ($this->_paymentProcessors) {
if (!empty($this->_submitValues)) {
$this->_paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $this->_submitValues);
$this->_paymentProcessor = CRM_Utils_Array::value($this->_paymentProcessorID, $this->_paymentProcessors);
$this->set('type', $this->_paymentProcessorID);
$this->set('mode', $this->_mode);
$this->set('paymentProcessor', $this->_paymentProcessor);
}
// Set default payment processor
else {
foreach ($this->_paymentProcessors as $values) {
if (!empty($values['is_default']) || count($this->_paymentProcessors) == 1) {
$this->_paymentProcessorID = $values['id'];
break;
}
}
}
if ($this->_paymentProcessorID
|| (isset($this->_submitValues['payment_processor_id']) && $this->_submitValues['payment_processor_id'] == 0)
) {
CRM_Core_Payment_ProcessorForm::preProcess($this);
}
else {
$this->_paymentProcessor = [];
}
}
// We save the fact that the profile 'billing' is required on the payment form.
// Currently pay-later is the only 'processor' that takes notice of this - but ideally
// 1) it would be possible to select the minimum_billing_profile_id for the contribution form
// 2) that profile_id would be set on the payment processor
// 3) the payment processor would return a billing form that combines these user-configured
// minimums with the payment processor minimums. This would lead to fields like 'postal_code'
// only being on the form if either the admin has configured it as wanted or the processor
// requires it.
$this->assign('billing_profile_id', (CRM_Utils_Array::value('is_billing_required', $this->_values) ? 'billing' : ''));
}
/**
* Handle pre approval for processors.
*
* This fits with the flow where a pre-approval is done and then confirmed in the next stage when confirm is hit.
*
* This function is shared between contribution & event forms & this is their common class.
*
* However, this should be seen as an in-progress refactor, the end goal being to also align the
* backoffice forms that action payments.
*
* @param array $params
*/
protected function handlePreApproval(&$params) {
try {
$payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
$params['component'] = 'contribute';
$result = $payment->doPreApproval($params);
if (empty($result)) {
// This could happen, for example, when paypal looks at the button value & decides it is not paypal express.
return;
}
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
CRM_Core_Error::statusBounce(ts('Payment approval failed with message :') . $e->getMessage(), $payment->getCancelUrl($params['qfKey'], CRM_Utils_Array::value('participant_id', $params)));
}
$this->set('pre_approval_parameters', $result['pre_approval_parameters']);
if (!empty($result['redirect_url'])) {
CRM_Utils_System::redirect($result['redirect_url']);
}
}
/**
* Setter function for options.
*
* @param mixed $options
*/
public function setOptions($options) {
$this->_options = $options;
}
/**
* Render form and return contents.
*
* @return string
*/
public function toSmarty() {
$this->preProcessChainSelectFields();
$renderer = $this->getRenderer();
$this->accept($renderer);
$content = $renderer->toArray();
$content['formName'] = $this->getName();
// CRM-15153
$content['formClass'] = CRM_Utils_System::getClassName($this);
return $content;
}
/**
* Getter function for renderer.
*
* If renderer is not set create one and initialize it.
*
* @return object
*/
public function &getRenderer() {
if (!isset($this->_renderer)) {
$this->_renderer = CRM_Core_Form_Renderer::singleton();
}
return $this->_renderer;
}
/**
* Use the form name to create the tpl file name.
*
* @return string
*/
public function getTemplateFileName() {
$ext = CRM_Extension_System::singleton()->getMapper();
if ($ext->isExtensionClass(CRM_Utils_System::getClassName($this))) {
$filename = $ext->getTemplateName(CRM_Utils_System::getClassName($this));
$tplname = $ext->getTemplatePath(CRM_Utils_System::getClassName($this)) . DIRECTORY_SEPARATOR . $filename;