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