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