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