Merge pull request #8972 from liedekef/customfields
[civicrm-core.git] / CRM / Contribute / Form / AbstractEditPayment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 usefusul, 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-2016
32 */
33
34 /**
35 * This class generates form components for processing a contribution
36 * CRM-16229 - During the event registration bulk action via search we
37 * need to inherit CRM_Contact_Form_Task so that we can inherit functions
38 * like getContactIds and make use of controller state. But this is not possible
39 * because CRM_Event_Form_Participant inherits this class.
40 * Ideal situation would be something like
41 * CRM_Event_Form_Participant extends CRM_Contact_Form_Task,
42 * CRM_Contribute_Form_AbstractEditPayment
43 * However this is not possible. Currently PHP does not support multiple
44 * inheritance. So work around solution is to extend this class with
45 * CRM_Contact_Form_Task which further extends CRM_Core_Form.
46 *
47 */
48 class CRM_Contribute_Form_AbstractEditPayment extends CRM_Contact_Form_Task {
49 public $_mode;
50
51 public $_action;
52
53 public $_bltID;
54
55 public $_fields = array();
56
57 /**
58 * @var array current payment processor including a copy of the object in 'object' key
59 */
60 public $_paymentProcessor;
61
62 /**
63 * Available recurring processors.
64 *
65 * @var array
66 */
67 public $_recurPaymentProcessors = array();
68
69 /**
70 * Array of processor options in the format id => array($id => $label)
71 * WARNING it appears that the format used to differ to this and there are places in the code that
72 * expect the old format. $this->_paymentProcessors provides the additional data which this
73 * array seems to have provided in the past
74 * @var array
75 */
76 public $_processors;
77
78 /**
79 * Available payment processors with full details including the key 'object' indexed by their id
80 * @var array
81 */
82 protected $_paymentProcessors = array();
83
84 /**
85 * Instance of the payment processor object.
86 *
87 * @var CRM_Core_Payment
88 */
89 protected $_paymentObject;
90
91 /**
92 * The id of the contribution that we are processing.
93 *
94 * @var int
95 */
96 public $_id;
97
98 /**
99 * The id of the premium that we are proceessing.
100 *
101 * @var int
102 */
103 public $_premiumID = NULL;
104
105 /**
106 * @var CRM_Contribute_DAO_ContributionProduct
107 */
108 public $_productDAO = NULL;
109
110 /**
111 * The id of the note
112 *
113 * @var int
114 */
115 public $_noteID;
116
117 /**
118 * The id of the contact associated with this contribution
119 *
120 * @var int
121 */
122 public $_contactID;
123
124 /**
125 * The id of the pledge payment that we are processing
126 *
127 * @var int
128 */
129 public $_ppID;
130
131 /**
132 * The id of the pledge that we are processing
133 *
134 * @var int
135 */
136 public $_pledgeID;
137
138 /**
139 * Is this contribution associated with an online
140 * financial transaction
141 *
142 * @var boolean
143 */
144 public $_online = FALSE;
145
146 /**
147 * Stores all product option
148 *
149 * @var array
150 */
151 public $_options;
152
153 /**
154 * Stores the honor id
155 *
156 * @var int
157 */
158 public $_honorID = NULL;
159
160 /**
161 * Store the financial Type ID
162 *
163 * @var array
164 */
165 public $_contributionType;
166
167 /**
168 * The contribution values if an existing contribution
169 */
170 public $_values;
171
172 /**
173 * The pledge values if this contribution is associated with pledge
174 */
175 public $_pledgeValues;
176
177 public $_contributeMode = 'direct';
178
179 public $_context;
180
181 public $_compId;
182
183 /**
184 * Store the line items if price set used.
185 */
186 public $_lineItems;
187
188 /**
189 * Is this a backoffice form
190 * (this will affect whether paypal express code is displayed)
191 * @var bool
192 */
193 public $isBackOffice = TRUE;
194
195 protected $_formType;
196
197 /**
198 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
199 * be all in this array in order like
200 * 'credit_card' => array('credit_card_number' ...
201 * 'billing_details' => array('first_name' ...
202 *
203 * such that both the fields and the order can be more easily altered by payment processors & other extensions
204 * @var array
205 */
206 public $billingFieldSets = array();
207
208 /**
209 * Pre process function with common actions.
210 */
211 public function preProcess() {
212 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
213 $this->assign('contactID', $this->_contactID);
214 CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $this->_contactID));
215 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
216 }
217
218 /**
219 * @param int $id
220 */
221 public function showRecordLinkMesssage($id) {
222 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
223 if (CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name') == 'Partially paid') {
224 if ($pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
225 $recordPaymentLink = CRM_Utils_System::url('civicrm/payment',
226 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
227 );
228 CRM_Core_Session::setStatus(ts('Please use the <a href="%1">Record Payment</a> form if you have received an additional payment for this Partially paid contribution record.', array(1 => $recordPaymentLink)), ts('Notice'), 'alert');
229 }
230 }
231 }
232
233 /**
234 * @param int $id
235 * @param $values
236 */
237 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
238 $ids = array();
239 $params = array('id' => $id);
240 CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
241
242 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
243 $this->_online = FALSE;
244 $fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
245 if (!empty($fids['financialTrxnId'])) {
246 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
247 }
248
249 // Also don't allow user to update some fields for recurring contributions.
250 if (!$this->_online) {
251 $this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
252 }
253
254 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
255
256 //to get note id
257 $daoNote = new CRM_Core_BAO_Note();
258 $daoNote->entity_table = 'civicrm_contribution';
259 $daoNote->entity_id = $id;
260 if ($daoNote->find(TRUE)) {
261 $this->_noteID = $daoNote->id;
262 $values['note'] = $daoNote->note;
263 }
264 $this->_contributionType = $values['financial_type_id'];
265 }
266
267 /**
268 * @param string $type
269 * Eg 'Contribution'.
270 * @param string $subType
271 * @param int $entityId
272 */
273 public function applyCustomData($type, $subType, $entityId) {
274 $this->set('type', $type);
275 $this->set('subType', $subType);
276 $this->set('entityId', $entityId);
277
278 CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
279 CRM_Custom_Form_CustomData::buildQuickForm($this);
280 CRM_Custom_Form_CustomData::setDefaultValues($this);
281 }
282
283 /**
284 * @param int $id
285 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
286 */
287 public function assignPremiumProduct($id) {
288 $sql = "
289 SELECT *
290 FROM civicrm_contribution_product
291 WHERE contribution_id = {$id}
292 ";
293 $dao = CRM_Core_DAO::executeQuery($sql,
294 CRM_Core_DAO::$_nullArray
295 );
296 if ($dao->fetch()) {
297 $this->_premiumID = $dao->id;
298 $this->_productDAO = $dao;
299 }
300 $dao->free();
301 }
302
303 /**
304 * @return array
305 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
306 * @throws Exception
307 */
308 public function getValidProcessors() {
309 $defaultID = NULL;
310 $capabilities = array('BackOffice');
311 if ($this->_mode) {
312 $capabilities[] = (ucfirst($this->_mode) . 'Mode');
313 }
314 $processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
315 return $processors;
316
317 }
318
319 /**
320 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
321 */
322 public function assignProcessors() {
323 //ensure that processor has a valid config
324 //only valid processors get display to user
325
326 if ($this->_mode) {
327 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('FutureRecurStartDate')));
328 $this->_paymentProcessors = $this->getValidProcessors();
329 if (!isset($this->_paymentProcessor['id'])) {
330 // if the payment processor isn't set yet (as indicated by the presence of an id,) we'll grab the first one which should be the default
331 $this->_paymentProcessor = reset($this->_paymentProcessors);
332 }
333 if (empty($this->_paymentProcessors)) {
334 throw new CRM_Core_Exception(ts('You will need to configure the %1 settings for your Payment Processor before you can submit a credit card transactions.', array(1 => $this->_mode)));
335 }
336 $this->_processors = array();
337 foreach ($this->_paymentProcessors as $id => $processor) {
338 // @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
339 // However the function $this->getValidProcessors() is expected to only return the processors relevant
340 // to the mode (using the actual id - ie. the id of the test processor for the test processor).
341 // for some reason there was a need to filter here per commit history - but this indicates a problem
342 // somewhere else.
343 if ($processor['is_test'] == ($this->_mode == 'test')) {
344 $this->_processors[$id] = ts($processor['name']);
345 if (!empty($processor['description'])) {
346 $this->_processors[$id] .= ' : ' . ts($processor['description']);
347 }
348 if ($processor['is_recur']) {
349 $this->_recurPaymentProcessors[$id] = $this->_processors[$id];
350 }
351 }
352 }
353 CRM_Financial_Form_Payment::addCreditCardJs($id);
354 }
355 $this->assign('recurringPaymentProcessorIds',
356 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
357 );
358
359 // this required to show billing block
360 // @todo remove this assignment the billing block is now designed to be always included but will not show fieldsets unless those sets of fields are assigned
361 $this->assign_by_ref('paymentProcessor', $processor);
362 }
363
364 /**
365 * Get current currency from DB or use default currency.
366 *
367 * @param $submittedValues
368 *
369 * @return mixed
370 */
371 public function getCurrency($submittedValues) {
372 $config = CRM_Core_Config::singleton();
373
374 $currentCurrency = CRM_Utils_Array::value('currency',
375 $this->_values,
376 $config->defaultCurrency
377 );
378
379 // use submitted currency if present else use current currency
380 $result = CRM_Utils_Array::value('currency',
381 $submittedValues,
382 $currentCurrency
383 );
384 return $result;
385 }
386
387 /**
388 * @param int $financialTypeId
389 *
390 * @return array
391 */
392 public function getFinancialAccounts($financialTypeId) {
393 $financialAccounts = array();
394 CRM_Core_PseudoConstant::populate($financialAccounts,
395 'CRM_Financial_DAO_EntityFinancialAccount',
396 $all = TRUE,
397 $retrieve = 'financial_account_id',
398 $filter = NULL,
399 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
400 return $financialAccounts;
401 }
402
403 /**
404 * @param int $financialTypeId
405 * @param int $relationTypeId
406 *
407 * @return mixed
408 */
409 public function getFinancialAccount($financialTypeId, $relationTypeId) {
410 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
411 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
412 }
413
414 public function preProcessPledge() {
415 //get the payment values associated with given pledge payment id OR check for payments due.
416 $this->_pledgeValues = array();
417 if ($this->_ppID) {
418 $payParams = array('id' => $this->_ppID);
419
420 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
421 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
422 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
423 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
424
425 //get all status
426 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
427 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
428 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
429 }
430
431 //get the pledge values associated with given pledge payment.
432
433 $ids = array();
434 $pledgeParams = array('id' => $this->_pledgeID);
435 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
436 $this->assign('ppID', $this->_ppID);
437 }
438 else {
439 // Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
440 if (isset($this->_contactID)) {
441 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
442
443 if (!empty($contactPledges)) {
444 $payments = $paymentsDue = NULL;
445 $multipleDue = FALSE;
446 foreach ($contactPledges as $key => $pledgeId) {
447 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
448 if ($payments) {
449 if ($paymentsDue) {
450 $multipleDue = TRUE;
451 break;
452 }
453 else {
454 $paymentsDue = $payments;
455 }
456 }
457 }
458 if ($multipleDue) {
459 // Show link to pledge tab since more than one pledge has a payment due
460 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
461 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
462 );
463 CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)), ts('Notice'), 'alert');
464 }
465 elseif ($paymentsDue) {
466 // Show user link to oldest Pending or Overdue pledge payment
467 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
468 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
469 if ($this->_mode) {
470 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
471 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
472 );
473 }
474 else {
475 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
476 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
477 );
478 }
479 CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', array(
480 1 => $ppUrl,
481 2 => $ppAmountDue,
482 3 => $ppSchedDate,
483 )), ts('Notice'), 'alert');
484 }
485 }
486 }
487 }
488 }
489
490 /**
491 * @param array $submittedValues
492 *
493 * @return mixed
494 */
495 public function unsetCreditCardFields($submittedValues) {
496 //Offline Contribution.
497 $unsetParams = array(
498 'payment_processor_id',
499 "email-{$this->_bltID}",
500 'hidden_buildCreditCard',
501 'hidden_buildDirectDebit',
502 'billing_first_name',
503 'billing_middle_name',
504 'billing_last_name',
505 'street_address-5',
506 "city-{$this->_bltID}",
507 "state_province_id-{$this->_bltID}",
508 "postal_code-{$this->_bltID}",
509 "country_id-{$this->_bltID}",
510 'credit_card_number',
511 'cvv2',
512 'credit_card_exp_date',
513 'credit_card_type',
514 );
515 foreach ($unsetParams as $key) {
516 if (isset($submittedValues[$key])) {
517 unset($submittedValues[$key]);
518 }
519 }
520 return $submittedValues;
521 }
522
523 /**
524 * Common block for setting up the parts of a form that relate to credit / debit card
525 * @throws Exception
526 */
527 protected function assignPaymentRelatedVariables() {
528 try {
529 if ($this->_contactID) {
530 list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
531 $this->assign('displayName', $this->userDisplayName);
532 }
533 if ($this->_mode) {
534 $this->assignProcessors();
535
536 $this->assignBillingType();
537
538 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor, FALSE, TRUE);
539 }
540 }
541 catch (CRM_Core_Exception $e) {
542 CRM_Core_Error::fatal($e->getMessage());
543 }
544 }
545
546 /**
547 * Begin post processing.
548 *
549 * This function aims to start to bring together common postProcessing functions.
550 *
551 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
552 * access this function.
553 */
554 protected function beginPostProcess() {
555 if ($this->_mode) {
556 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment(
557 $this->_params['payment_processor_id'],
558 ($this->_mode == 'test')
559 );
560 if (in_array('credit_card_exp_date', array_keys($this->_params))) {
561 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
562 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
563 }
564 $this->assign('credit_card_exp_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format($this->_params['credit_card_exp_date'])));
565 $this->assign('credit_card_number',
566 CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
567 );
568 $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $this->_params));
569 }
570 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
571 }
572
573
574 /**
575 * Add the billing address to the contact who paid.
576 *
577 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
578 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
579 * for pay later.
580 */
581 protected function processBillingAddress() {
582 $fields = array();
583
584 $fields['email-Primary'] = 1;
585 $this->_params['email-5'] = $this->_params['email-Primary'] = $this->_contributorEmail;
586 // now set the values for the billing location.
587 foreach (array_keys($this->_fields) as $name) {
588 $fields[$name] = 1;
589 }
590
591 $fields["address_name-{$this->_bltID}"] = 1;
592
593 //ensure we don't over-write the payer's email with the member's email
594 if ($this->_contributorContactID == $this->_contactID) {
595 $fields["email-{$this->_bltID}"] = 1;
596 }
597
598 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($this->_params, $this->_bltID);
599 $fields = $this->formatParamsForPaymentProcessor($fields);
600
601 if ($hasBillingField) {
602 $addressParams = array_merge($this->_params, $addressParams);
603 // CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
604 // Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
605 // Note this source field is covered by a unit test.
606 if (isset($addressParams['source'])) {
607 unset($addressParams['source']);
608 }
609 //here we are setting up the billing contact - if different from the member they are already created
610 // but they will get billing details assigned
611 CRM_Contact_BAO_Contact::createProfileContact($addressParams, $fields,
612 $this->_contributorContactID, NULL, NULL,
613 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')
614 );
615 }
616 }
617
618 /**
619 * Get default values for billing fields.
620 *
621 * @todo this function still replicates code in several other places in the code.
622 *
623 * Also - the call to getProfileDefaults possibly covers the state_province & country already.
624 *
625 * @param $defaults
626 *
627 * @return array
628 */
629 protected function getBillingDefaults($defaults) {
630 // set default country from config if no country set
631 $config = CRM_Core_Config::singleton();
632 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
633 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
634 }
635
636 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
637 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
638 }
639
640 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
641 return array_merge($defaults, $billingDefaults);
642 }
643
644 }