Merge pull request #7203 from civicrm/eileenmcnaughton-patch-1
[civicrm-core.git] / CRM / Contribute / Form / Contribution.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 * This class generates form components for processing a contribution.
30 */
31 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
32 /**
33 * The id of the contribution that we are processing.
34 *
35 * @var int
36 */
37 public $_id;
38
39 /**
40 * The id of the premium that we are processing.
41 *
42 * @var int
43 */
44 public $_premiumID = NULL;
45
46 /**
47 * @var CRM_Contribute_DAO_ContributionProduct
48 */
49 public $_productDAO = NULL;
50
51 /**
52 * The id of the note.
53 *
54 * @var int
55 */
56 public $_noteID;
57
58 /**
59 * The id of the contact associated with this contribution.
60 *
61 * @var int
62 */
63 public $_contactID;
64
65 /**
66 * The id of the pledge payment that we are processing.
67 *
68 * @var int
69 */
70 public $_ppID;
71
72 /**
73 * The id of the pledge that we are processing.
74 *
75 * @var int
76 */
77 public $_pledgeID;
78
79 /**
80 * Is this contribution associated with an online.
81 * financial transaction
82 *
83 * @var boolean
84 */
85 public $_online = FALSE;
86
87 /**
88 * Stores all product options.
89 *
90 * @var array
91 */
92 public $_options;
93
94 /**
95 * Storage of parameters from form
96 *
97 * @var array
98 */
99 public $_params;
100
101 /**
102 * Store the contribution Type ID
103 *
104 * @var array
105 */
106 public $_contributionType;
107
108 /**
109 * The contribution values if an existing contribution
110 */
111 public $_values;
112
113 /**
114 * The pledge values if this contribution is associated with pledge
115 */
116 public $_pledgeValues;
117
118 public $_contributeMode = 'direct';
119
120 public $_context;
121
122 /**
123 * Parameter with confusing name.
124 * @todo what is it?
125 * @var string
126 */
127 public $_compContext;
128
129 public $_compId;
130
131 /**
132 * Possible From email addresses
133 * @var array
134 */
135 public $_fromEmails;
136
137 /**
138 * ID of from email
139 * @var integer
140 */
141 public $fromEmailId;
142
143 /**
144 * Store the line items if price set used.
145 */
146 public $_lineItems;
147
148 /**
149 * Line item
150 * @todo explain why we use lineItem & lineItems
151 * @var array
152 */
153 public $_lineItem;
154
155 /**
156 * @var array soft credit info
157 */
158 public $_softCreditInfo;
159
160 protected $_formType;
161
162 /**
163 * @todo what on earth does cdType stand for????
164 * @var
165 */
166 protected $_cdType;
167 public $_honoreeProfileType;
168
169 /**
170 * Array of billing panes to be displayed by billingBlock.tpl.
171 * Currently this is likely to look like
172 * array('Credit Card' => ts('Credit Card') or
173 * array('Direct Debit => ts('Direct Debit')
174 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
175 *
176 * @var array
177 */
178 public $billingPane = array();
179
180 /**
181 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
182 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
183 *
184 * @var array
185 */
186 public $_paymentFields = array();
187 /**
188 * Logged in user's email.
189 * @var string
190 */
191 public $userEmail;
192
193 /**
194 * Price set ID
195 * @var integer
196 */
197 public $_priceSetId;
198
199
200 /**
201 * Price set as an array
202 * @var array
203 */
204 public $_priceSet;
205
206 /**
207 * Form defaults
208 * @todo can we define this a as protected? can we define higher up the chain
209 * @var array
210 */
211 public $_defaults;
212
213 /**
214 * User display name
215 *
216 * @var string
217 */
218 public $userDisplayName;
219
220 /**
221 * Set variables up before form is built.
222 */
223 public function preProcess() {
224
225 // Check permission for action.
226 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
227 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
228 }
229
230 // @todo - if anyone ever figures out what this _cdType subroutine is about
231 // (or even if it still applies) please add comments!!!!!!!!!!
232 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
233 $this->assign('cdType', FALSE);
234 if ($this->_cdType) {
235 $this->assign('cdType', TRUE);
236 CRM_Custom_Form_CustomData::preProcess($this);
237 return;
238 }
239
240 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
241
242 // Get price set id.
243 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId);
245 $this->assign('priceSetId', $this->_priceSetId);
246
247 // Get the pledge payment id
248 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
249
250 // Get the contact id
251 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
252
253 // Get the action.
254 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
255 $this->assign('action', $this->_action);
256
257 // Get the contribution id if update
258 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
259 if (!empty($this->_id)) {
260 $this->assign('contribID', $this->_id);
261 }
262
263 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
264 $this->assign('context', $this->_context);
265
266 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
267
268 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
269
270 //set the contribution mode.
271 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
272
273 $this->assign('contributionMode', $this->_mode);
274 if ($this->_action & CRM_Core_Action::DELETE) {
275 return;
276 }
277
278 $this->assign('showCheckNumber', TRUE);
279
280 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
281 $this->assignPaymentRelatedVariables();
282
283 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
284 $this->preProcessPledge();
285 }
286
287 if ($this->_id) {
288 $this->showRecordLinkMesssage($this->_id);
289 }
290 $this->_values = array();
291
292 // Current contribution id.
293 if ($this->_id) {
294 $this->assignPremiumProduct($this->_id);
295 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
296 }
297
298 // when custom data is included in this page
299 if (!empty($_POST['hidden_custom'])) {
300 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
301 }
302
303 $this->_lineItems = array();
304 if ($this->_id) {
305 if (!empty($this->_compId) && $this->_compContext == 'participant') {
306 $this->assign('compId', $this->_compId);
307 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
308 }
309 else {
310 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
311 }
312 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
313 }
314
315 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
316
317 // Set title
318 if ($this->_mode) {
319 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
320 }
321 else {
322 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
323 }
324
325 if ($this->_id) {
326 CRM_Contribute_Form_SoftCredit::preprocess($this);
327 }
328 }
329
330 /**
331 * Set default values.
332 *
333 * @return array
334 */
335 public function setDefaultValues() {
336 if ($this->_cdType) {
337 // @todo document when this function would be called in this way
338 // (and whether it is valid or an overloading of this form).
339 return CRM_Custom_Form_CustomData::setDefaultValues($this);
340 }
341
342 $defaults = $this->_values;
343
344 // Set defaults for pledge payment.
345 if ($this->_ppID) {
346 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
347 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
348 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
349 $defaults['option_type'] = 1;
350 }
351
352 if ($this->_action & CRM_Core_Action::DELETE) {
353 return $defaults;
354 }
355
356 $defaults['frequency_interval'] = 1;
357 $defaults['frequency_unit'] = 'month';
358
359 // Set soft credit defaults.
360 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
361
362 if ($this->_mode) {
363 $config = CRM_Core_Config::singleton();
364 // Set default country from config if no country set.
365 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
366 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
367 }
368
369 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
370 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
371 }
372
373 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
374 $defaults = array_merge($defaults, $billingDefaults);
375 }
376
377 if ($this->_id) {
378 $this->_contactID = $defaults['contact_id'];
379 }
380
381 // Set $newCredit variable in template to control whether link to credit card mode is included.
382 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
383
384 // Fix the display of the monetary value, CRM-4038.
385 if (isset($defaults['total_amount'])) {
386 if (!empty($defaults['tax_amount'])) {
387 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
388 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
389 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
390 }
391 }
392 else {
393 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
394 }
395 }
396
397 if (isset($defaults['non_deductible_amount'])) {
398 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
399 }
400
401 if (isset($defaults['fee_amount'])) {
402 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
403 }
404
405 if (isset($defaults['net_amount'])) {
406 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
407 }
408
409 if ($this->_contributionType) {
410 $defaults['financial_type_id'] = $this->_contributionType;
411 }
412
413 if (empty($defaults['payment_instrument_id'])) {
414 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
415 }
416
417 if (!empty($defaults['is_test'])) {
418 $this->assign('is_test', TRUE);
419 }
420
421 $this->assign('showOption', TRUE);
422 // For Premium section.
423 if ($this->_premiumID) {
424 $this->assign('showOption', FALSE);
425 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
426 if (!$options) {
427 $this->assign('showOption', TRUE);
428 }
429 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
430 if ($options_key) {
431 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
432 }
433 else {
434 $defaults['product_name'] = array($this->_productDAO->product_id);
435 }
436 if ($this->_productDAO->fulfilled_date) {
437 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
438 }
439 }
440
441 if (isset($this->userEmail)) {
442 $this->assign('email', $this->userEmail);
443 }
444
445 if (!empty($defaults['is_pay_later'])) {
446 $this->assign('is_pay_later', TRUE);
447 }
448 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
449
450 $dates = array(
451 'receive_date',
452 'receipt_date',
453 'cancel_date',
454 'thankyou_date',
455 );
456 foreach ($dates as $key) {
457 if (!empty($defaults[$key])) {
458 list($defaults[$key], $defaults[$key . '_time'])
459 = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime');
460 }
461 }
462
463 if (!$this->_id && empty($defaults['receive_date'])) {
464 list($defaults['receive_date'],
465 $defaults['receive_date_time']
466 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
467 }
468
469 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
470 CRM_Utils_Array::value('receive_date_time', $defaults)
471 ));
472 $currency = CRM_Utils_Array::value('currency', $defaults);
473 $this->assign('currency', $currency);
474 // Hack to get currency info to the js layer. CRM-11440.
475 CRM_Utils_Money::format(1);
476 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
477 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
478
479 // Inherit campaign from pledge.
480 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
481 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
482 }
483
484 $this->_defaults = $defaults;
485 return $defaults;
486 }
487
488 /**
489 * Build the form object.
490 */
491 public function buildQuickForm() {
492 //@todo document the purpose of cdType (if still in use)
493 if ($this->_cdType) {
494 CRM_Custom_Form_CustomData::buildQuickForm($this);
495 return;
496 }
497 $allPanes = array();
498 //tax rate from financialType
499 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
500 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
501
502 // build price set form.
503 $buildPriceSet = FALSE;
504 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
505 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
506 $this->assign('invoicing', $invoicing);
507
508 // display tax amount on edit contribution page
509 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
510 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
511 }
512
513 if (empty($this->_lineItems) &&
514 ($this->_priceSetId || !empty($_POST['price_set_id']))
515 ) {
516 $buildPriceSet = TRUE;
517 $getOnlyPriceSetElements = TRUE;
518 if (!$this->_priceSetId) {
519 $this->_priceSetId = $_POST['price_set_id'];
520 $getOnlyPriceSetElements = FALSE;
521 }
522
523 $this->set('priceSetId', $this->_priceSetId);
524 CRM_Price_BAO_PriceSet::buildPriceSet($this);
525
526 // get only price set form elements.
527 if ($getOnlyPriceSetElements) {
528 return;
529 }
530 }
531 // use to build form during form rule.
532 $this->assign('buildPriceSet', $buildPriceSet);
533
534 $showAdditionalInfo = FALSE;
535
536 $defaults = $this->_values;
537 $additionalDetailFields = array(
538 'note',
539 'thankyou_date',
540 'invoice_id',
541 'non_deductible_amount',
542 'fee_amount',
543 'net_amount',
544 );
545 foreach ($additionalDetailFields as $key) {
546 if (!empty($defaults[$key])) {
547 $defaults['hidden_AdditionalDetail'] = 1;
548 break;
549 }
550 }
551
552 if ($this->_productDAO) {
553 if ($this->_productDAO->product_id) {
554 $defaults['hidden_Premium'] = 1;
555 }
556 }
557
558 if ($this->_noteID &&
559 isset($this->_values['note'])
560 ) {
561 $defaults['hidden_AdditionalDetail'] = 1;
562 }
563
564 $paneNames = array(
565 ts('Additional Details') => 'AdditionalDetail',
566 );
567
568 //Add Premium pane only if Premium is exists.
569 $dao = new CRM_Contribute_DAO_Product();
570 $dao->is_active = 1;
571
572 if ($dao->find(TRUE)) {
573 $paneNames[ts('Premium Information')] = 'Premium';
574 }
575
576 $billingPanes = array();
577 if ($this->_mode) {
578 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
579 $buildRecurBlock = TRUE;
580 foreach ($this->billingPane as $name => $label) {
581 if (!empty($this->billingFieldSets[$name]['fields'])) {
582 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
583 $billingPanes[$label] = $this->generatePane(CRM_Utils_String::convertStringToCamel($name), $defaults);
584 }
585 }
586 }
587 }
588
589 foreach ($paneNames as $name => $type) {
590 $allPanes[$name] = $this->generatePane($type, $defaults);
591 }
592 if (empty($this->_recurPaymentProcessors)) {
593 $buildRecurBlock = FALSE;
594 }
595 if ($this->_ppID) {
596 foreach ($this->_paymentProcessors as $processor) {
597 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
598 $buildRecurBlock = TRUE;
599 break;
600 }
601 $buildRecurBlock = FALSE;
602 }
603 }
604 if ($buildRecurBlock) {
605 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
606 $this->setDefaults(array('is_recur' => 0));
607 }
608 $this->assign('buildRecurBlock', $buildRecurBlock);
609 $qfKey = $this->controller->_key;
610 $this->assign('qfKey', $qfKey);
611 $this->assign('billingPanes', $billingPanes);
612 $this->assign('allPanes', $allPanes);
613
614 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
615
616 if ($this->_formType) {
617 $this->assign('formType', $this->_formType);
618 return;
619 }
620
621 $this->applyFilter('__ALL__', 'trim');
622
623 if ($this->_action & CRM_Core_Action::DELETE) {
624 $this->addButtons(array(
625 array(
626 'type' => 'next',
627 'name' => ts('Delete'),
628 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
629 'isDefault' => TRUE,
630 ),
631 array(
632 'type' => 'cancel',
633 'name' => ts('Cancel'),
634 ),
635 )
636 );
637 return;
638 }
639
640 //need to assign custom data type and subtype to the template
641 $this->assign('customDataType', 'Contribution');
642 $this->assign('customDataSubType', $this->_contributionType);
643 $this->assign('entityID', $this->_id);
644
645 if ($this->_context == 'standalone') {
646 $this->addEntityRef('contact_id', ts('Contact'), array(
647 'create' => TRUE,
648 'api' => array('extra' => array('email')),
649 ), TRUE);
650 }
651
652 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
653
654 $financialType = $this->add('select', 'financial_type_id',
655 ts('Financial Type'),
656 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
657 TRUE,
658 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
659 );
660 $paymentInstrument = FALSE;
661 if (!$this->_mode) {
662 $paymentInstrument = $this->add('select', 'payment_instrument_id',
663 ts('Paid By'),
664 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
665 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
666 );
667 }
668
669 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
670
671 //add receipt for offline contribution
672 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
673
674 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
675
676 $status = CRM_Contribute_PseudoConstant::contributionStatus();
677
678 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
679 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
680 if ($this->_ppID) {
681 foreach (array(
682 'Cancelled',
683 'Failed',
684 'In Progress',
685 ) as $suppress) {
686 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
687 }
688 }
689 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
690 $suppressFlag = FALSE;
691 if ($this->_id) {
692 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
693 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
694 $suppressFlag = TRUE;
695 }
696 }
697 if (!$suppressFlag) {
698 foreach (array(
699 'Overdue',
700 'In Progress',
701 ) as $suppress) {
702 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
703 }
704 }
705 else {
706 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
707 }
708 }
709
710 if ($this->_id) {
711 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
712 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
713 switch ($name) {
714 case 'Completed':
715 case 'Cancelled':
716 case 'Refunded':
717 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
718 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
719 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
720 break;
721
722 case 'Pending':
723 case 'In Progress':
724 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
725 break;
726
727 case 'Failed':
728 foreach (array(
729 'Pending',
730 'Refunded',
731 'Completed',
732 'In Progress',
733 'Cancelled',
734 ) as $suppress) {
735 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
736 }
737 break;
738 }
739 }
740 else {
741 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
742 }
743
744 $this->add('select', 'contribution_status_id',
745 ts('Contribution Status'),
746 $status,
747 FALSE
748 );
749
750 // add various dates
751 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
752
753 if ($this->_online) {
754 $this->assign('hideCalender', TRUE);
755 }
756 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
757
758 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
759 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
760
761 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
762
763 $recurJs = NULL;
764 if ($buildRecurBlock) {
765 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
766 }
767 $element = $this->add('select',
768 'payment_processor_id',
769 ts('Payment Processor'),
770 $this->_processors,
771 NULL,
772 $recurJs
773 );
774
775 if ($this->_online) {
776 $element->freeze();
777 }
778 $totalAmount = NULL;
779 if (empty($this->_lineItems)) {
780 $buildPriceSet = FALSE;
781 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
782 if (!empty($priceSets) && !$this->_ppID) {
783 $buildPriceSet = TRUE;
784 }
785
786 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
787 // and if we already have line items for that participant. CRM-5095
788 if ($buildPriceSet && $this->_id) {
789 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
790 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
791 $this->_id,
792 'id',
793 'contribution_id'
794 );
795 if ($pledgePaymentId) {
796 $buildPriceSet = FALSE;
797 }
798 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
799 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
800 if (!CRM_Utils_System::isNull($participantLI)) {
801 $buildPriceSet = FALSE;
802 }
803 }
804 }
805
806 $hasPriceSets = FALSE;
807 if ($buildPriceSet) {
808 $hasPriceSets = TRUE;
809 // CRM-16451: set financial type of 'Price Set' in back office contribution
810 // instead of selecting manually
811 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
812 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
813 array(
814 '' => ts('Choose price set'),
815 ) + $priceSets,
816 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
817 );
818 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
819 $element->freeze();
820 }
821 }
822 $this->assign('hasPriceSets', $hasPriceSets);
823 $currencyFreeze = FALSE;
824 if (!($this->_action & CRM_Core_Action::UPDATE)) {
825 if ($this->_online || $this->_ppID) {
826 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
827 'READONLY' => TRUE,
828 'style' => "background-color:#EBECE4",
829 ));
830 $optionTypes = array(
831 '1' => ts('Adjust Pledge Payment Schedule?'),
832 '2' => ts('Adjust Total Pledge Amount?'),
833 );
834 $this->addRadio('option_type',
835 NULL,
836 $optionTypes,
837 array(), '<br/>'
838 );
839
840 $currencyFreeze = TRUE;
841 }
842 }
843
844 $totalAmount = $this->addMoney('total_amount',
845 ts('Total Amount'),
846 ($hasPriceSets) ? FALSE : TRUE,
847 $attributes['total_amount'],
848 TRUE, 'currency', NULL, $currencyFreeze
849 );
850 }
851
852 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
853
854 // CRM-7362 --add campaigns.
855 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
856
857 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
858
859 $js = NULL;
860 if (!$this->_mode) {
861 $js = array('onclick' => "return verify( );");
862 }
863
864 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
865 'mailing_backend'
866 );
867 $this->assign('outBound_option', $mailingInfo['outBound_option']);
868
869 $this->addButtons(array(
870 array(
871 'type' => 'upload',
872 'name' => ts('Save'),
873 'js' => $js,
874 'isDefault' => TRUE,
875 ),
876 array(
877 'type' => 'upload',
878 'name' => ts('Save and New'),
879 'js' => $js,
880 'subName' => 'new',
881 ),
882 array(
883 'type' => 'cancel',
884 'name' => ts('Cancel'),
885 ),
886 )
887 );
888
889 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
890 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
891 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
892 if ($totalAmount) {
893 $totalAmount->freeze();
894 }
895 $checkNumber->freeze();
896 $paymentInstrument->freeze();
897 $trxnId->freeze();
898 $financialType->freeze();
899 }
900
901 // if contribution is related to membership or participant freeze Financial Type, Amount
902 if ($this->_id && isset($this->_values['tax_amount'])) {
903 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
904 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
905 if ($totalAmount) {
906 $totalAmount->freeze();
907 }
908 $financialType->freeze();
909 $this->assign('freezeFinancialType', TRUE);
910 }
911 }
912
913 if ($this->_action & CRM_Core_Action::VIEW) {
914 $this->freeze();
915 }
916 }
917
918 /**
919 * Global form rule.
920 *
921 * @param array $fields
922 * The input form values.
923 * @param array $files
924 * The uploaded files if any.
925 * @param $self
926 *
927 * @return bool|array
928 * true if no errors, else array of errors
929 */
930 public static function formRule($fields, $files, $self) {
931 $errors = array();
932 // Check for Credit Card Contribution.
933 if ($self->_mode) {
934 if (empty($fields['payment_processor_id'])) {
935 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
936 }
937 else {
938 // validate payment instrument (e.g. credit card number)
939 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
940 }
941 }
942
943 // Do the amount validations.
944 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
945 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
946 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
947 }
948 }
949
950 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
951
952 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
953 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
954 // For taxable contribution we need to deduct taxable amount from
955 // (net amount + fee amount) before comparing it with total amount
956 if (!empty($self->_values['tax_amount'])) {
957 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($self->_id);
958 if (!(CRM_Utils_Array::value('membership', $componentDetails) ||
959 CRM_Utils_Array::value('participant', $componentDetails))
960 ) {
961 $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a');
962 }
963 }
964 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != CRM_Utils_Rule::cleanMoney($sum)) {
965 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
966 }
967 }
968
969 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
970 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
971
972 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
973 if (($self->_action & CRM_Core_Action::UPDATE)
974 && $self->_id
975 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
976 ) {
977 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
978 }
979 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
980 if (($self->_action & CRM_Core_Action::UPDATE)
981 && $self->_id
982 && $self->_values['financial_type_id'] != $fields['financial_type_id']
983 ) {
984 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
985 }
986 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
987 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
988 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
989 }
990
991 // $trxn_id must be unique CRM-13919
992 if (!empty($fields['trxn_id'])) {
993 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
994 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
995 if ($self->_id) {
996 $queryParams[2] = array((int) $self->_id, 'Integer');
997 $query .= ' and id !=%2';
998 }
999 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
1000 if ($tCnt) {
1001 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
1002 }
1003 }
1004
1005 $errors = array_merge($errors, $softErrors);
1006 return $errors;
1007 }
1008
1009 /**
1010 * Process the form submission.
1011 */
1012 public function postProcess() {
1013 $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
1014 $softParams = $softIDs = array();
1015
1016 if ($this->_action & CRM_Core_Action::DELETE) {
1017 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
1018 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1019 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1020 ));
1021 return;
1022 }
1023
1024 // Get the submitted form values.
1025 $submittedValues = $this->controller->exportValues($this->_name);
1026 if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) {
1027 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1028 $lineID = key($line);
1029 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1030 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1031 if ($quickConfig) {
1032 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1033 }
1034 }
1035
1036 // Process price set and get total amount and line items.
1037 $lineItem = array();
1038 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1039 if (empty($priceSetId) && !$this->_id) {
1040 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1041 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1042 $fieldID = key($this->_priceSet['fields']);
1043 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1044 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1045 $submittedValues['price_' . $fieldID] = 1;
1046 }
1047
1048 if ($priceSetId) {
1049 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1050 $submittedValues, $lineItem[$priceSetId]);
1051
1052 // Unset tax amount for offline 'is_quick_config' contribution.
1053 if ($this->_priceSet['is_quick_config'] &&
1054 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1055 ) {
1056 unset($submittedValues['tax_amount']);
1057 }
1058 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1059 }
1060 if ($this->_id) {
1061 if ($this->_compId) {
1062 if ($this->_context == 'participant') {
1063 $pId = $this->_compId;
1064 }
1065 elseif ($this->_context == 'membership') {
1066 $isRelatedId = TRUE;
1067 }
1068 else {
1069 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1070 }
1071 }
1072 else {
1073 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1074 if (array_key_exists('membership', $contributionDetails)) {
1075 $isRelatedId = TRUE;
1076 }
1077 elseif (array_key_exists('participant', $contributionDetails)) {
1078 $pId = $contributionDetails['participant'];
1079 }
1080 }
1081 }
1082 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1083 // CRM-10117 update the line items for participants.
1084 if ($pId) {
1085 $entityTable = 'participant';
1086 $entityID = $pId;
1087 $isRelatedId = FALSE;
1088 $participantParams = array(
1089 'fee_amount' => $submittedValues['total_amount'],
1090 'id' => $entityID,
1091 );
1092 CRM_Event_BAO_Participant::add($participantParams);
1093 if (empty($this->_lineItems)) {
1094 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1095 }
1096 }
1097 else {
1098 $entityTable = 'contribution';
1099 $entityID = $this->_id;
1100 }
1101
1102 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1103 foreach (array_keys($lineItems) as $id) {
1104 $lineItems[$id]['id'] = $id;
1105 }
1106 $itemId = key($lineItems);
1107 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1108 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1109 }
1110
1111 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1112 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1113 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1114 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
1115 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1116 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1117 }
1118 }
1119 // Update line total and total amount with tax on edit.
1120 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1121 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1122 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1123 }
1124 else {
1125 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1126 $submittedValues['tax_amount'] = 'null';
1127 }
1128 if ($lineItems[$itemId]['tax_rate']) {
1129 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1130 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1131 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1132 }
1133 }
1134 // CRM-10117 update the line items for participants.
1135 if (!empty($lineItems[$itemId]['price_field_id'])) {
1136 $lineItem[$this->_priceSetId] = $lineItems;
1137 }
1138 }
1139
1140 $isQuickConfig = 0;
1141 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1142 $isQuickConfig = 1;
1143 }
1144 //CRM-11529 for quick config back office transactions
1145 //when financial_type_id is passed in form, update the
1146 //line items with the financial type selected in form
1147 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1148 ) {
1149 foreach ($lineItem[$this->_priceSetId] as &$values) {
1150 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1151 }
1152 }
1153
1154 if (!isset($submittedValues['total_amount'])) {
1155 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1156 }
1157 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1158
1159 if (!empty($submittedValues['pcp_made_through_id'])) {
1160 $pcp = array();
1161 $fields = array(
1162 'pcp_made_through_id',
1163 'pcp_display_in_roll',
1164 'pcp_roll_nickname',
1165 'pcp_personal_note',
1166 );
1167 foreach ($fields as $f) {
1168 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1169 }
1170 }
1171
1172 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1173 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1174 //Delete existing soft credit records if soft credit list is empty on update
1175 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
1176 }
1177 else {
1178 //build soft credit params
1179 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1180 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1181 $softParams[$key]['contact_id'] = $val;
1182 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1183 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1184 if (!empty($submittedValues['soft_credit_id'][$key])) {
1185 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1186 }
1187 }
1188 }
1189 }
1190
1191 // set the contact, when contact is selected
1192 if (!empty($submittedValues['contact_id'])) {
1193 $this->_contactID = $submittedValues['contact_id'];
1194 }
1195
1196 // Credit Card Contribution.
1197 if ($this->_mode) {
1198 $this->processCreditCard($submittedValues, $lineItem);
1199 }
1200 else {
1201 // Offline Contribution.
1202 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1203
1204 // get the required field value only.
1205 $formValues = $submittedValues;
1206 $params = $ids = array();
1207
1208 $params['contact_id'] = $this->_contactID;
1209
1210 $params['currency'] = $this->getCurrency($submittedValues);
1211
1212 $fields = array(
1213 'financial_type_id',
1214 'contribution_status_id',
1215 'payment_instrument_id',
1216 'cancel_reason',
1217 'source',
1218 'check_number',
1219 );
1220 foreach ($fields as $f) {
1221 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1222 }
1223
1224 $params['pcp'] = !empty($pcp) ? $pcp : NULL;
1225 $params['soft_credit'] = !empty($softParams) ? $softParams : array();
1226 $params['soft_credit_ids'] = !empty($softIDs) ? $softIDs : array();
1227
1228 // CRM-5740 if priceset is used, no need to cleanup money.
1229 if ($priceSetId) {
1230 $params['skipCleanMoney'] = 1;
1231 }
1232
1233 $dates = array(
1234 'receive_date',
1235 'receipt_date',
1236 'cancel_date',
1237 );
1238
1239 foreach ($dates as $d) {
1240 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1241 }
1242
1243 if (!empty($formValues['is_email_receipt'])) {
1244 $params['receipt_date'] = date("Y-m-d");
1245 }
1246
1247 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1248 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1249 ) {
1250 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1251 $params['cancel_date'] = date('Y-m-d');
1252 }
1253 }
1254 else {
1255 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1256 }
1257
1258 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1259 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1260 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1261 $params['is_pay_later'] = 1;
1262 }
1263 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1264 $params['is_pay_later'] = 0;
1265 }
1266
1267 $ids['contribution'] = $params['id'] = $this->_id;
1268
1269 // Add Additional common information to formatted params.
1270 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1271 if ($pId) {
1272 $params['contribution_mode'] = 'participant';
1273 $params['participant_id'] = $pId;
1274 $params['skipLineItem'] = 1;
1275 }
1276 elseif ($isRelatedId) {
1277 $params['contribution_mode'] = 'membership';
1278 }
1279 $params['line_item'] = $lineItem;
1280 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1281 if (isset($submittedValues['tax_amount'])) {
1282 $params['tax_amount'] = $submittedValues['tax_amount'];
1283 }
1284 //create contribution.
1285 if ($isQuickConfig) {
1286 $params['is_quick_config'] = 1;
1287 }
1288
1289 // CRM-11956
1290 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1291 // if non_deductible_amount does NOT exist - then calculate it depending on:
1292 // $ContributionType->is_deductible and whether there is a product (premium).
1293 if (empty($params['non_deductible_amount'])) {
1294 $contributionType = new CRM_Financial_DAO_FinancialType();
1295 $contributionType->id = $params['financial_type_id'];
1296 if (!$contributionType->find(TRUE)) {
1297 CRM_Core_Error::fatal('Could not find a system table');
1298 }
1299 if ($contributionType->is_deductible) {
1300
1301 if (isset($formValues['product_name'][0])) {
1302 $selectProduct = $formValues['product_name'][0];
1303 }
1304 // if there is a product - compare the value to the contribution amount
1305 if (isset($selectProduct)) {
1306 $productDAO = new CRM_Contribute_DAO_Product();
1307 $productDAO->id = $selectProduct;
1308 $productDAO->find(TRUE);
1309 // product value exceeds contribution amount
1310 if ($params['total_amount'] < $productDAO->price) {
1311 $params['non_deductible_amount'] = $params['total_amount'];
1312 }
1313 // product value does NOT exceed contribution amount
1314 else {
1315 $params['non_deductible_amount'] = $productDAO->price;
1316 }
1317 }
1318 // contribution is deductible - but there is no product
1319 else {
1320 $params['non_deductible_amount'] = '0.00';
1321 }
1322 }
1323 // contribution is NOT deductible
1324 else {
1325 $params['non_deductible_amount'] = $params['total_amount'];
1326 }
1327 }
1328
1329 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1330
1331 // process associated membership / participant, CRM-4395
1332 $relatedComponentStatusMsg = NULL;
1333 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1334 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1335 $contribution->contribution_status_id,
1336 CRM_Utils_Array::value('contribution_status_id',
1337 $this->_values
1338 ),
1339 $contribution->receive_date
1340 );
1341 }
1342
1343 //process note
1344 if ($contribution->id && isset($formValues['note'])) {
1345 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1346 }
1347
1348 //process premium
1349 if ($contribution->id && isset($formValues['product_name'][0])) {
1350 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1351 $this->_premiumID, $this->_options
1352 );
1353 }
1354
1355 // assign tax calculation for contribution receipts
1356 $taxRate = array();
1357 $getTaxDetails = FALSE;
1358 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1359 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1360 if ($invoicing) {
1361 if ($this->_action & CRM_Core_Action::ADD) {
1362 $line = $lineItem;
1363 }
1364 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1365 $line = $this->_lineItems;
1366 }
1367 foreach ($line as $key => $value) {
1368 foreach ($value as $v) {
1369 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1370 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1371 }
1372 else {
1373 if (isset($v['tax_rate'])) {
1374 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1375 $getTaxDetails = TRUE;
1376 }
1377 }
1378 }
1379 }
1380 }
1381
1382 if ($invoicing) {
1383 if ($this->_action & CRM_Core_Action::UPDATE) {
1384 if (isset($submittedValues['tax_amount'])) {
1385 $totalTaxAmount = $submittedValues['tax_amount'];
1386 }
1387 else {
1388 $totalTaxAmount = $this->_values['tax_amount'];
1389 }
1390 $this->assign('totalTaxAmount', $totalTaxAmount);
1391 $this->assign('dataArray', $taxRate);
1392 }
1393 else {
1394 if (!empty($submittedValues['price_set_id'])) {
1395 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1396 $this->assign('getTaxDetails', $getTaxDetails);
1397 $this->assign('dataArray', $taxRate);
1398 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1399 }
1400 else {
1401 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1402 }
1403 }
1404 }
1405
1406 //send receipt mail.
1407 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1408 $formValues['contact_id'] = $this->_contactID;
1409 $formValues['contribution_id'] = $contribution->id;
1410
1411 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1412
1413 // to get 'from email id' for send receipt
1414 $this->fromEmailId = $formValues['from_email_address'];
1415 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1416 }
1417
1418 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1419 $contribution->id,
1420 'id',
1421 'contribution_id'
1422 );
1423
1424 //update pledge payment status.
1425 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1426 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1427 ) {
1428
1429 if ($this->_ppID) {
1430 //store contribution id in payment record.
1431 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1432 }
1433 else {
1434 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1435 $contribution->id,
1436 'id',
1437 'contribution_id'
1438 );
1439 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1440 $contribution->id,
1441 'pledge_id',
1442 'contribution_id'
1443 );
1444 }
1445
1446 $adjustTotalAmount = FALSE;
1447 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1448 $adjustTotalAmount = TRUE;
1449 }
1450
1451 $updatePledgePaymentStatus = FALSE;
1452 //do only if either the status or the amount has changed
1453 if ($this->_action & CRM_Core_Action::ADD) {
1454 $updatePledgePaymentStatus = TRUE;
1455 }
1456 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1457 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1458 ) {
1459 $updatePledgePaymentStatus = TRUE;
1460 }
1461
1462 if ($updatePledgePaymentStatus) {
1463 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1464 array($this->_ppID),
1465 $contribution->contribution_status_id,
1466 NULL,
1467 $contribution->total_amount,
1468 $adjustTotalAmount
1469 );
1470 }
1471 }
1472
1473 $statusMsg = ts('The contribution record has been saved.');
1474 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1475 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1476 }
1477
1478 if ($relatedComponentStatusMsg) {
1479 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1480 }
1481
1482 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1483 //Offline Contribution ends.
1484 }
1485 $session = CRM_Core_Session::singleton();
1486 $buttonName = $this->controller->getButtonName();
1487 if ($this->_context == 'standalone') {
1488 if ($buttonName == $this->getButtonName('upload', 'new')) {
1489 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1490 'reset=1&action=add&context=standalone'
1491 ));
1492 }
1493 else {
1494 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1495 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1496 ));
1497 }
1498 }
1499 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1500 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1501 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1502 ));
1503 }
1504 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1505 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1506 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1507 ));
1508 }
1509
1510 //store contribution ID if not yet set (on create)
1511 if (empty($this->_id) && !empty($contribution->id)) {
1512 $this->_id = $contribution->id;
1513 }
1514 }
1515
1516 /**
1517 * Process credit card payment.
1518 *
1519 * @param array $submittedValues
1520 * @param array $lineItem
1521 *
1522 * @throws CRM_Core_Exception
1523 */
1524 protected function processCreditCard($submittedValues, $lineItem) {
1525 $sendReceipt = $contribution = FALSE;
1526
1527 $unsetParams = array(
1528 'trxn_id',
1529 'payment_instrument_id',
1530 'contribution_status_id',
1531 'cancel_date',
1532 'cancel_reason',
1533 );
1534 foreach ($unsetParams as $key) {
1535 if (isset($submittedValues[$key])) {
1536 unset($submittedValues[$key]);
1537 }
1538 }
1539 $isTest = ($this->_mode == 'test') ? 1 : 0;
1540 // CRM-12680 set $_lineItem if its not set
1541 if (empty($this->_lineItem) && !empty($lineItem)) {
1542 $this->_lineItem = $lineItem;
1543 }
1544
1545 //Get the require fields value only.
1546 $params = $this->_params = $submittedValues;
1547
1548 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1549 $this->_mode
1550 );
1551
1552 // Get the payment processor id as per mode.
1553 $this->_params['payment_processor'] = $params['payment_processor_id']
1554 = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1555
1556 $now = date('YmdHis');
1557 $fields = array();
1558
1559 // we need to retrieve email address
1560 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1561 list($this->userDisplayName,
1562 $this->userEmail
1563 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1564 $this->assign('displayName', $this->userDisplayName);
1565 }
1566
1567 // Set email for primary location.
1568 $fields['email-Primary'] = 1;
1569 $params['email-Primary'] = $this->userEmail;
1570
1571 // now set the values for the billing location.
1572 foreach (array_keys($this->_fields) as $name) {
1573 $fields[$name] = 1;
1574 }
1575
1576 // also add location name to the array
1577 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
1578
1579 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1580 $fields["address_name-{$this->_bltID}"] = 1;
1581 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1582 $this->_contactID,
1583 'contact_type'
1584 );
1585
1586 $nameFields = array('first_name', 'middle_name', 'last_name');
1587 foreach ($nameFields as $name) {
1588 $fields[$name] = 1;
1589 if (array_key_exists("billing_$name", $params)) {
1590 $params[$name] = $params["billing_{$name}"];
1591 $params['preserveDBName'] = TRUE;
1592 }
1593 }
1594
1595 if (!empty($params['source'])) {
1596 unset($params['source']);
1597 }
1598 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1599 $this->_contactID,
1600 NULL, NULL,
1601 $ctype
1602 );
1603
1604 // add all the additional payment params we need
1605 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
1606 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
1607 }
1608 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
1609 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1610 }
1611 $legacyCreditCardExpiryCheck = FALSE;
1612 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
1613 $legacyCreditCardExpiryCheck = TRUE;
1614 }
1615 if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
1616 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1617 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1618 }
1619 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1620 $this->_params['amount'] = $this->_params['total_amount'];
1621 $this->_params['amount_level'] = 0;
1622 $this->_params['description'] = ts('Office Credit Card contribution');
1623 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1624 $this->_params,
1625 CRM_Core_Config::singleton()->defaultCurrency
1626 );
1627 $this->_params['payment_action'] = 'Sale';
1628 if (!empty($this->_params['receive_date'])) {
1629 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1630 }
1631
1632 if (!empty($params['soft_credit_to'])) {
1633 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1634 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1635 }
1636
1637 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1638 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1639 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1640
1641 //Add common data to formatted params
1642 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1643
1644 if (empty($this->_params['invoice_id'])) {
1645 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1646 }
1647 else {
1648 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1649 }
1650
1651 // At this point we've created a contact and stored its address etc
1652 // all the payment processors expect the name and address to be in the
1653 // so we copy stuff over to first_name etc.
1654 $paymentParams = $this->_params;
1655 $paymentParams['contactID'] = $this->_contactID;
1656 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1657
1658 $contributionType = new CRM_Financial_DAO_FinancialType();
1659 $contributionType->id = $params['financial_type_id'];
1660 $contributionType->find(TRUE);
1661
1662 // Add some financial type details to the params list
1663 // if folks need to use it.
1664 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1665 $paymentParams['contributionPageID'] = NULL;
1666
1667 if (!empty($this->_params['is_email_receipt'])) {
1668 $paymentParams['email'] = $this->userEmail;
1669 $paymentParams['is_email_receipt'] = 1;
1670 }
1671 else {
1672 $paymentParams['is_email_receipt'] = 0;
1673 $this->_params['is_email_receipt'] = 0;
1674 }
1675 if (!empty($this->_params['receive_date'])) {
1676 $paymentParams['receive_date'] = $this->_params['receive_date'];
1677 }
1678
1679 // For recurring contribution, create Contribution Record first.
1680 // Contribution ID, Recurring ID and Contact ID needed
1681 // When we get a callback from the payment processor, CRM-7115
1682
1683 if (!empty($paymentParams['is_recur'])) {
1684 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1685 $this->_params,
1686 NULL,
1687 $this->_contactID,
1688 $contributionType,
1689 TRUE,
1690 FALSE,
1691 $isTest,
1692 $this->_lineItem
1693 );
1694 $paymentParams['contributionID'] = $contribution->id;
1695 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1696 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1697 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1698 }
1699 $result = array();
1700 if ($paymentParams['amount'] > 0.0) {
1701 // force a re-get of the payment processor in case the form changed it, CRM-7179
1702 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1703 try {
1704 $result = $payment->doPayment($paymentParams, 'contribute');
1705 }
1706 catch (CRM_Core_Exception $e) {
1707 $message = ts("Payment Processor Error message") . $e->getMessage();
1708 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1709 // Set the contribution mode.
1710 $urlParams = "action=add&cid={$this->_contactID}";
1711 if ($this->_mode) {
1712 $urlParams .= "&mode={$this->_mode}";
1713 }
1714 if (!empty($this->_ppID)) {
1715 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1716 }
1717 CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1718 }
1719 }
1720
1721 $this->_params = array_merge($this->_params, $result);
1722
1723 $this->_params['receive_date'] = $now;
1724
1725 if (!empty($this->_params['is_email_receipt'])) {
1726 $this->_params['receipt_date'] = $now;
1727 }
1728 else {
1729 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1730 $params['receipt_date_time'], TRUE
1731 );
1732 }
1733
1734 $this->set('params', $this->_params);
1735 $this->assign('trxn_id', $result['trxn_id']);
1736 $this->assign('receive_date', $this->_params['receive_date']);
1737
1738 // Result has all the stuff we need
1739 // lets archive it to a financial transaction
1740 if ($contributionType->is_deductible) {
1741 $this->assign('is_deductible', TRUE);
1742 $this->set('is_deductible', TRUE);
1743 }
1744
1745 // Set source if not set
1746 if (empty($this->_params['source'])) {
1747 $userID = CRM_Core_Session::singleton()->get('userID');
1748 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1749 'sort_name'
1750 );
1751 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1752 }
1753
1754 // Build custom data getFields array
1755 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1756 CRM_Utils_Array::value('financial_type_id', $params)
1757 );
1758 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1759 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1760 );
1761 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1762 $customFields,
1763 $this->_id,
1764 'Contribution'
1765 );
1766 if (empty($paymentParams['is_recur'])) {
1767 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1768 $this->_params,
1769 $result,
1770 $this->_contactID,
1771 $contributionType,
1772 FALSE, FALSE,
1773 $isTest,
1774 $this->_lineItem
1775 );
1776 }
1777
1778 if (!empty($paymentParams['is_recur']) && is_array($result) && CRM_Utils_Array::value('payment_status_id', $result) == 1) {
1779 try {
1780 civicrm_api3('contribution', 'completetransaction', array(
1781 'id' => $contribution->id,
1782 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result),
1783 'is_transactional' => FALSE,
1784 ));
1785 // This has not been set to 1 in the DB - declare it here also
1786 $contribution->contribution_status_id = 1;
1787 }
1788 catch (CiviCRM_API3_Exception $e) {
1789 if ($e->getErrorCode() != 'contribution_completed') {
1790 throw new CRM_Core_Exception('Failed to update contribution in database');
1791 }
1792 }
1793 }
1794 // Send receipt mail. (if the complete transaction ran it will have sent it - so avoid 2
1795 // with the elseif. CRM-16926
1796 elseif ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1797 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1798 $this->_params['contact_id'] = $this->_contactID;
1799 $this->_params['contribution_id'] = $contribution->id;
1800 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1801 }
1802
1803 //process the note
1804 if ($contribution->id && isset($params['note'])) {
1805 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1806 }
1807 //process premium
1808 if ($contribution->id && isset($params['product_name'][0])) {
1809 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1810 }
1811
1812 //update pledge payment status.
1813 if ($this->_ppID && $contribution->id) {
1814 // Store contribution id in payment record.
1815 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1816
1817 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1818 array($this->_ppID),
1819 $contribution->contribution_status_id,
1820 NULL,
1821 $contribution->total_amount
1822 );
1823 }
1824
1825 if ($contribution->id) {
1826 $statusMsg = ts('The contribution record has been processed.');
1827 if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
1828 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1829 }
1830 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1831 }
1832 }
1833
1834 /**
1835 * Clean up DB after payment fails.
1836 *
1837 * This function removes related DB entries. Note that it has been agreed in principle,
1838 * but not implemented, that contributions should be retained as 'Failed' rather than
1839 * deleted.
1840 *
1841 * @todo it doesn't clean up line items.
1842 *
1843 * @param array $paymentParams
1844 * @param string $message
1845 */
1846 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1847 // Make sure to cleanup db for recurring case.
1848 if (!empty($paymentParams['contributionID'])) {
1849 CRM_Core_Error::debug_log_message($message .
1850 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1851 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1852 }
1853 if (!empty($paymentParams['contributionRecurID'])) {
1854 CRM_Core_Error::debug_log_message($message .
1855 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1856 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1857 }
1858 }
1859
1860 /**
1861 * Generate the data to construct a snippet based pane.
1862 *
1863 * This form also assigns the showAdditionalInfo var based on historical code.
1864 * This appears to mean 'there is a pane to show'.
1865 *
1866 * @param string $type
1867 * Type of Pane - this is generally used to determine the function name used to build it
1868 * - e.g CreditCard, AdditionalDetail
1869 * @param array $defaults
1870 *
1871 * @return array
1872 * We aim to further refactor & simplify this but currently
1873 * - the panes array
1874 * - should additional info be shown?
1875 */
1876 protected function generatePane($type, $defaults) {
1877 $urlParams = "snippet=4&formType={$type}";
1878 if ($this->_mode) {
1879 $urlParams .= "&mode={$this->_mode}";
1880 }
1881
1882 $open = 'false';
1883 if ($type == 'CreditCard' ||
1884 $type == 'DirectDebit'
1885 ) {
1886 $open = 'true';
1887 }
1888
1889 $pane = array(
1890 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1891 'open' => $open,
1892 'id' => $type,
1893 );
1894
1895 // See if we need to include this paneName in the current form.
1896 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1897 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1898 ) {
1899 $this->assign('showAdditionalInfo', TRUE);
1900 $pane['open'] = 'true';
1901 }
1902
1903 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1904 // @todo would be good to align tpl name with form name...
1905 // @todo document why this hidden variable is required.
1906 $this->add('hidden', 'hidden_' . $type, 1);
1907 return $pane;
1908 }
1909 else {
1910 $additionalInfoFormFunction = 'build' . $type;
1911 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1912 return $pane;
1913 }
1914 }
1915
1916 }