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