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