CRM-15555 break sharing of parent class between unrelated forms
[civicrm-core.git] / CRM / Contribute / Form / AbstractEditPayment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for processing a contribution
38 *
39 */
40class CRM_Contribute_Form_AbstractEditPayment extends CRM_Core_Form {
41 public $_mode;
42
43 public $_action;
44
45 public $_bltID;
46
47 public $_fields;
48
49 public $_paymentProcessor;
50 public $_recurPaymentProcessors;
51
dc913073
EM
52 /**
53 * array of processor options in the format id => array($id => $label)
54 * WARNING it appears that the format used to differ to this and there are places in the code that
55 * expect the old format. $this->_paymentProcessors provides the additional data which this
56 * array seems to have provided in the past
57 * @var array
58 */
6a488035
TO
59 public $_processors;
60
61 /**
dc913073
EM
62 * available payment processors with full details including the key 'object' indexed by their id
63 * @var array
64 */
65 protected $_paymentProcessors = array();
66 /**
67 * the id of the contribution that we are processing
6a488035
TO
68 *
69 * @var int
70 * @public
71 */
72 public $_id;
73
74 /**
75 * the id of the premium that we are proceessing
76 *
77 * @var int
78 * @public
79 */
80 public $_premiumID = NULL;
4691b077
EM
81
82 /**
83 * @var CRM_Contribute_DAO_ContributionProduct
84 */
6a488035
TO
85 public $_productDAO = NULL;
86
87 /**
88 * the id of the note
89 *
90 * @var int
91 * @public
92 */
93 public $_noteID;
94
95 /**
96 * the id of the contact associated with this contribution
97 *
98 * @var int
99 * @public
100 */
101 public $_contactID;
102
103 /**
104 * the id of the pledge payment that we are processing
105 *
106 * @var int
107 * @public
108 */
109 public $_ppID;
110
111 /**
112 * the id of the pledge that we are processing
113 *
114 * @var int
115 * @public
116 */
117 public $_pledgeID;
118
119 /**
120 * is this contribution associated with an online
121 * financial transaction
122 *
123 * @var boolean
124 * @public
125 */
126 public $_online = FALSE;
127
128 /**
129 * Stores all product option
130 *
131 * @var array
132 * @public
133 */
134 public $_options;
135
136 /**
137 * stores the honor id
138 *
139 * @var int
140 * @public
141 */
142 public $_honorID = NULL;
143
144 /**
dde5a0ef 145 * Store the financial Type ID
6a488035
TO
146 *
147 * @var array
148 */
149 public $_contributionType;
150
151 /**
152 * The contribution values if an existing contribution
153 */
154 public $_values;
155
156 /**
157 * The pledge values if this contribution is associated with pledge
158 */
159 public $_pledgeValues;
160
161 public $_contributeMode = 'direct';
162
163 public $_context;
164
165 public $_compId;
166
167 /*
168 * Store the line items if price set used.
169 */
170 public $_lineItems;
171
0be0b79d
EM
172 /**
173 * Is this a backoffice form
174 * (this will affect whether paypal express code is displayed)
175 * @var bool
176 */
177 public $isBackOffice = TRUE;
178
6a488035 179 protected $_formType;
dde5a0ef
EM
180
181 /**
182 * @var mystery variable screaming out for documentation
183 */
6a488035
TO
184 protected $_cdType;
185
dde5a0ef
EM
186 /**
187 * array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
188 * be all in this array in order like
189 * 'credit_card' => array('credit_card_number' ...
190 * 'billing_details' => array('first_name' ...
191 *
192 * such that both the fields and the order can be more easily altered by payment processors & other extensions
193 * @var array
194 */
195 public $billingFieldSets = array();
196
186c9c17
EM
197 /**
198 * @param $id
199 */
d5397f2f
PJ
200 public function showRecordLinkMesssage($id) {
201 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
202 if (CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name') == 'Partially paid') {
203 if ($pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
204 $recordPaymentLink = CRM_Utils_System::url('civicrm/payment',
205 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
206 );
207 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');
208 }
209 }
210 }
211
186c9c17
EM
212 /**
213 * @param $id
214 * @param $values
215 */
6a488035
TO
216 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
217 $ids = array();
218 $params = array('id' => $id);
219 CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
220
221 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
222 $this->_online = FALSE;
223 $fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
a7488080 224 if (!empty($fids['financialTrxnId'])) {
6a488035
TO
225 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
226 }
eea16664 227
6a488035
TO
228 // Also don't allow user to update some fields for recurring contributions.
229 if (!$this->_online) {
230 $this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
231 }
eea16664 232
6a488035
TO
233 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
234
6a488035
TO
235 //to get note id
236 $daoNote = new CRM_Core_BAO_Note();
237 $daoNote->entity_table = 'civicrm_contribution';
238 $daoNote->entity_id = $id;
239 if ($daoNote->find(TRUE)) {
240 $this->_noteID = $daoNote->id;
241 $values['note'] = $daoNote->note;
242 }
243 $this->_contributionType = $values['financial_type_id'];
6a488035
TO
244 }
245
246 /**
247 * @param string $type eg 'Contribution'
248 * @param string $subType
249 * @param int $entityId
250 */
251 public function applyCustomData($type, $subType, $entityId) {
252 $this->set('type', $type);
253 $this->set('subType', $subType);
254 $this->set('entityId', $entityId);
255
256 CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
257 CRM_Custom_Form_CustomData::buildQuickForm($this);
258 CRM_Custom_Form_CustomData::setDefaultValues($this);
259 }
260
4691b077
EM
261 /**
262 * @param $id
263 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
264 */
6a488035
TO
265 public function assignPremiumProduct($id) { //to get Premium id
266 $sql = "
267SELECT *
268FROM civicrm_contribution_product
269WHERE contribution_id = {$id}
270";
271 $dao = CRM_Core_DAO::executeQuery($sql,
272 CRM_Core_DAO::$_nullArray
273 );
274 if ($dao->fetch()) {
275 $this->_premiumID = $dao->id;
276 $this->_productDAO = $dao;
277 }
278 $dao->free();
279 }
280
281 /**
282 * This function process contribution related objects.
03110609
EM
283 *
284 * @param integer $contributionId
285 * @param integer $statusId
286 * @param integer|null $previousStatusId
287 *
288 * @return null|string
6a488035
TO
289 */
290 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL) {
291 $statusMsg = NULL;
292 if (!$contributionId || !$statusId) {
293 return $statusMsg;
294 }
295
296 $params = array(
297 'contribution_id' => $contributionId,
298 'contribution_status_id' => $statusId,
299 'previous_contribution_status_id' => $previousStatusId,
300 );
301
302 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
303
304 if (!is_array($updateResult) ||
305 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
306 !is_array($updatedComponents) ||
307 empty($updatedComponents)
308 ) {
309 return $statusMsg;
310 }
311
312 // get the user display name.
313 $sql = "
314 SELECT display_name as displayName
315 FROM civicrm_contact
316LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
317 WHERE civicrm_contribution.id = {$contributionId}";
318 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
319
320 // get the status message for user.
321 foreach ($updatedComponents as $componentName => $updatedStatusId) {
322
323 if ($componentName == 'CiviMember') {
324 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
325 CRM_Member_PseudoConstant::membershipStatus()
326 );
327 if ($updatedStatusName == 'Cancelled') {
328 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
329 }
330 elseif ($updatedStatusName == 'Expired') {
331 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
332 }
d008a264 333 else {
13299a2b
JM
334 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
335 if ($endDate) {
d008a264
JM
336 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
337 array(
338 1 => $userDisplayName,
339 2 => $endDate
340 )
341 );
342 }
6a488035
TO
343 }
344 }
345
346 if ($componentName == 'CiviEvent') {
347 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
348 CRM_Event_PseudoConstant::participantStatus()
349 );
350 if ($updatedStatusName == 'Cancelled') {
351 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
352 }
353 elseif ($updatedStatusName == 'Registered') {
354 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
355 }
356 }
357
358 if ($componentName == 'CiviPledge') {
359 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
360 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
361 );
362 if ($updatedStatusName == 'Cancelled') {
363 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
364 }
365 elseif ($updatedStatusName == 'Failed') {
366 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
367 }
368 elseif ($updatedStatusName == 'Completed') {
369 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
370 }
371 }
372 }
373
374 return $statusMsg;
375 }
376
377 /**
dc913073 378 * @return array of valid processors. The array resembles the DB table but also has 'object' as a key
fbcb6fba
EM
379 * @throws Exception
380 */
381 public function getValidProcessors() {
fbcb6fba
EM
382 $defaultID = NULL;
383 $capabilities = array('BackOffice');
384 if ($this->_mode == 'live') {
385 $capabilities[] = 'LiveMode';
386 }
387 $processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
44b6505d
EM
388 return $processors;
389
6a488035
TO
390 }
391
392 /**
393 * Assign billing type id to bltID
394 *
44b6505d 395 * @throws CRM_Core_Exception
6a488035
TO
396 * @return void
397 */
398 public function assignBillingType() {
180409a4 399 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
400 $this->_bltID = array_search('Billing', $locationTypes);
401 if (!$this->_bltID) {
44b6505d 402 throw new CRM_Core_Exception(ts('Please set a location type of %1', array(1 => 'Billing')));
6a488035
TO
403 }
404 $this->set('bltID', $this->_bltID);
405 $this->assign('bltID', $this->_bltID);
406 }
407
408 /**
409 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
410 */
411 public function assignProcessors() {
412 //ensure that processor has a valid config
413 //only valid processors get display to user
44b6505d 414
6a488035 415 if ($this->_mode) {
fbcb6fba 416 $this->assign(CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('supportsFutureRecurStartDate')), TRUE);
dc913073
EM
417 $this->_paymentProcessors = $this->getValidProcessors();
418 if (!isset($this->_paymentProcessor['id'])) {
419 // 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
420 $this->_paymentProcessor = reset($this->_paymentProcessors);
421 }
422 if (empty($this->_paymentProcessors)) {
44b6505d
EM
423 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)));
424 }
425 $this->_processors = array();
dc913073 426 foreach ($this->_paymentProcessors as $id => $processor) {
44b6505d
EM
427 $this->_processors[$id] = ts($processor['name']);
428 }
6a488035
TO
429 //get the valid recurring processors.
430 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
431 $this->_recurPaymentProcessors = array_intersect_assoc($this->_processors, $recurring);
432 }
433 $this->assign('recurringPaymentProcessorIds',
434 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
435 );
436
437 // this required to show billing block
03110609 438 // @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
44b6505d 439 $this->assign_by_ref('paymentProcessor', $processor);
6a488035
TO
440 }
441
186c9c17
EM
442 /**
443 * @param $submittedValues
444 *
445 * @return mixed
446 */
6a488035
TO
447 public function getCurrency($submittedValues) { // get current currency from DB or use default currency
448 $config = CRM_Core_Config::singleton();
449
450 $currentCurrency = CRM_Utils_Array::value('currency',
451 $this->_values,
452 $config->defaultCurrency
453 );
454
455 // use submitted currency if present else use current currency
456 $result = CRM_Utils_Array::value('currency',
457 $submittedValues,
458 $currentCurrency
459 );
460 return $result;
461 }
462
186c9c17
EM
463 /**
464 * @param $financialTypeId
465 *
466 * @return array
467 */
6a488035
TO
468 public function getFinancialAccounts($financialTypeId) {
469 $financialAccounts = array();
470 CRM_Core_PseudoConstant::populate($financialAccounts,
471 'CRM_Financial_DAO_EntityFinancialAccount',
472 $all = TRUE,
473 $retrieve = 'financial_account_id',
474 $filter = NULL,
475 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
476 return $financialAccounts;
477 }
478
186c9c17
EM
479 /**
480 * @param $financialTypeId
481 * @param $relationTypeId
482 *
483 * @return mixed
484 */
6a488035
TO
485 public function getFinancialAccount($financialTypeId, $relationTypeId) {
486 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
487 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
488 }
489
490 public function preProcessPledge() {
491 //get the payment values associated with given pledge payment id OR check for payments due.
492 $this->_pledgeValues = array();
493 if ($this->_ppID) {
494 $payParams = array('id' => $this->_ppID);
495
496 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
497 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
498 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
499 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
500
501 //get all status
502 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
503 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
504 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
505 }
506
507 //get the pledge values associated with given pledge payment.
508
509 $ids = array();
510 $pledgeParams = array('id' => $this->_pledgeID);
511 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
512 $this->assign('ppID', $this->_ppID);
513 }
514 else {
515 // 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
516 if (isset($this->_contactID)) {
517 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
518
519 if (!empty($contactPledges)) {
520 $payments = $paymentsDue = NULL;
521 $multipleDue = FALSE;
522 foreach ($contactPledges as $key => $pledgeId) {
523 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
524 if ($payments) {
525 if ($paymentsDue) {
526 $multipleDue = TRUE;
527 break;
528 }
529 else {
530 $paymentsDue = $payments;
531 }
532 }
533 }
534 if ($multipleDue) {
535 // Show link to pledge tab since more than one pledge has a payment due
536 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
537 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
538 );
539 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');
540 }
541 elseif ($paymentsDue) {
542 // Show user link to oldest Pending or Overdue pledge payment
543 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
544 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
545 if ($this->_mode) {
546 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
547 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
548 );
549 }
550 else {
551 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
552 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
553 );
554 }
555 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(
556 1 => $ppUrl,
557 2 => $ppAmountDue,
558 3 => $ppSchedDate
559 )), ts('Notice'), 'alert');
560 }
561 }
562 }
563 }
564 }
565
186c9c17
EM
566 /**
567 * @param $submittedValues
568 *
569 * @return mixed
570 */
6a488035
TO
571 public function unsetCreditCardFields($submittedValues) {
572 //Offline Contribution.
573 $unsetParams = array(
574 'payment_processor_id',
575 "email-{$this->_bltID}",
576 'hidden_buildCreditCard',
577 'hidden_buildDirectDebit',
578 'billing_first_name',
579 'billing_middle_name',
580 'billing_last_name',
581 'street_address-5',
582 "city-{$this->_bltID}",
583 "state_province_id-{$this->_bltID}",
584 "postal_code-{$this->_bltID}",
585 "country_id-{$this->_bltID}",
586 'credit_card_number',
587 'cvv2',
588 'credit_card_exp_date',
589 'credit_card_type',
590 );
591 foreach ($unsetParams as $key) {
592 if (isset($submittedValues[$key])) {
593 unset($submittedValues[$key]);
594 }
595 }
596 return $submittedValues;
597 }
598
cc984198
EM
599 /**
600 * common block for setting up the parts of a form that relate to credit / debit card
601 * @throws Exception
602 */
603 protected function assignPaymentRelatedVariables() {
604 try {
99efbbf8
EM
605 if ($this->_contactID) {
606 list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
607 $this->assign('displayName', $this->userDisplayName);
608 }
cc984198
EM
609 if ($this->_mode) {
610 $this->assignProcessors();
cc984198
EM
611
612 $this->assignBillingType();
613
614 $this->_fields = array();
615 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
616 }
617 }
618 catch (CRM_Core_Exception $e) {
619 CRM_Core_Error::fatal($e->getMessage());
620 }
621 }
6a488035 622}