Merge pull request #5971 from PalanteJon/activityreportfix
[civicrm-core.git] / CRM / Core / Payment / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_Core_Payment_Form {
36
37
38 /**
39 * Add payment fields depending on payment processor. The payment processor can implement the following functions to override the built in fields.
40 *
41 * - getPaymentFormFields()
42 * - getPaymentFormFieldsMetadata()
43 * (planned - getBillingDetailsFormFields(), getBillingDetailsFormFieldsMetadata()
44 *
45 * Note that this code is written to accommodate the possibility CiviCRM will switch to implementing pay later as a manual processor in future
46 *
47 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main $form
48 * @param array $processor
49 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
50 * @param bool $forceBillingFieldsForPayLater
51 * Display billing fields even for pay later.
52 */
53 static public function setPaymentFieldsByProcessor(&$form, $processor, $forceBillingFieldsForPayLater = FALSE) {
54 $form->billingFieldSets = array();
55 if ($processor != NULL) {
56 // ie it is pay later
57 $paymentFields = self::getPaymentFields($processor);
58 $paymentTypeName = self::getPaymentTypeName($processor);
59 $paymentTypeLabel = self::getPaymentTypeLabel($processor);
60 //@todo if we switch to iterating through $form->billingFieldSets we won't need to assign these directly
61 $form->assign('paymentTypeName', $paymentTypeName);
62 $form->assign('paymentTypeLabel', $paymentTypeLabel);
63
64 $form->billingFieldSets[$paymentTypeName]['fields'] = $form->_paymentFields = array_intersect_key(self::getPaymentFieldMetadata($processor), array_flip($paymentFields));
65 $form->billingPane = array($paymentTypeName => $paymentTypeLabel);
66 $form->assign('paymentFields', $paymentFields);
67 }
68
69 // @todo - replace this section with one similar to above per discussion - probably use a manual processor shell class to stand in for that capability
70 //return without adding billing fields if billing_mode = 4 (@todo - more the ability to set that to the payment processor)
71 // or payment processor is NULL (pay later)
72 if (($processor == NULL && !$forceBillingFieldsForPayLater) || CRM_Utils_Array::value('billing_mode', $processor) == 4) {
73 return;
74 }
75 //@todo setPaymentFields defines the billing fields - this should be moved to the processor class & renamed getBillingFields
76 // potentially pay later would also be a payment processor
77 //also set the billingFieldSet to hold all the details required to render the fieldset so we can iterate through the fieldset - making
78 // it easier to re-order in hooks etc. The billingFieldSets param is used to determine whether to show the billing pane
79 CRM_Core_Payment_Form::setBillingDetailsFields($form);
80 $form->billingFieldSets['billing_name_address-group']['fields'] = array();
81 }
82
83 /**
84 * Add general billing fields.
85 * @todo set these like processor fields & let payment processors alter them
86 *
87 * @param CRM_Core_Form $form
88 *
89 * @return void
90 */
91 static protected function setBillingDetailsFields(&$form) {
92 $bltID = $form->_bltID;
93
94 $form->_paymentFields['billing_first_name'] = array(
95 'htmlType' => 'text',
96 'name' => 'billing_first_name',
97 'title' => ts('Billing First Name'),
98 'cc_field' => TRUE,
99 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
100 'is_required' => TRUE,
101 );
102
103 $form->_paymentFields['billing_middle_name'] = array(
104 'htmlType' => 'text',
105 'name' => 'billing_middle_name',
106 'title' => ts('Billing Middle Name'),
107 'cc_field' => TRUE,
108 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
109 'is_required' => FALSE,
110 );
111
112 $form->_paymentFields['billing_last_name'] = array(
113 'htmlType' => 'text',
114 'name' => 'billing_last_name',
115 'title' => ts('Billing Last Name'),
116 'cc_field' => TRUE,
117 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
118 'is_required' => TRUE,
119 );
120
121 $form->_paymentFields["billing_street_address-{$bltID}"] = array(
122 'htmlType' => 'text',
123 'name' => "billing_street_address-{$bltID}",
124 'title' => ts('Street Address'),
125 'cc_field' => TRUE,
126 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
127 'is_required' => TRUE,
128 );
129
130 $form->_paymentFields["billing_city-{$bltID}"] = array(
131 'htmlType' => 'text',
132 'name' => "billing_city-{$bltID}",
133 'title' => ts('City'),
134 'cc_field' => TRUE,
135 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
136 'is_required' => TRUE,
137 );
138
139 $form->_paymentFields["billing_state_province_id-{$bltID}"] = array(
140 'htmlType' => 'chainSelect',
141 'title' => ts('State/Province'),
142 'name' => "billing_state_province_id-{$bltID}",
143 'cc_field' => TRUE,
144 'is_required' => TRUE,
145 );
146
147 $form->_paymentFields["billing_postal_code-{$bltID}"] = array(
148 'htmlType' => 'text',
149 'name' => "billing_postal_code-{$bltID}",
150 'title' => ts('Postal Code'),
151 'cc_field' => TRUE,
152 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'),
153 'is_required' => TRUE,
154 );
155
156 $form->_paymentFields["billing_country_id-{$bltID}"] = array(
157 'htmlType' => 'select',
158 'name' => "billing_country_id-{$bltID}",
159 'title' => ts('Country'),
160 'cc_field' => TRUE,
161 'attributes' => array(
162 '' => ts('- select -'),
163 ) +
164 CRM_Core_PseudoConstant::country(),
165 'is_required' => TRUE,
166 );
167 //CRM-15509 working towards giving control over billing fields to payment processors. For now removing tpl hard-coding
168 $smarty = CRM_Core_Smarty::singleton();
169 $smarty->assign('billingDetailsFields', array(
170 'billing_first_name',
171 'billing_middle_name',
172 'billing_last_name',
173 "billing_street_address-{$bltID}",
174 "billing_city-{$bltID}",
175 "billing_country_id-{$bltID}",
176 "billing_state_province_id-{$bltID}",
177 "billing_postal_code-{$bltID}",
178 ));
179 }
180
181 /**
182 * @param CRM_Core_Form $form
183 * @param bool $useRequired
184 * @param array $paymentFields
185 */
186 protected static function addCommonFields(&$form, $useRequired, $paymentFields) {
187 foreach ($paymentFields as $name => $field) {
188 if (!empty($field['cc_field'])) {
189 if ($field['htmlType'] == 'chainSelect') {
190 $form->addChainSelect($field['name'], array('required' => $useRequired && $field['is_required']));
191 }
192 else {
193 $form->add($field['htmlType'],
194 $field['name'],
195 $field['title'],
196 $field['attributes'],
197 $useRequired ? $field['is_required'] : FALSE
198 );
199 }
200 }
201 }
202 }
203
204 /**
205 * @param array $paymentProcessor
206 * @todo it will be necessary to set details that affect it - mostly likely take Country as a param. Should we add generic
207 * setParams on processor class or just setCountry which we know we need?
208 *
209 * @return array
210 */
211 public static function getPaymentFields($paymentProcessor) {
212 $paymentProcessorObject = CRM_Core_Payment::singleton(($paymentProcessor['is_test'] ? 'test' : 'live'), $paymentProcessor);
213 return $paymentProcessorObject->getPaymentFormFields();
214 }
215
216 /**
217 * @param array $paymentProcessor
218 *
219 * @return array
220 */
221 public static function getPaymentFieldMetadata($paymentProcessor) {
222 $paymentProcessorObject = CRM_Core_Payment::singleton(($paymentProcessor['is_test'] ? 'test' : 'live'), $paymentProcessor);
223 return $paymentProcessorObject->getPaymentFormFieldsMetadata();
224 }
225
226 /**
227 * @param array $paymentProcessor
228 *
229 * @return string
230 */
231 public static function getPaymentTypeName($paymentProcessor) {
232 $paymentProcessorObject = CRM_Core_Payment::singleton(($paymentProcessor['is_test'] ? 'test' : 'live'), $paymentProcessor);
233 return $paymentProcessorObject->getPaymentTypeName();
234 }
235
236 /**
237 * @param array $paymentProcessor
238 *
239 * @return string
240 */
241 public static function getPaymentTypeLabel($paymentProcessor) {
242 $paymentProcessorObject = CRM_Core_Payment::singleton(($paymentProcessor['is_test'] ? 'test' : 'live'), $paymentProcessor);
243 return ts(($paymentProcessorObject->getPaymentTypeLabel()) . ' Information');
244 }
245
246 /**
247 * @param CRM_Contribute_Form_AbstractEditPayment|CRM_Contribute_Form_Contribution_Main|CRM_Core_Payment_ProcessorForm|CRM_Contribute_Form_UpdateBilling $form
248 * @param array $processor
249 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
250 * @param bool $isBillingDataOptional
251 * This manifests for 'NULL' (pay later) payment processor as the addition of billing fields to the form and.
252 * for payment processors that gather payment data on site as rendering the fields as not being required. (not entirely sure why but this
253 * is implemented for back office forms)
254 *
255 * @return bool
256 */
257 public static function buildPaymentForm(&$form, $processor, $isBillingDataOptional) {
258 //if the form has address fields assign to the template so the js can decide what billing fields to show
259 $profileAddressFields = $form->get('profileAddressFields');
260 if (!empty($profileAddressFields)) {
261 $form->assign('profileAddressFields', $profileAddressFields);
262 }
263
264 // $processor->buildForm appears to be an undocumented (possibly unused) option for payment processors
265 // which was previously available only in some form flows
266 if (!empty($form->_paymentProcessor) && !empty($form->_paymentProcessor['object']) && $form->_paymentProcessor['object']->isSupported('buildForm')) {
267 $form->_paymentProcessor['object']->buildForm($form);
268 return NULL;
269 }
270
271 self::setPaymentFieldsByProcessor($form, $processor, empty($isBillingDataOptional));
272 self::addCommonFields($form, !$isBillingDataOptional, $form->_paymentFields);
273 self::addRules($form, $form->_paymentFields);
274 self::addPaypalExpressCode($form);
275 return (!empty($form->_paymentFields));
276 }
277
278 /**
279 * @param CRM_Core_Form $form
280 * @param array $paymentFields
281 * Array of properties including 'object' as loaded from CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors.
282 * @param $paymentFields
283 */
284 protected static function addRules(&$form, $paymentFields) {
285 foreach ($paymentFields as $paymentField => $fieldSpecs) {
286 if (!empty($fieldSpecs['rules'])) {
287 foreach ($fieldSpecs['rules'] as $rule) {
288 $form->addRule($paymentField,
289 $rule['rule_message'],
290 $rule['rule_name'],
291 $rule['rule_parameters']
292 );
293 }
294 }
295 }
296 }
297
298 /**
299 * Billing mode button is basically synonymous with paypal express - this is probably a good example of 'odds & sods' code we
300 * need to find a way for the payment processor to assign. A tricky aspect is that the payment processor may need to set the order
301 *
302 * @param $form
303 */
304 protected static function addPaypalExpressCode(&$form) {
305 if (empty($form->isBackOffice)) {
306 if (CRM_Utils_Array::value('billing_mode', $form->_paymentProcessor) == 3
307 ) {
308 $form->_expressButtonName = $form->getButtonName('upload', 'express');
309 $form->assign('expressButtonName', $form->_expressButtonName);
310 $form->add('image',
311 $form->_expressButtonName,
312 $form->_paymentProcessor['url_button'],
313 array('class' => 'crm-form-submit')
314 );
315 }
316 }
317 }
318
319 /**
320 * Validate the payment instrument values before passing it to the payment processor
321 * We want this to be overrideable by the payment processor, and default to using
322 * this object's validCreditCard for credit cards (implemented as the default in the Payment class).
323 */
324 public static function validatePaymentInstrument($payment_processor_id, $values, &$errors, $form) {
325 // ignore if we don't have a payment instrument to validate (e.g. backend payments)
326 if ($payment_processor_id > 0) {
327 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($payment_processor_id, 'live');
328 $payment = CRM_Core_Payment::singleton('live', $paymentProcessor, $form);
329 $payment->validatePaymentInstrument($values, $errors);
330 }
331 }
332
333 /**
334 * The credit card pseudo constant results only the CC label, not the key ID
335 * So we normalize the name to use it as a CSS class.
336 */
337 public static function getCreditCardCSSNames() {
338 $creditCardTypes = array();
339 foreach (CRM_Contribute_PseudoConstant::creditCard() as $key => $name) {
340 // Replace anything not css-friendly by an underscore
341 // Non-latin names will not like this, but so many things are wrong with
342 // the credit-card type configurations already.
343 $key = str_replace(' ', '', $key);
344 $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
345 $key = strtolower($key);
346 $creditCardTypes[$key] = $name;
347 }
348 return $creditCardTypes;
349 }
350
351 /**
352 * Make sure that credit card number and cvv are valid.
353 * Called within the scope of a QF formRule function
354 *
355 * @param array $values
356 * @param array $errors
357 */
358 public static function validateCreditCard($values, &$errors) {
359 if (!empty($values['credit_card_type']) || !empty($values['credit_card_number'])) {
360 if (!empty($values['credit_card_number']) &&
361 !CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
362 ) {
363 $errors['credit_card_number'] = ts('Please enter a valid Card Number');
364 }
365 if (!empty($values['cvv2']) &&
366 !CRM_Utils_Rule::cvv($values['cvv2'], $values['credit_card_type'])
367 ) {
368 $errors['cvv2'] = ts('Please enter a valid Card Verification Number');
369 }
370 }
371 }
372
373 /**
374 * Map address fields.
375 *
376 * @param int $id
377 * @param array $src
378 * @param array $dst
379 * @param bool $reverse
380 */
381 public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
382 static $map = NULL;
383 if (!$map) {
384 $map = array(
385 'first_name' => 'billing_first_name',
386 'middle_name' => 'billing_middle_name',
387 'last_name' => 'billing_last_name',
388 'email' => "email-$id",
389 'street_address' => "billing_street_address-$id",
390 'supplemental_address_1' => "billing_supplemental_address_1-$id",
391 'city' => "billing_city-$id",
392 'state_province' => "billing_state_province-$id",
393 'postal_code' => "billing_postal_code-$id",
394 'country' => "billing_country-$id",
395 'contactID' => 'contact_id',
396 );
397 }
398
399 foreach ($map as $n => $v) {
400 if (!$reverse) {
401 if (isset($src[$n])) {
402 $dst[$v] = $src[$n];
403 }
404 }
405 else {
406 if (isset($src[$v])) {
407 $dst[$n] = $src[$v];
408 }
409 }
410 }
411 }
412
413 /**
414 * Get the credit card expiration month.
415 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
416 * See CRM-9017
417 *
418 * @param $src
419 *
420 * @return int
421 */
422 public static function getCreditCardExpirationMonth($src) {
423 if ($month = CRM_Utils_Array::value('M', $src['credit_card_exp_date'])) {
424 return $month;
425 }
426
427 return CRM_Utils_Array::value('m', $src['credit_card_exp_date']);
428 }
429
430 /**
431 * Get the credit card expiration year.
432 * The date format for this field should typically be "M Y" (ex: Feb 2011) or "m Y" (02 2011)
433 * This function exists only to make it consistent with getCreditCardExpirationMonth
434 *
435 * @param $src
436 *
437 * @return int
438 */
439 public static function getCreditCardExpirationYear($src) {
440 return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
441 }
442
443 }