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