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