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