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