CRM-20264 support card_type_id and pan_truncation in all backoffice form
[civicrm-core.git] / CRM / Core / Payment / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 $paymentTypeLabel = self::getPaymentTypeLabel($processor);
72 $form->assign('paymentTypeLabel', $paymentTypeLabel);
73 $form->assign('isBackOffice', $isBackOffice);
74 $form->_paymentFields = $form->billingFieldSets[$paymentTypeName]['fields'] = self::getPaymentFieldMetadata($processor);
75 $form->_paymentFields = array_merge($form->_paymentFields, self::getBillingAddressMetadata($processor, $form->_bltID));
76 $form->assign('paymentFields', self::getPaymentFields($processor));
77 self::setBillingAddressFields($form, $processor);
78 // @todo - this may be obsolete - although potentially it could be used to re-order things in the form.
79 $form->billingFieldSets['billing_name_address-group']['fields'] = array();
80 }
81
82 /**
83 * Add general billing fields.
84 *
85 * @param CRM_Core_Form $form
86 * @param CRM_Core_Payment $processor
87 */
88 static protected function setBillingAddressFields(&$form, $processor) {
89 $billingID = $form->_bltID;
90 $smarty = CRM_Core_Smarty::singleton();
91 $smarty->assign('billingDetailsFields', self::getBillingAddressFields($processor, $billingID));
92 }
93
94 /**
95 * Add the payment fields to the template.
96 *
97 * Generally this is the payment processor fields & the billing fields required
98 * for the payment processor. However, this has been complicated by adding
99 * pay later billing fields into this mix
100 *
101 * We now have the situation where the required fields cannot be set as required
102 * on the form level if they are required for the payment processor, as another
103 * processor might be selected and the validation will then be incorrect.
104 *
105 * However, if they are required for pay later we DO set them on the form level,
106 * presumably assuming they will be required whatever happens.
107 *
108 * As a side-note this seems to re-enforce the argument for making pay later
109 * operate as a payment processor rather than as a 'special thing on its own'.
110 *
111 * @param CRM_Core_Form $form
112 * Form that the payment fields are to be added to.
113 * @param array $paymentFields
114 * Fields that are to be shown on the payment form.
115 */
116 protected static function addCommonFields(&$form, $paymentFields) {
117 $requiredPaymentFields = array();
118 foreach ($paymentFields as $name => $field) {
119 // @todo - remove the cc_field check - no longer useful.
120 if (!empty($field['cc_field'])) {
121 if ($field['htmlType'] == 'chainSelect') {
122 $form->addChainSelect($field['name'], array('required' => FALSE));
123 }
124 else {
125 $form->add($field['htmlType'],
126 $field['name'],
127 $field['title'],
128 $field['attributes'],
129 FALSE
130 );
131 }
132 }
133 // This will cause the fields to be marked as required - but it is up to the payment processor to
134 // validate it.
135 $requiredPaymentFields[$field['name']] = $field['is_required'];
136 }
137 $form->assign('requiredPaymentFields', $requiredPaymentFields);
138 }
139
140 /**
141 * Get the payment fields that apply to this processor.
142 *
143 * @param array $paymentProcessor
144 *
145 * @todo sometimes things like the country alter the required fields (e.g direct debit fields). We should possibly
146 * set these before calling getPaymentFormFields (as we identify them).
147 *
148 * @return array
149 */
150 public static function getPaymentFields($paymentProcessor) {
151 return $paymentProcessor['object']->getPaymentFormFields();
152 }
153
154 /**
155 * @param array $paymentProcessor
156 *
157 * @return array
158 */
159 public static function getPaymentFieldMetadata($paymentProcessor) {
160 return array_intersect_key($paymentProcessor['object']->getPaymentFormFieldsMetadata(), array_flip(self::getPaymentFields($paymentProcessor)));
161 }
162
163 /**
164 * Get the billing fields that apply to this processor.
165 *
166 * @param array $paymentProcessor
167 * @param int $billingLocationID
168 * ID of billing location type.
169 *
170 * @todo sometimes things like the country alter the required fields (e.g postal code). We should possibly
171 * set these before calling getPaymentFormFields (as we identify them).
172 *
173 * @return array
174 */
175 public static function getBillingAddressFields($paymentProcessor, $billingLocationID) {
176 return $paymentProcessor['object']->getBillingAddressFields($billingLocationID);
177 }
178
179 /**
180 * @param array $paymentProcessor
181 *
182 * @param int $billingLocationID
183 *
184 * @return array
185 * @throws \CRM_Core_Exception
186 */
187 public static function getBillingAddressMetadata($paymentProcessor, $billingLocationID) {
188 $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
189 return array_intersect_key(
190 $paymentProcessorObject->getBillingAddressFieldsMetadata($billingLocationID),
191 array_flip(self::getBillingAddressFields($paymentProcessor, $billingLocationID))
192 );
193 }
194
195 /**
196 * @param array $paymentProcessor
197 *
198 * @return string
199 */
200 public static function getPaymentTypeName($paymentProcessor) {
201 return $paymentProcessor['object']->getPaymentTypeName();
202 }
203
204 /**
205 * @param array $paymentProcessor
206 *
207 * @return string
208 */
209 public static function getPaymentTypeLabel($paymentProcessor) {
210 $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
211 return ts(($paymentProcessorObject->getPaymentTypeLabel()) . ' Information');
212 }
213
214 /**
215 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main|CRM_Core_Payment_ProcessorForm|CRM_Contribute_Form_UpdateBilling $form
216 * @param array $processor
217 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
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)
221 *
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'.
227 * @param int $paymentInstrumentID
228 * Payment instrument ID.
229 *
230 * @return bool
231 */
232 public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID = NULL) {
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
239 if (!empty($processor['object']) && $processor['object']->buildForm($form)) {
240 return NULL;
241 }
242
243 self::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID);
244 self::addCommonFields($form, $form->_paymentFields);
245 self::addRules($form, $form->_paymentFields);
246 return (!empty($form->_paymentFields));
247 }
248
249 /**
250 * @param CRM_Core_Form $form
251 * @param array $paymentFields
252 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
253 * @param $paymentFields
254 */
255 protected static function addRules(&$form, $paymentFields) {
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 }
267 }
268
269 /**
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
273 * this object's validCreditCard for credit cards (implemented as the default in the Payment class).
274 *
275 * @param int $payment_processor_id
276 * @param array $values
277 * @param array $errors
278 * @param int $billing_profile_id
279 */
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);
284 }
285
286 /**
287 * The credit card pseudo constant results only the CC label, not the key ID
288 * So we normalize the name to use it as a CSS class.
289 */
290 public static function getCreditCardCSSNames($creditCards = array()) {
291 $creditCardTypes = array();
292 if (empty($creditCards)) {
293 $creditCards = CRM_Contribute_PseudoConstant::creditCard();
294 }
295 foreach ($creditCards as $key => $name) {
296 // Replace anything not css-friendly by an underscore
297 // Non-latin names will not like this, but so many things are wrong with
298 // the credit-card type configurations already.
299 $key = str_replace(' ', '', $key);
300 $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
301 $key = strtolower($key);
302 $creditCardTypes[$key] = $name;
303 }
304 return $creditCardTypes;
305 }
306
307 /**
308 * Set default values for the form.
309 *
310 * @param CRM_Core_Form $form
311 * @param int $contactID
312 */
313 public static function setDefaultValues(&$form, $contactID) {
314 $billingDefaults = $form->getProfileDefaults('Billing', $contactID);
315 $form->_defaults = array_merge($form->_defaults, $billingDefaults);
316
317 // set default country & state from config if no country set
318 // note the effect of this is to set the billing country to default to the site default
319 // country if the person has an address but no country (for anonymous country is set above)
320 // this could have implications if the billing profile is filled but hidden.
321 // this behaviour has been in place for a while but the use of js to hide things has increased
322 if (empty($form->_defaults["billing_country_id-{$form->_bltID}"])) {
323 $form->_defaults["billing_country_id-{$form->_bltID}"] = CRM_Core_Config::singleton()->defaultContactCountry;
324 }
325 if (empty($form->_defaults["billing_state_province_id-{$form->_bltID}"])) {
326 $form->_defaults["billing_state_province_id-{$form->_bltID}"] = CRM_Core_Config::singleton()
327 ->defaultContactStateProvince;
328 }
329 }
330
331 /**
332 * Make sure that credit card number and cvv are valid.
333 * Called within the scope of a QF formRule function
334 *
335 * @param array $values
336 * @param array $errors
337 * @param int $processorID
338 */
339 public static function validateCreditCard($values, &$errors, $processorID = NULL) {
340 if (!empty($values['credit_card_type']) || !empty($values['credit_card_number'])) {
341 if (!empty($values['credit_card_type'])) {
342 $processorCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($processorID);
343 if (!empty($processorCards) && !in_array($values['credit_card_type'], $processorCards)) {
344 $errors['credit_card_type'] = ts('This procesor does not support credit card type ' . $values['credit_card_type']);
345 }
346 }
347 if (!empty($values['credit_card_number']) &&
348 !CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
349 ) {
350 $errors['credit_card_number'] = ts('Please enter a valid Card Number');
351 }
352 if (!empty($values['cvv2']) &&
353 !CRM_Utils_Rule::cvv($values['cvv2'], $values['credit_card_type'])
354 ) {
355 $errors['cvv2'] = ts('Please enter a valid Card Verification Number');
356 }
357 }
358 }
359
360 /**
361 * Map address fields.
362 *
363 * @param int $id
364 * @param array $src
365 * @param array $dst
366 * @param bool $reverse
367 */
368 public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
369 $map = array(
370 'first_name' => 'billing_first_name',
371 'middle_name' => 'billing_middle_name',
372 'last_name' => 'billing_last_name',
373 'email' => "email-$id",
374 'street_address' => "billing_street_address-$id",
375 'supplemental_address_1' => "billing_supplemental_address_1-$id",
376 'city' => "billing_city-$id",
377 'state_province' => "billing_state_province-$id",
378 'postal_code' => "billing_postal_code-$id",
379 'country' => "billing_country-$id",
380 'contactID' => 'contact_id',
381 );
382
383 foreach ($map as $n => $v) {
384 if (!$reverse) {
385 if (isset($src[$n])) {
386 $dst[$v] = $src[$n];
387 }
388 }
389 else {
390 if (isset($src[$v])) {
391 $dst[$n] = $src[$v];
392 }
393 }
394 }
395 }
396
397 /**
398 * Get the credit card expiration month.
399 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
400 * See CRM-9017
401 *
402 * @param $src
403 *
404 * @return int
405 */
406 public static function getCreditCardExpirationMonth($src) {
407 if ($month = CRM_Utils_Array::value('M', $src['credit_card_exp_date'])) {
408 return $month;
409 }
410
411 return CRM_Utils_Array::value('m', $src['credit_card_exp_date']);
412 }
413
414 /**
415 * Get the credit card expiration year.
416 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
417 * This function exists only to make it consistent with getCreditCardExpirationMonth
418 *
419 * @param $src
420 *
421 * @return int
422 */
423 public static function getCreditCardExpirationYear($src) {
424 return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
425 }
426
427 }