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