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