3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Class for constructing the payment processor block.
32 * @copyright CiviCRM LLC (c) 2004-2018
34 class CRM_Core_Payment_Form
{
38 * Add payment fields depending on payment processor.
40 * The payment processor can implement the following functions to override the built in fields.
42 * - getPaymentFormFields()
43 * - getPaymentFormFieldsMetadata()
44 * (planned - getBillingDetailsFormFields(), getBillingDetailsFormFieldsMetadata()
46 * Note that this code is written to accommodate the possibility CiviCRM will switch to implementing pay later as a manual processor in future
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.
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);
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();
82 * Add general billing fields.
84 * @param CRM_Core_Form $form
85 * @param CRM_Core_Payment $processor
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));
94 * Add the payment fields to the template.
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
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.
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.
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'.
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.
115 protected static function addCommonFields(&$form, $paymentFields) {
116 $requiredPaymentFields = array();
117 foreach ($paymentFields as $name => $field) {
118 if ($field['htmlType'] == 'chainSelect') {
119 $form->addChainSelect($field['name'], array('required' => FALSE));
122 $form->add($field['htmlType'],
125 $field['attributes'],
129 // This will cause the fields to be marked as required - but it is up to the payment processor to
131 $requiredPaymentFields[$field['name']] = $field['is_required'];
134 $form->assign('requiredPaymentFields', $requiredPaymentFields);
138 * Get the payment fields that apply to this processor.
140 * @param array $paymentProcessor
142 * @todo sometimes things like the country alter the required fields (e.g direct debit fields). We should possibly
143 * set these before calling getPaymentFormFields (as we identify them).
147 public static function getPaymentFields($paymentProcessor) {
148 return $paymentProcessor['object']->getPaymentFormFields();
152 * @param array $paymentProcessor
156 public static function getPaymentFieldMetadata($paymentProcessor) {
157 return array_intersect_key($paymentProcessor['object']->getPaymentFormFieldsMetadata(), array_flip(self
::getPaymentFields($paymentProcessor)));
161 * Get the billing fields that apply to this processor.
163 * @param array $paymentProcessor
164 * @param int $billingLocationID
165 * ID of billing location type.
167 * @todo sometimes things like the country alter the required fields (e.g postal code). We should possibly
168 * set these before calling getPaymentFormFields (as we identify them).
172 public static function getBillingAddressFields($paymentProcessor, $billingLocationID) {
173 return $paymentProcessor['object']->getBillingAddressFields($billingLocationID);
177 * @param array $paymentProcessor
179 * @param int $billingLocationID
182 * @throws \CRM_Core_Exception
184 public static function getBillingAddressMetadata($paymentProcessor, $billingLocationID) {
185 $paymentProcessorObject = Civi\Payment\System
::singleton()->getByProcessor($paymentProcessor);
186 return array_intersect_key(
187 $paymentProcessorObject->getBillingAddressFieldsMetadata($billingLocationID),
188 array_flip(self
::getBillingAddressFields($paymentProcessor, $billingLocationID))
193 * @param array $paymentProcessor
197 public static function getPaymentTypeName($paymentProcessor) {
198 return $paymentProcessor['object']->getPaymentTypeName();
202 * @param array $paymentProcessor
206 public static function getPaymentTypeLabel($paymentProcessor) {
207 return ts('%1 Information', [$paymentProcessor->getPaymentTypeLabel()]);
211 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main|CRM_Core_Payment_ProcessorForm|CRM_Contribute_Form_UpdateBilling $form
212 * @param array $processor
213 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
214 * @param int|string $billing_profile_id
215 * Id of a profile to be passed to the processor for the processor to merge with it's required fields.
216 * (currently only implemented by manual/ pay-later processor)
218 * @param bool $isBackOffice
219 * Is this a backoffice form. This could affect the display of the cvn or whether some processors show,
220 * although the distinction is losing it's meaning as front end forms are used for back office and a permission
221 * for the 'enter without cvn' is probably more appropriate. Paypal std does not support another user
222 * entering details but once again the issue is not back office but 'another user'.
223 * @param int $paymentInstrumentID
224 * Payment instrument ID.
228 public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID = NULL) {
229 //if the form has address fields assign to the template so the js can decide what billing fields to show
230 $profileAddressFields = $form->get('profileAddressFields');
231 if (!empty($profileAddressFields)) {
232 $form->assign('profileAddressFields', $profileAddressFields);
235 if (!empty($processor['object']) && $processor['object']->buildForm($form)) {
239 self
::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID);
240 self
::addCommonFields($form, $form->_paymentFields
);
241 self
::addRules($form, $form->_paymentFields
);
242 return (!empty($form->_paymentFields
));
246 * @param CRM_Core_Form $form
247 * @param array $paymentFields
248 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
249 * @param $paymentFields
251 protected static function addRules(&$form, $paymentFields) {
252 foreach ($paymentFields as $paymentField => $fieldSpecs) {
253 if (!empty($fieldSpecs['rules'])) {
254 foreach ($fieldSpecs['rules'] as $rule) {
255 $form->addRule($paymentField,
256 $rule['rule_message'],
258 $rule['rule_parameters']
266 * Validate the payment instrument values before passing it to the payment processor.
268 * We want this to be able to be overridden by the payment processor, and default to using
269 * this object's validCreditCard for credit cards (implemented as the default in the Payment class).
271 * @param int $payment_processor_id
272 * @param array $values
273 * @param array $errors
274 * @param int $billing_profile_id
276 public static function validatePaymentInstrument($payment_processor_id, $values, &$errors, $billing_profile_id) {
277 $payment = Civi\Payment\System
::singleton()->getById($payment_processor_id);
278 $payment->setBillingProfile($billing_profile_id);
279 $payment->validatePaymentInstrument($values, $errors);
283 * The credit card pseudo constant results only the CC label, not the key ID
284 * So we normalize the name to use it as a CSS class.
286 public static function getCreditCardCSSNames($creditCards = array()) {
287 $creditCardTypes = array();
288 if (empty($creditCards)) {
289 $creditCards = CRM_Contribute_PseudoConstant
::creditCard();
291 foreach ($creditCards as $key => $name) {
292 // Replace anything not css-friendly by an underscore
293 // Non-latin names will not like this, but so many things are wrong with
294 // the credit-card type configurations already.
295 $key = str_replace(' ', '', $key);
296 $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
297 $key = strtolower($key);
298 $creditCardTypes[$key] = $name;
300 return $creditCardTypes;
304 * Set default values for the form.
306 * @param CRM_Core_Form $form
307 * @param int $contactID
309 public static function setDefaultValues(&$form, $contactID) {
310 $billingDefaults = $form->getProfileDefaults('Billing', $contactID);
311 $form->_defaults
= array_merge($form->_defaults
, $billingDefaults);
313 // set default country & state from config if no country set
314 // note the effect of this is to set the billing country to default to the site default
315 // country if the person has an address but no country (for anonymous country is set above)
316 // this could have implications if the billing profile is filled but hidden.
317 // this behaviour has been in place for a while but the use of js to hide things has increased
318 if (empty($form->_defaults
["billing_country_id-{$form->_bltID}"])) {
319 $form->_defaults
["billing_country_id-{$form->_bltID}"] = CRM_Core_Config
::singleton()->defaultContactCountry
;
321 if (empty($form->_defaults
["billing_state_province_id-{$form->_bltID}"])) {
322 $form->_defaults
["billing_state_province_id-{$form->_bltID}"] = CRM_Core_Config
::singleton()
323 ->defaultContactStateProvince
;
328 * Make sure that credit card number and cvv are valid.
329 * Called within the scope of a QF formRule function
331 * @param array $values
332 * @param array $errors
333 * @param int $processorID
335 public static function validateCreditCard($values, &$errors, $processorID = NULL) {
336 if (!empty($values['credit_card_type']) ||
!empty($values['credit_card_number'])) {
337 if (!empty($values['credit_card_type'])) {
338 $processorCards = CRM_Financial_BAO_PaymentProcessor
::getCreditCards($processorID);
339 if (!empty($processorCards) && !in_array($values['credit_card_type'], $processorCards)) {
340 $errors['credit_card_type'] = ts('This procesor does not support credit card type ' . $values['credit_card_type']);
343 if (!empty($values['credit_card_number']) &&
344 !CRM_Utils_Rule
::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
346 $errors['credit_card_number'] = ts('Please enter a valid Card Number');
348 if (!empty($values['cvv2']) &&
349 !CRM_Utils_Rule
::cvv($values['cvv2'], $values['credit_card_type'])
351 $errors['cvv2'] = ts('Please enter a valid Card Verification Number');
357 * Map address fields.
362 * @param bool $reverse
364 public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
366 'first_name' => 'billing_first_name',
367 'middle_name' => 'billing_middle_name',
368 'last_name' => 'billing_last_name',
369 'email' => "email-$id",
370 'street_address' => "billing_street_address-$id",
371 'supplemental_address_1' => "billing_supplemental_address_1-$id",
372 'city' => "billing_city-$id",
373 'state_province' => "billing_state_province-$id",
374 'postal_code' => "billing_postal_code-$id",
375 'country' => "billing_country-$id",
376 'contactID' => 'contact_id',
379 foreach ($map as $n => $v) {
381 if (isset($src[$n])) {
386 if (isset($src[$v])) {
392 //CRM-19469 provide option for returning modified params
397 * Get the credit card expiration month.
398 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
405 public static function getCreditCardExpirationMonth($src) {
406 if ($month = CRM_Utils_Array
::value('M', $src['credit_card_exp_date'])) {
410 return CRM_Utils_Array
::value('m', $src['credit_card_exp_date']);
414 * Get the credit card expiration year.
415 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
416 * This function exists only to make it consistent with getCreditCardExpirationMonth
422 public static function getCreditCardExpirationYear($src) {
423 return CRM_Utils_Array
::value('Y', $src['credit_card_exp_date']);
427 * Get the label for the processor.
429 * We do not use a label if there are no enterable fields.
431 * @param \CRM_Core_Payment $processor
435 public static function getPaymentLabel($processor) {
437 $paymentTypeLabel = self
::getPaymentTypeLabel($processor);
438 foreach (self
::getPaymentFieldMetadata(['object' => $processor]) as $paymentField) {
439 if ($paymentField['htmlType'] !== 'hidden') {
443 return $isVisible ?
$paymentTypeLabel : '';