Merge pull request #12615 from eileenmcnaughton/amex
[civicrm-core.git] / CRM / Core / Payment / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Class for constructing the payment processor block.
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2018
33 */
34 class CRM_Core_Payment_Form {
35
36
37 /**
38 * Add payment fields depending on payment processor.
39 *
40 * The payment processor can implement the following functions to override the built in fields.
41 *
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
49 * @param array $processor
50 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
51 * @param int $billing_profile_id
52 * Display billing fields even for pay later.
53 * @param bool $isBackOffice
54 * Is this a back office function? If so the option to suppress the cvn needs to be evaluated.
55 * @param int $paymentInstrumentID
56 * ID of the payment processor.
57 */
58 static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_profile_id = NULL, $isBackOffice = FALSE, $paymentInstrumentID = NULL) {
59 $form->billingFieldSets = array();
60 // Load the pay-later processor
61 // @todo load this right up where the other processors are loaded initially.
62 if (empty($processor)) {
63 $processor = CRM_Financial_BAO_PaymentProcessor::getPayment(0);
64 }
65
66 $processor['object']->setBillingProfile($billing_profile_id);
67 $processor['object']->setBackOffice($isBackOffice);
68 $processor['object']->setPaymentInstrumentID($paymentInstrumentID);
69 $paymentTypeName = self::getPaymentTypeName($processor);
70 $form->assign('paymentTypeName', $paymentTypeName);
71 $form->assign('paymentTypeLabel', self::getPaymentLabel($processor['object']));
72 $form->assign('isBackOffice', $isBackOffice);
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.
78 $form->billingFieldSets['billing_name_address-group']['fields'] = array();
79 }
80
81 /**
82 * Add general billing fields.
83 *
84 * @param CRM_Core_Form $form
85 * @param CRM_Core_Payment $processor
86 */
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
93 /**
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 *
110 * @param CRM_Core_Form $form
111 * Form that the payment fields are to be added to.
112 * @param array $paymentFields
113 * Fields that are to be shown on the payment form.
114 */
115 protected static function addCommonFields(&$form, $paymentFields) {
116 $requiredPaymentFields = $paymentFieldsMetadata = [];
117 foreach ($paymentFields as $name => $field) {
118 if ($field['htmlType'] == 'chainSelect') {
119 $form->addChainSelect($field['name'], array('required' => FALSE));
120 }
121 else {
122 $form->add($field['htmlType'],
123 $field['name'],
124 $field['title'],
125 $field['attributes'],
126 FALSE
127 );
128 }
129 // This will cause the fields to be marked as required - but it is up to the payment processor to
130 // validate it.
131 $requiredPaymentFields[$field['name']] = $field['is_required'];
132 $paymentFieldsMetadata[$field['name']] = $field;
133 }
134
135 $form->assign('paymentFieldsMetadata', $paymentFieldsMetadata);
136 $form->assign('requiredPaymentFields', $requiredPaymentFields);
137 }
138
139 /**
140 * Get the payment fields that apply to this processor.
141 *
142 * @param array $paymentProcessor
143 *
144 * @todo sometimes things like the country alter the required fields (e.g direct debit fields). We should possibly
145 * set these before calling getPaymentFormFields (as we identify them).
146 *
147 * @return array
148 */
149 public static function getPaymentFields($paymentProcessor) {
150 return $paymentProcessor['object']->getPaymentFormFields();
151 }
152
153 /**
154 * @param array $paymentProcessor
155 *
156 * @return array
157 */
158 public static function getPaymentFieldMetadata($paymentProcessor) {
159 return array_intersect_key($paymentProcessor['object']->getPaymentFormFieldsMetadata(), array_flip(self::getPaymentFields($paymentProcessor)));
160 }
161
162 /**
163 * Get the billing fields that apply to this processor.
164 *
165 * @param array $paymentProcessor
166 * @param int $billingLocationID
167 * ID of billing location type.
168 *
169 * @todo sometimes things like the country alter the required fields (e.g postal code). We should possibly
170 * set these before calling getPaymentFormFields (as we identify them).
171 *
172 * @return array
173 */
174 public static function getBillingAddressFields($paymentProcessor, $billingLocationID) {
175 return $paymentProcessor['object']->getBillingAddressFields($billingLocationID);
176 }
177
178 /**
179 * @param array $paymentProcessor
180 *
181 * @param int $billingLocationID
182 *
183 * @return array
184 * @throws \CRM_Core_Exception
185 */
186 public static function getBillingAddressMetadata($paymentProcessor, $billingLocationID) {
187 $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
188 return array_intersect_key(
189 $paymentProcessorObject->getBillingAddressFieldsMetadata($billingLocationID),
190 array_flip(self::getBillingAddressFields($paymentProcessor, $billingLocationID))
191 );
192 }
193
194 /**
195 * @param array $paymentProcessor
196 *
197 * @return string
198 */
199 public static function getPaymentTypeName($paymentProcessor) {
200 return $paymentProcessor['object']->getPaymentTypeName();
201 }
202
203 /**
204 * @param array $paymentProcessor
205 *
206 * @return string
207 */
208 public static function getPaymentTypeLabel($paymentProcessor) {
209 return ts('%1 Information', [$paymentProcessor->getPaymentTypeLabel()]);
210 }
211
212 /**
213 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main|CRM_Core_Payment_ProcessorForm|CRM_Contribute_Form_UpdateBilling $form
214 * @param array $processor
215 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
216 * @param int|string $billing_profile_id
217 * Id of a profile to be passed to the processor for the processor to merge with it's required fields.
218 * (currently only implemented by manual/ pay-later processor)
219 *
220 * @param bool $isBackOffice
221 * Is this a backoffice form. This could affect the display of the cvn or whether some processors show,
222 * although the distinction is losing it's meaning as front end forms are used for back office and a permission
223 * for the 'enter without cvn' is probably more appropriate. Paypal std does not support another user
224 * entering details but once again the issue is not back office but 'another user'.
225 * @param int $paymentInstrumentID
226 * Payment instrument ID.
227 *
228 * @return bool
229 */
230 public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID = NULL) {
231 //if the form has address fields assign to the template so the js can decide what billing fields to show
232 $profileAddressFields = $form->get('profileAddressFields');
233 if (!empty($profileAddressFields)) {
234 $form->assign('profileAddressFields', $profileAddressFields);
235 }
236
237 if (!empty($processor['object']) && $processor['object']->buildForm($form)) {
238 return NULL;
239 }
240
241 self::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID);
242 self::addCommonFields($form, $form->_paymentFields);
243 self::addRules($form, $form->_paymentFields);
244 return (!empty($form->_paymentFields));
245 }
246
247 /**
248 * @param CRM_Core_Form $form
249 * @param array $paymentFields
250 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
251 * @param $paymentFields
252 */
253 protected static function addRules(&$form, $paymentFields) {
254 foreach ($paymentFields as $paymentField => $fieldSpecs) {
255 if (!empty($fieldSpecs['rules'])) {
256 foreach ($fieldSpecs['rules'] as $rule) {
257 $form->addRule($paymentField,
258 $rule['rule_message'],
259 $rule['rule_name'],
260 $rule['rule_parameters']
261 );
262 }
263 }
264 }
265 }
266
267 /**
268 * Validate the payment instrument values before passing it to the payment processor.
269 *
270 * We want this to be able to be overridden by the payment processor, and default to using
271 * this object's validCreditCard for credit cards (implemented as the default in the Payment class).
272 *
273 * @param int $payment_processor_id
274 * @param array $values
275 * @param array $errors
276 * @param int $billing_profile_id
277 */
278 public static function validatePaymentInstrument($payment_processor_id, $values, &$errors, $billing_profile_id) {
279 $payment = Civi\Payment\System::singleton()->getById($payment_processor_id);
280 $payment->setBillingProfile($billing_profile_id);
281 $payment->validatePaymentInstrument($values, $errors);
282 }
283
284 /**
285 * Set default values for the form.
286 *
287 * @param CRM_Core_Form $form
288 * @param int $contactID
289 */
290 public static function setDefaultValues(&$form, $contactID) {
291 $billingDefaults = $form->getProfileDefaults('Billing', $contactID);
292 $form->_defaults = array_merge($form->_defaults, $billingDefaults);
293
294 // set default country & state from config if no country set
295 // note the effect of this is to set the billing country to default to the site default
296 // country if the person has an address but no country (for anonymous country is set above)
297 // this could have implications if the billing profile is filled but hidden.
298 // this behaviour has been in place for a while but the use of js to hide things has increased
299 if (empty($form->_defaults["billing_country_id-{$form->_bltID}"])) {
300 $form->_defaults["billing_country_id-{$form->_bltID}"] = CRM_Core_Config::singleton()->defaultContactCountry;
301 }
302 if (empty($form->_defaults["billing_state_province_id-{$form->_bltID}"])) {
303 $form->_defaults["billing_state_province_id-{$form->_bltID}"] = CRM_Core_Config::singleton()
304 ->defaultContactStateProvince;
305 }
306 }
307
308 /**
309 * Make sure that credit card number and cvv are valid.
310 * Called within the scope of a QF formRule function
311 *
312 * @param array $values
313 * @param array $errors
314 * @param int $processorID
315 */
316 public static function validateCreditCard($values, &$errors, $processorID = NULL) {
317 if (!empty($values['credit_card_type']) || !empty($values['credit_card_number'])) {
318 if (!empty($values['credit_card_type'])) {
319 $processorCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($processorID);
320 if (!empty($processorCards) && !in_array($values['credit_card_type'], $processorCards)) {
321 $errors['credit_card_type'] = ts('This procesor does not support credit card type ' . $values['credit_card_type']);
322 }
323 }
324 if (!empty($values['credit_card_number']) &&
325 !CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
326 ) {
327 $errors['credit_card_number'] = ts('Please enter a valid Card Number');
328 }
329 if (!empty($values['cvv2']) &&
330 !CRM_Utils_Rule::cvv($values['cvv2'], $values['credit_card_type'])
331 ) {
332 $errors['cvv2'] = ts('Please enter a valid Card Verification Number');
333 }
334 }
335 }
336
337 /**
338 * Map address fields.
339 *
340 * @param int $id
341 * @param array $src
342 * @param array $dst
343 * @param bool $reverse
344 */
345 public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
346 $map = array(
347 'first_name' => 'billing_first_name',
348 'middle_name' => 'billing_middle_name',
349 'last_name' => 'billing_last_name',
350 'email' => "email-$id",
351 'street_address' => "billing_street_address-$id",
352 'supplemental_address_1' => "billing_supplemental_address_1-$id",
353 'city' => "billing_city-$id",
354 'state_province' => "billing_state_province-$id",
355 'postal_code' => "billing_postal_code-$id",
356 'country' => "billing_country-$id",
357 'contactID' => 'contact_id',
358 );
359
360 foreach ($map as $n => $v) {
361 if (!$reverse) {
362 if (isset($src[$n])) {
363 $dst[$v] = $src[$n];
364 }
365 }
366 else {
367 if (isset($src[$v])) {
368 $dst[$n] = $src[$v];
369 }
370 }
371 }
372
373 //CRM-19469 provide option for returning modified params
374 return $dst;
375 }
376
377 /**
378 * Get the credit card expiration month.
379 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
380 * See CRM-9017
381 *
382 * @param $src
383 *
384 * @return int
385 */
386 public static function getCreditCardExpirationMonth($src) {
387 if ($month = CRM_Utils_Array::value('M', $src['credit_card_exp_date'])) {
388 return $month;
389 }
390
391 return CRM_Utils_Array::value('m', $src['credit_card_exp_date']);
392 }
393
394 /**
395 * Get the credit card expiration year.
396 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
397 * This function exists only to make it consistent with getCreditCardExpirationMonth
398 *
399 * @param $src
400 *
401 * @return int
402 */
403 public static function getCreditCardExpirationYear($src) {
404 return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
405 }
406
407 /**
408 * Get the label for the processor.
409 *
410 * We do not use a label if there are no enterable fields.
411 *
412 * @param \CRM_Core_Payment $processor
413 *
414 * @return string
415 */
416 public static function getPaymentLabel($processor) {
417 $isVisible = FALSE;
418 $paymentTypeLabel = self::getPaymentTypeLabel($processor);
419 foreach (self::getPaymentFieldMetadata(['object' => $processor]) as $paymentField) {
420 if ($paymentField['htmlType'] !== 'hidden') {
421 $isVisible = TRUE;
422 }
423 }
424 return $isVisible ? $paymentTypeLabel : '';
425
426 }
427
428 }