Merge pull request #13895 from eileenmcnaughton/format
[civicrm-core.git] / CRM / Core / Payment / Form.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
3310ab71 29 * Class for constructing the payment processor block.
6a488035
TO
30 *
31 * @package CRM
6b83d5bd 32 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
33 */
34class CRM_Core_Payment_Form {
35
dc913073
EM
36
37 /**
70d1766d 38 * Add payment fields depending on payment processor.
39 *
40 * The payment processor can implement the following functions to override the built in fields.
dc913073 41 *
dde5a0ef
EM
42 * - getPaymentFormFields()
43 * - getPaymentFormFieldsMetadata()
44 * (planned - getBillingDetailsFormFields(), getBillingDetailsFormFieldsMetadata()
45 *
46 * Note that this code is written to accommodate the possibility CiviCRM will switch to implementing pay later as a manual processor in future
47 *
48 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main $form
6a0b768e
TO
49 * @param array $processor
50 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
1d1fee72 51 * @param int $billing_profile_id
6a0b768e 52 * Display billing fields even for pay later.
dfc68e82
EM
53 * @param bool $isBackOffice
54 * Is this a back office function? If so the option to suppress the cvn needs to be evaluated.
18135422 55 * @param int $paymentInstrumentID
56 * ID of the payment processor.
dc913073 57 */
18135422 58 static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_profile_id = NULL, $isBackOffice = FALSE, $paymentInstrumentID = NULL) {
dc913073 59 $form->billingFieldSets = array();
1d1fee72 60 // Load the pay-later processor
61 // @todo load this right up where the other processors are loaded initially.
3310ab71 62 if (empty($processor)) {
1d1fee72 63 $processor = CRM_Financial_BAO_PaymentProcessor::getPayment(0);
dc913073 64 }
3310ab71 65
1d1fee72 66 $processor['object']->setBillingProfile($billing_profile_id);
18135422 67 $processor['object']->setBackOffice($isBackOffice);
68 $processor['object']->setPaymentInstrumentID($paymentInstrumentID);
3310ab71 69 $paymentTypeName = self::getPaymentTypeName($processor);
3310ab71 70 $form->assign('paymentTypeName', $paymentTypeName);
c42f1a19 71 $form->assign('paymentTypeLabel', self::getPaymentLabel($processor['object']));
18135422 72 $form->assign('isBackOffice', $isBackOffice);
3310ab71 73 $form->_paymentFields = $form->billingFieldSets[$paymentTypeName]['fields'] = self::getPaymentFieldMetadata($processor);
74 $form->_paymentFields = array_merge($form->_paymentFields, self::getBillingAddressMetadata($processor, $form->_bltID));
75 $form->assign('paymentFields', self::getPaymentFields($processor));
76 self::setBillingAddressFields($form, $processor);
77 // @todo - this may be obsolete - although potentially it could be used to re-order things in the form.
dde5a0ef 78 $form->billingFieldSets['billing_name_address-group']['fields'] = array();
dc913073 79 }
9c39fb25 80
6a488035 81 /**
fe482240 82 * Add general billing fields.
9c39fb25 83 *
c490a46a 84 * @param CRM_Core_Form $form
3310ab71 85 * @param CRM_Core_Payment $processor
6a488035 86 */
3310ab71 87 static protected function setBillingAddressFields(&$form, $processor) {
88 $billingID = $form->_bltID;
89 $smarty = CRM_Core_Smarty::singleton();
90 $smarty->assign('billingDetailsFields', self::getBillingAddressFields($processor, $billingID));
91 }
92
c46f87cf 93 /**
9d421118 94 * Add the payment fields to the template.
95 *
96 * Generally this is the payment processor fields & the billing fields required
97 * for the payment processor. However, this has been complicated by adding
98 * pay later billing fields into this mix
99 *
100 * We now have the situation where the required fields cannot be set as required
101 * on the form level if they are required for the payment processor, as another
102 * processor might be selected and the validation will then be incorrect.
103 *
104 * However, if they are required for pay later we DO set them on the form level,
105 * presumably assuming they will be required whatever happens.
106 *
107 * As a side-note this seems to re-enforce the argument for making pay later
108 * operate as a payment processor rather than as a 'special thing on its own'.
109 *
c46f87cf 110 * @param CRM_Core_Form $form
9d421118 111 * Form that the payment fields are to be added to.
dc913073 112 * @param array $paymentFields
9d421118 113 * Fields that are to be shown on the payment form.
c46f87cf 114 */
c319039f 115 protected static function addCommonFields(&$form, $paymentFields) {
4533376a 116 $requiredPaymentFields = $paymentFieldsMetadata = [];
dc913073 117 foreach ($paymentFields as $name => $field) {
69e1be3a 118 $field['extra'] = isset($field['extra']) ? $field['extra'] : NULL;
c42f1a19 119 if ($field['htmlType'] == 'chainSelect') {
120 $form->addChainSelect($field['name'], array('required' => FALSE));
121 }
122 else {
123 $form->add($field['htmlType'],
124 $field['name'],
125 $field['title'],
126 $field['attributes'],
69e1be3a
SL
127 FALSE,
128 $field['extra']
c42f1a19 129 );
c46f87cf 130 }
c319039f 131 // This will cause the fields to be marked as required - but it is up to the payment processor to
132 // validate it.
133 $requiredPaymentFields[$field['name']] = $field['is_required'];
4533376a 134 $paymentFieldsMetadata[$field['name']] = $field;
c46f87cf 135 }
c42f1a19 136
4533376a 137 $form->assign('paymentFieldsMetadata', $paymentFieldsMetadata);
9d421118 138 $form->assign('requiredPaymentFields', $requiredPaymentFields);
c46f87cf
CW
139 }
140
44b6505d 141 /**
3310ab71 142 * Get the payment fields that apply to this processor.
143 *
44b6505d 144 * @param array $paymentProcessor
3310ab71 145 *
146 * @todo sometimes things like the country alter the required fields (e.g direct debit fields). We should possibly
147 * set these before calling getPaymentFormFields (as we identify them).
44b6505d 148 *
dc913073 149 * @return array
44b6505d 150 */
00be9182 151 public static function getPaymentFields($paymentProcessor) {
18135422 152 return $paymentProcessor['object']->getPaymentFormFields();
44b6505d
EM
153 }
154
155 /**
dc913073 156 * @param array $paymentProcessor
44b6505d 157 *
dc913073
EM
158 * @return array
159 */
00be9182 160 public static function getPaymentFieldMetadata($paymentProcessor) {
18135422 161 return array_intersect_key($paymentProcessor['object']->getPaymentFormFieldsMetadata(), array_flip(self::getPaymentFields($paymentProcessor)));
3310ab71 162 }
163
164 /**
165 * Get the billing fields that apply to this processor.
166 *
167 * @param array $paymentProcessor
168 * @param int $billingLocationID
169 * ID of billing location type.
170 *
171 * @todo sometimes things like the country alter the required fields (e.g postal code). We should possibly
172 * set these before calling getPaymentFormFields (as we identify them).
173 *
174 * @return array
175 */
176 public static function getBillingAddressFields($paymentProcessor, $billingLocationID) {
1d1fee72 177 return $paymentProcessor['object']->getBillingAddressFields($billingLocationID);
3310ab71 178 }
179
180 /**
181 * @param array $paymentProcessor
182 *
183 * @param int $billingLocationID
184 *
185 * @return array
186 * @throws \CRM_Core_Exception
187 */
188 public static function getBillingAddressMetadata($paymentProcessor, $billingLocationID) {
189 $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
048d49dc 190 return array_intersect_key(
191 $paymentProcessorObject->getBillingAddressFieldsMetadata($billingLocationID),
e58c1c1a 192 array_flip(self::getBillingAddressFields($paymentProcessor, $billingLocationID))
048d49dc 193 );
dc913073
EM
194 }
195
196 /**
44b6505d 197 * @param array $paymentProcessor
44b6505d 198 *
dc913073 199 * @return string
44b6505d 200 */
00be9182 201 public static function getPaymentTypeName($paymentProcessor) {
1d1fee72 202 return $paymentProcessor['object']->getPaymentTypeName();
dc913073 203 }
44b6505d 204
dc913073
EM
205 /**
206 * @param array $paymentProcessor
207 *
208 * @return string
209 */
00be9182 210 public static function getPaymentTypeLabel($paymentProcessor) {
c42f1a19 211 return ts('%1 Information', [$paymentProcessor->getPaymentTypeLabel()]);
44b6505d
EM
212 }
213
dc913073 214 /**
a6513ad5 215 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main|CRM_Core_Payment_ProcessorForm|CRM_Contribute_Form_UpdateBilling $form
6a0b768e
TO
216 * @param array $processor
217 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
1d1fee72 218 * @param int|string $billing_profile_id
219 * Id of a profile to be passed to the processor for the processor to merge with it's required fields.
220 * (currently only implemented by manual/ pay-later processor)
dc913073 221 *
225584c9
EM
222 * @param bool $isBackOffice
223 * Is this a backoffice form. This could affect the display of the cvn or whether some processors show,
224 * although the distinction is losing it's meaning as front end forms are used for back office and a permission
225 * for the 'enter without cvn' is probably more appropriate. Paypal std does not support another user
226 * entering details but once again the issue is not back office but 'another user'.
18135422 227 * @param int $paymentInstrumentID
228 * Payment instrument ID.
225584c9 229 *
dc913073
EM
230 * @return bool
231 */
18135422 232 public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID = NULL) {
dde5a0ef
EM
233 //if the form has address fields assign to the template so the js can decide what billing fields to show
234 $profileAddressFields = $form->get('profileAddressFields');
235 if (!empty($profileAddressFields)) {
236 $form->assign('profileAddressFields', $profileAddressFields);
237 }
238
287aebfb 239 if (!empty($processor['object']) && $processor['object']->buildForm($form)) {
aefd7f6b 240 return NULL;
dde5a0ef
EM
241 }
242
18135422 243 self::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID);
c319039f 244 self::addCommonFields($form, $form->_paymentFields);
dc913073 245 self::addRules($form, $form->_paymentFields);
dc913073
EM
246 return (!empty($form->_paymentFields));
247 }
44b6505d 248
dc913073
EM
249 /**
250 * @param CRM_Core_Form $form
6a0b768e
TO
251 * @param array $paymentFields
252 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
dc913073
EM
253 * @param $paymentFields
254 */
9c39fb25 255 protected static function addRules(&$form, $paymentFields) {
dc913073
EM
256 foreach ($paymentFields as $paymentField => $fieldSpecs) {
257 if (!empty($fieldSpecs['rules'])) {
258 foreach ($fieldSpecs['rules'] as $rule) {
259 $form->addRule($paymentField,
260 $rule['rule_message'],
261 $rule['rule_name'],
262 $rule['rule_parameters']
263 );
264 }
265 }
266 }
6a488035
TO
267 }
268
a479fe60 269 /**
54957108 270 * Validate the payment instrument values before passing it to the payment processor.
271 *
272 * We want this to be able to be overridden by the payment processor, and default to using
a479fe60 273 * this object's validCreditCard for credit cards (implemented as the default in the Payment class).
54957108 274 *
275 * @param int $payment_processor_id
276 * @param array $values
277 * @param array $errors
278 * @param int $billing_profile_id
a479fe60 279 */
1d1fee72 280 public static function validatePaymentInstrument($payment_processor_id, $values, &$errors, $billing_profile_id) {
281 $payment = Civi\Payment\System::singleton()->getById($payment_processor_id);
282 $payment->setBillingProfile($billing_profile_id);
283 $payment->validatePaymentInstrument($values, $errors);
a479fe60 284 }
285
70d1766d 286 /**
287 * Set default values for the form.
288 *
289 * @param CRM_Core_Form $form
290 * @param int $contactID
291 */
292 public static function setDefaultValues(&$form, $contactID) {
293 $billingDefaults = $form->getProfileDefaults('Billing', $contactID);
294 $form->_defaults = array_merge($form->_defaults, $billingDefaults);
295
296 // set default country & state from config if no country set
297 // note the effect of this is to set the billing country to default to the site default
298 // country if the person has an address but no country (for anonymous country is set above)
299 // this could have implications if the billing profile is filled but hidden.
300 // this behaviour has been in place for a while but the use of js to hide things has increased
301 if (empty($form->_defaults["billing_country_id-{$form->_bltID}"])) {
302 $form->_defaults["billing_country_id-{$form->_bltID}"] = CRM_Core_Config::singleton()->defaultContactCountry;
303 }
304 if (empty($form->_defaults["billing_state_province_id-{$form->_bltID}"])) {
305 $form->_defaults["billing_state_province_id-{$form->_bltID}"] = CRM_Core_Config::singleton()
306 ->defaultContactStateProvince;
307 }
308 }
309
7cb3d4f0 310 /**
fe482240 311 * Make sure that credit card number and cvv are valid.
7cb3d4f0 312 * Called within the scope of a QF formRule function
431c430b
EM
313 *
314 * @param array $values
315 * @param array $errors
06051ca4 316 * @param int $processorID
7cb3d4f0 317 */
06051ca4 318 public static function validateCreditCard($values, &$errors, $processorID = NULL) {
4d1fd569 319 if (!empty($values['credit_card_type']) || !empty($values['credit_card_number'])) {
27b252af
SL
320 if (!empty($values['credit_card_type'])) {
321 $processorCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($processorID);
322 if (!empty($processorCards) && !in_array($values['credit_card_type'], $processorCards)) {
323 $errors['credit_card_type'] = ts('This procesor does not support credit card type ' . $values['credit_card_type']);
324 }
325 }
7cb3d4f0
CW
326 if (!empty($values['credit_card_number']) &&
327 !CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
328 ) {
8543f7c1 329 $errors['credit_card_number'] = ts('Please enter a valid Card Number');
7cb3d4f0
CW
330 }
331 if (!empty($values['cvv2']) &&
332 !CRM_Utils_Rule::cvv($values['cvv2'], $values['credit_card_type'])
333 ) {
8543f7c1 334 $errors['cvv2'] = ts('Please enter a valid Card Verification Number');
7cb3d4f0
CW
335 }
336 }
337 }
338
6a488035 339 /**
fe482240 340 * Map address fields.
6a488035 341 *
100fef9d 342 * @param int $id
431c430b
EM
343 * @param array $src
344 * @param array $dst
77b97be7 345 * @param bool $reverse
6a488035 346 */
431c430b 347 public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
0b05b9a9 348 $map = array(
349 'first_name' => 'billing_first_name',
350 'middle_name' => 'billing_middle_name',
351 'last_name' => 'billing_last_name',
352 'email' => "email-$id",
353 'street_address' => "billing_street_address-$id",
354 'supplemental_address_1' => "billing_supplemental_address_1-$id",
355 'city' => "billing_city-$id",
356 'state_province' => "billing_state_province-$id",
357 'postal_code' => "billing_postal_code-$id",
358 'country' => "billing_country-$id",
359 'contactID' => 'contact_id',
360 );
6a488035
TO
361
362 foreach ($map as $n => $v) {
363 if (!$reverse) {
364 if (isset($src[$n])) {
365 $dst[$v] = $src[$n];
366 }
367 }
368 else {
369 if (isset($src[$v])) {
370 $dst[$n] = $src[$v];
371 }
372 }
373 }
3be4a20e
BS
374
375 //CRM-19469 provide option for returning modified params
376 return $dst;
6a488035
TO
377 }
378
379 /**
fe482240 380 * Get the credit card expiration month.
6a488035
TO
381 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
382 * See CRM-9017
383 *
2a6da8d7
EM
384 * @param $src
385 *
6a488035 386 * @return int
6a488035 387 */
00be9182 388 public static function getCreditCardExpirationMonth($src) {
6a488035
TO
389 if ($month = CRM_Utils_Array::value('M', $src['credit_card_exp_date'])) {
390 return $month;
391 }
392
393 return CRM_Utils_Array::value('m', $src['credit_card_exp_date']);
394 }
395
396 /**
fe482240 397 * Get the credit card expiration year.
6a488035 398 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
c1cc3e0c 399 * This function exists only to make it consistent with getCreditCardExpirationMonth
6a488035 400 *
2a6da8d7
EM
401 * @param $src
402 *
6a488035 403 * @return int
6a488035 404 */
00be9182 405 public static function getCreditCardExpirationYear($src) {
6a488035
TO
406 return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
407 }
96025800 408
c42f1a19 409 /**
410 * Get the label for the processor.
411 *
412 * We do not use a label if there are no enterable fields.
413 *
414 * @param \CRM_Core_Payment $processor
415 *
416 * @return string
417 */
418 public static function getPaymentLabel($processor) {
419 $isVisible = FALSE;
420 $paymentTypeLabel = self::getPaymentTypeLabel($processor);
421 foreach (self::getPaymentFieldMetadata(['object' => $processor]) as $paymentField) {
422 if ($paymentField['htmlType'] !== 'hidden') {
423 $isVisible = TRUE;
424 }
425 }
426 return $isVisible ? $paymentTypeLabel : '';
427
428 }
429
6a488035 430}