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