aa27d772043eb6a49913aaf7d93aca1cc5ecb6b9
[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 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
401 }
402
403 if (isset($defaults['non_deductible_amount'])) {
404 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
405 }
406
407 if (isset($defaults['fee_amount'])) {
408 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
409 }
410
411 if (isset($defaults['net_amount'])) {
412 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
413 }
414
415 if ($this->_contributionType) {
416 $defaults['financial_type_id'] = $this->_contributionType;
417 }
418
419 if (empty($defaults['payment_instrument_id'])) {
420 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
421 }
422
423 if (!empty($defaults['is_test'])) {
424 $this->assign('is_test', TRUE);
425 }
426
427 $this->assign('showOption', TRUE);
428 // for Premium section
429 if ($this->_premiumID) {
430 $this->assign('showOption', FALSE);
431 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
432 if (!$options) {
433 $this->assign('showOption', TRUE);
434 }
435 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
436 if ($options_key) {
437 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
438 }
439 else {
440 $defaults['product_name'] = array($this->_productDAO->product_id);
441 }
442 if ($this->_productDAO->fulfilled_date) {
443 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
444 }
445 }
446
447 if (isset($this->userEmail)) {
448 $this->assign('email', $this->userEmail);
449 }
450
451 if (!empty($defaults['is_pay_later'])) {
452 $this->assign('is_pay_later', TRUE);
453 }
454 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
455
456 $dates = array('receive_date', 'receipt_date', 'cancel_date', 'thankyou_date');
457 foreach ($dates as $key) {
458 if (!empty($defaults[$key])) {
459 list($defaults[$key],
460 $defaults[$key . '_time']
461 ) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults),
462 'activityDateTime'
463 );
464 }
465 }
466
467 if (!$this->_id && empty($defaults['receive_date'])) {
468 list($defaults['receive_date'],
469 $defaults['receive_date_time']
470 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
471 }
472
473 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
474 CRM_Utils_Array::value('receive_date_time', $defaults)
475 ));
476 $currency = CRM_Utils_Array::value('currency', $defaults);
477 $this->assign('currency', $currency);
478 // Hack to get currency info to the js layer. CRM-11440
479 CRM_Utils_Money::format(1);
480 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
481 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
482
483 //inherit campaign from pledge.
484 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
485 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
486 }
487
488 $this->_defaults = $defaults;
489 return $defaults;
490 }
491
492 /**
493 * Function to build the form
494 *
495 * @return void
496 * @access public
497 */
498 public function buildQuickForm() {
499 if ($this->_cdType) {
500 CRM_Custom_Form_CustomData::buildQuickForm($this);
501 return;
502 }
503 $allPanes = array();
504 //tax rate from financialType
505 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
506
507 // build price set form.
508 $buildPriceSet = FALSE;
509 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
510 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
511
512 // display tax amount on edit contribution page
513 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
514 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
515 }
516
517 if (empty($this->_lineItems) &&
518 ($this->_priceSetId || !empty($_POST['price_set_id']))
519 ) {
520 $buildPriceSet = TRUE;
521 $getOnlyPriceSetElements = TRUE;
522 if (!$this->_priceSetId) {
523 $this->_priceSetId = $_POST['price_set_id'];
524 $getOnlyPriceSetElements = FALSE;
525 }
526
527 $this->set('priceSetId', $this->_priceSetId);
528 CRM_Price_BAO_PriceSet::buildPriceSet($this);
529
530 // get only price set form elements.
531 if ($getOnlyPriceSetElements) {
532 return;
533 }
534 }
535 // use to build form during form rule.
536 $this->assign('buildPriceSet', $buildPriceSet);
537
538 $showAdditionalInfo = FALSE;
539
540 $defaults = $this->_values;
541 $additionalDetailFields = array(
542 'note',
543 'thankyou_date',
544 'invoice_id',
545 'non_deductible_amount',
546 'fee_amount',
547 'net_amount',
548 );
549 foreach ($additionalDetailFields as $key) {
550 if (!empty($defaults[$key])) {
551 $defaults['hidden_AdditionalDetail'] = 1;
552 break;
553 }
554 }
555
556 if ($this->_productDAO) {
557 if ($this->_productDAO->product_id) {
558 $defaults['hidden_Premium'] = 1;
559 }
560 }
561
562 if ($this->_noteID &&
563 isset($this->_values['note'])
564 ) {
565 $defaults['hidden_AdditionalDetail'] = 1;
566 }
567
568 $paneNames = array(
569 ts('Additional Details') => 'AdditionalDetail',
570 );
571
572 //Add Premium pane only if Premium is exists.
573 $dao = new CRM_Contribute_DAO_Product();
574 $dao->is_active = 1;
575
576 if ($dao->find(TRUE)) {
577 $paneNames[ts('Premium Information')] = 'Premium';
578 }
579
580 $ccPane = NULL;
581 if ($this->_mode) {
582 if (CRM_Utils_Array::value('payment_type', $this->_processors) & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
583 ) {
584 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
585 }
586 else {
587 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
588 }
589 }
590 if (is_array($ccPane)) {
591 $paneNames = array_merge($ccPane, $paneNames);
592 }
593
594 $buildRecurBlock = FALSE;
595 foreach ($paneNames as $name => $type) {
596 $urlParams = "snippet=4&formType={$type}";
597 if ($this->_mode) {
598 $urlParams .= "&mode={$this->_mode}";
599 }
600
601 $open = 'false';
602 if ($type == 'CreditCard' ||
603 $type == 'DirectDebit'
604 ) {
605 $open = 'true';
606 }
607
608 $allPanes[$name] = array(
609 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
610 'open' => $open,
611 'id' => $type
612 );
613
614 // see if we need to include this paneName in the current form
615 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
616 CRM_Utils_Array::value("hidden_{$type}", $defaults)
617 ) {
618 $showAdditionalInfo = TRUE;
619 $allPanes[$name]['open'] = 'true';
620 }
621
622 if ($type == 'CreditCard') {
623 $buildRecurBlock = TRUE;
624 $this->add('hidden', 'hidden_CreditCard', 1);
625 CRM_Core_Payment_Form::buildCreditCard($this, TRUE);
626 }
627 elseif ($type == 'DirectDebit') {
628 $buildRecurBlock = TRUE;
629 $this->add('hidden', 'hidden_DirectDebit', 1);
630 CRM_Core_Payment_Form::buildDirectDebit($this, TRUE);
631 }
632 else {
633 $additionalInfoFormFunction = 'build' . $type;
634 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
635 }
636 }
637 if (empty($this->_recurPaymentProcessors)) {
638 $buildRecurBlock = FALSE;
639 }
640 if ($buildRecurBlock) {
641 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
642 $this->setDefaults(array('is_recur' => 0));
643 }
644 $this->assign('buildRecurBlock', $buildRecurBlock);
645 $qfKey = $this->controller->_key;
646 $this->assign('qfKey', $qfKey);
647 $this->assign('allPanes', $allPanes);
648 $this->assign('showAdditionalInfo', $showAdditionalInfo);
649
650 if ($this->_formType) {
651 $this->assign('formType', $this->_formType);
652 return;
653 }
654
655 $this->applyFilter('__ALL__', 'trim');
656
657 if ($this->_action & CRM_Core_Action::DELETE) {
658 $this->addButtons(array(
659 array(
660 'type' => 'next',
661 'name' => ts('Delete'),
662 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
663 'isDefault' => TRUE,
664 ),
665 array(
666 'type' => 'cancel',
667 'name' => ts('Cancel')
668 )
669 )
670 );
671 return;
672 }
673
674 //need to assign custom data type and subtype to the template
675 $this->assign('customDataType', 'Contribution');
676 $this->assign('customDataSubType', $this->_contributionType);
677 $this->assign('entityID', $this->_id);
678
679 if ($this->_context == 'standalone') {
680 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE), TRUE);
681 }
682
683 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
684
685 $financialType = $this->add('select', 'financial_type_id',
686 ts('Financial Type'),
687 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
688 TRUE,
689 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
690 );
691 $paymentInstrument = FALSE;
692 if (!$this->_mode) {
693 $paymentInstrument = $this->add('select', 'payment_instrument_id',
694 ts('Paid By'),
695 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
696 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
697 );
698 }
699
700 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']);
701
702 //add receipt for offline contribution
703 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
704
705 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
706
707 $status = CRM_Contribute_PseudoConstant::contributionStatus();
708
709 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
710 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
711 if ($this->_ppID) {
712 foreach (array(
713 'Cancelled',
714 'Failed',
715 'In Progress'
716 ) as $suppress) {
717 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
718 }
719 }
720 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
721 $suppressFlag = FALSE;
722 if ($this->_id) {
723 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
724 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
725 $suppressFlag = TRUE;
726 }
727 }
728 if (!$suppressFlag) {
729 foreach (array(
730 'Overdue',
731 'In Progress'
732 ) as $suppress) {
733 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
734 }
735 }
736 else {
737 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
738 }
739 }
740
741 if ($this->_id) {
742 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
743 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
744 switch ($name) {
745 case 'Completed':
746 case 'Cancelled':
747 case 'Refunded':
748 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
749 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
750 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
751 break;
752 case 'Pending':
753 case 'In Progress':
754 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
755 break;
756 case 'Failed':
757 foreach (array(
758 'Pending',
759 'Refunded',
760 'Completed',
761 'In Progress',
762 'Cancelled'
763 ) as $suppress) {
764 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
765 }
766 break;
767 }
768 }
769 else {
770 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
771 }
772
773 $this->add('select', 'contribution_status_id',
774 ts('Contribution Status'),
775 $status,
776 FALSE
777 );
778
779 // add various dates
780 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
781
782 if ($this->_online) {
783 $this->assign('hideCalender', TRUE);
784 }
785 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
786
787 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
788 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
789
790 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
791
792 $recurJs = NULL;
793 if ($buildRecurBlock) {
794 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
795 }
796 $element = $this->add('select',
797 'payment_processor_id',
798 ts('Payment Processor'),
799 $this->_processors,
800 NULL,
801 $recurJs
802 );
803
804 if ($this->_online) {
805 $element->freeze();
806 }
807 $totalAmount = NULL;
808 if (empty($this->_lineItems)) {
809 $buildPriceSet = FALSE;
810 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
811 if (!empty($priceSets) && !$this->_ppID) {
812 $buildPriceSet = TRUE;
813 }
814
815 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
816 // and if we already have line items for that participant. CRM-5095
817 if ($buildPriceSet && $this->_id) {
818 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
819 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
820 $this->_id,
821 'id',
822 'contribution_id'
823 );
824 if ($pledgePaymentId) {
825 $buildPriceSet = FALSE;
826 }
827 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
828 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
829 if (!CRM_Utils_System::isNull($participantLI)) {
830 $buildPriceSet = FALSE;
831 }
832 }
833 }
834
835 $hasPriceSets = FALSE;
836 if ($buildPriceSet) {
837 $hasPriceSets = TRUE;
838 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
839 array(
840 '' => ts('Choose price set')
841 ) + $priceSets,
842 NULL, array('onchange' => "buildAmount( this.value );")
843 );
844 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
845 $element->freeze();
846 }
847 }
848 $this->assign('hasPriceSets', $hasPriceSets);
849 $currencyFreeze = FALSE;
850 if (!($this->_action & CRM_Core_Action::UPDATE)) {
851 if ($this->_online || $this->_ppID) {
852 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
853 'READONLY' => TRUE,
854 'style' => "background-color:#EBECE4"
855 ));
856 $optionTypes = array(
857 '1' => ts('Adjust Pledge Payment Schedule?'),
858 '2' => ts('Adjust Total Pledge Amount?'),
859 );
860 $this->addRadio('option_type',
861 NULL,
862 $optionTypes,
863 array(), '<br/>'
864 );
865
866 $currencyFreeze = TRUE;
867 }
868 }
869
870 $totalAmount = $this->addMoney('total_amount',
871 ts('Total Amount'),
872 ($hasPriceSets) ? FALSE : TRUE,
873 $attributes['total_amount'],
874 TRUE, 'currency', NULL, $currencyFreeze
875 );
876 }
877
878 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
879
880 //CRM-7362 --add campaigns.
881 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
882
883 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
884
885 $js = NULL;
886 if (!$this->_mode) {
887 $js = array('onclick' => "return verify( );");
888 }
889
890 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
891 'mailing_backend'
892 );
893 $this->assign('outBound_option', $mailingInfo['outBound_option']);
894
895 $this->addButtons(array(
896 array(
897 'type' => 'upload',
898 'name' => ts('Save'),
899 'js' => $js,
900 'isDefault' => TRUE
901 ),
902 array(
903 'type' => 'upload',
904 'name' => ts('Save and New'),
905 'js' => $js,
906 'subName' => 'new'
907 ),
908 array(
909 'type' => 'cancel',
910 'name' => ts('Cancel')
911 ),
912 )
913 );
914
915 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
916 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
917 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
918 if ($totalAmount) {
919 $totalAmount->freeze();
920 }
921 $checkNumber->freeze();
922 $paymentInstrument->freeze();
923 $trxnId->freeze();
924 $financialType->freeze();
925 }
926
927 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
928
929 if ($this->_action & CRM_Core_Action::VIEW) {
930 $this->freeze();
931 }
932 }
933
934 /**
935 * global form rule
936 *
937 * @param array $fields the input form values
938 * @param array $files the uploaded files if any
939 * @param $self
940 *
941 * @internal param array $options additional user data
942 *
943 * @return true if no errors, else array of errors
944 * @access public
945 * @static
946 */
947 static function formRule($fields, $files, $self) {
948 $errors = array();
949
950 //check for Credit Card Contribution.
951 if ($self->_mode) {
952 if (empty($fields['payment_processor_id'])) {
953 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
954 }
955 }
956
957 // do the amount validations.
958 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
959 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
960 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
961 }
962 }
963
964 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
965
966 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
967 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
968 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
969 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
970 }
971 }
972 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
973 if ($self->_id && $self->_values['contribution_status_id'] != $fields['contribution_status_id']) {
974 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
975 }
976
977 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
978 if (!empty($fields['fee_amount']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
979 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
980 }
981
982 // $trxn_id must be unique CRM-13919
983 if (!empty($fields['trxn_id'])) {
984 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
985 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
986 if ($self->_id) {
987 $queryParams[2] = array((int)$self->_id, 'Integer');
988 $query .= ' and id !=%2';
989 }
990 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
991 if ($tCnt) {
992 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
993 }
994 }
995
996 $errors = array_merge($errors, $softErrors);
997 return $errors;
998 }
999
1000 /**
1001 * Function to process the form
1002 *
1003 * @access public
1004 *
1005 * @return void
1006 */
1007 public function postProcess() {
1008 $session = CRM_Core_Session::singleton();
1009 $sendReceipt = $pId = $contribution = FALSE;
1010 $softParams = $softIDs =array();
1011
1012 if ($this->_action & CRM_Core_Action::DELETE) {
1013 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
1014 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1015 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1016 ));
1017 return;
1018 }
1019
1020 // get the submitted form values.
1021 $submittedValues = $this->controller->exportValues($this->_name);
1022 if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) {
1023 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1024 $lineID = key($line);
1025 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1026 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1027 if ($quickConfig) {
1028 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1029 }
1030 }
1031
1032 // assign dataArray for contribution receipts
1033 $dataArray = array();
1034 foreach ($this->_lineItems as $key => $value) {
1035 foreach ($value as $v) {
1036 if (isset($dataArray[$v['tax_rate']])) {
1037 $dataArray[$v['tax_rate']] = $dataArray[$v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1038 }
1039 else {
1040 $dataArray[$v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1041 }
1042 }
1043 }
1044 $smarty = CRM_Core_Smarty::singleton();
1045 $smarty->assign('dataArray', $dataArray);
1046
1047 // process price set and get total amount and line items.
1048 $lineItem = array();
1049 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1050 if (empty($priceSetId) && !$this->_id) {
1051 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1052 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1053 $fieldID = key($this->_priceSet['fields']);
1054 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1055 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1056 $submittedValues['price_' . $fieldID] = 1;
1057 }
1058
1059 if ($priceSetId) {
1060 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1061 $submittedValues, $lineItem[$priceSetId]);
1062
1063 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1064 }
1065 if ($this->_id) {
1066 //CRM-10964
1067 $pId = ($this->_compId && $this->_context == 'participant') ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1068 }
1069 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1070 // 10117 update th line items for participants
1071 if ($pId) {
1072 $entityTable = 'participant';
1073 $entityID = $pId;
1074 $participantParams = array(
1075 'fee_amount' => $submittedValues['total_amount'],
1076 'id' => $entityID
1077 );
1078 CRM_Event_BAO_Participant::add($participantParams);
1079 if (empty($this->_lineItems)) {
1080 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1081 }
1082 }
1083 else {
1084 $entityTable = 'contribution';
1085 $entityID = $this->_id;
1086 }
1087
1088 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
1089 foreach (array_keys($lineItems) as $id) {
1090 $lineItems[$id]['id'] = $id;
1091 }
1092 $itemId = key($lineItems);
1093 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1094 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1095 }
1096
1097 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1098 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1099 }
1100 // 10117 update th line items for participants
1101 if (!empty($lineItems[$itemId]['price_field_id'])) {
1102 $lineItem[$this->_priceSetId] = $lineItems;
1103 }
1104 }
1105 $isQuickConfig = 0;
1106 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1107 $isQuickConfig = 1;
1108 }
1109 //CRM-11529 for quick config back office transactions
1110 //when financial_type_id is passed in form, update the
1111 //line items with the financial type selected in form
1112 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1113 ) {
1114 foreach ($lineItem[$this->_priceSetId] as &$values) {
1115 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1116 }
1117 }
1118
1119 if (!isset($submittedValues['total_amount'])) {
1120 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1121 }
1122 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1123
1124 if (!empty($submittedValues['pcp_made_through_id'])) {
1125 $pcp = array();
1126 $fields = array(
1127 'pcp_made_through_id',
1128 'pcp_display_in_roll',
1129 'pcp_roll_nickname',
1130 'pcp_personal_note',
1131 );
1132 foreach ($fields as $f) {
1133 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1134 }
1135 }
1136
1137 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1138 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1139 //Delete existing soft credit records if soft credit list is empty on update
1140 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id));
1141 }
1142 else {
1143 //build soft credit params
1144 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1145 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1146 $softParams[$key]['contact_id'] = $val;
1147 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1148 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1149 if (!empty($submittedValues['soft_credit_id'][$key])) {
1150 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1151 }
1152 }
1153 }
1154 }
1155
1156 // set the contact, when contact is selected
1157 if (!empty($submittedValues['contact_id'])) {
1158 $this->_contactID = $submittedValues['contact_id'];
1159 }
1160
1161 $config = CRM_Core_Config::singleton();
1162
1163 //Credit Card Contribution.
1164 if ($this->_mode) {
1165 $this->processCreditCard($submittedValues, $config, $session, $lineItem);
1166 }
1167 else {
1168 //Offline Contribution.
1169 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1170
1171 // get the required field value only.
1172 $formValues = $submittedValues;
1173 $params = $ids = array();
1174
1175 $params['contact_id'] = $this->_contactID;
1176
1177 $params['currency'] = $this->getCurrency($submittedValues);
1178
1179 $fields = array(
1180 'financial_type_id',
1181 'contribution_status_id',
1182 'payment_instrument_id',
1183 'cancel_reason',
1184 'source',
1185 'check_number',
1186 );
1187 foreach ($fields as $f) {
1188 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1189 }
1190
1191 if (!empty($pcp)) {
1192 $params['pcp'] = $pcp;
1193 }
1194 if (!empty($softParams)) {
1195 $params['soft_credit'] = $softParams;
1196 $params['soft_credit_ids'] = $softIDs;
1197 }
1198
1199 //if priceset is used, no need to cleanup money
1200 //CRM-5740
1201 if ($priceSetId) {
1202 $params['skipCleanMoney'] = 1;
1203 }
1204
1205 $dates = array(
1206 'receive_date',
1207 'receipt_date',
1208 'cancel_date',
1209 );
1210
1211 foreach ($dates as $d) {
1212 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1213 }
1214
1215 if (!empty($formValues['is_email_receipt'])) {
1216 $params['receipt_date'] = date("Y-m-d");
1217 }
1218
1219 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1220 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1221 ) {
1222 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1223 $params['cancel_date'] = date('Y-m-d');
1224 }
1225 }
1226 else {
1227 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1228 }
1229
1230 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1231 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1232 $params['is_pay_later'] = 1;
1233 }
1234
1235 $ids['contribution'] = $params['id'] = $this->_id;
1236
1237 //Add Additional common information to formatted params
1238 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1239 if ($pId) {
1240 $params['contribution_mode'] = 'participant';
1241 $params['participant_id'] = $pId;
1242 $params['skipLineItem'] = 1;
1243 }
1244 $params['line_item'] = $lineItem;
1245 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1246 if (CRM_Utils_Array::value('tax_amount', $submittedValues)) {
1247 $params['tax_amount'] = $submittedValues['tax_amount'];
1248 }
1249 //create contribution.
1250 if ($isQuickConfig) {
1251 $params['is_quick_config'] = 1;
1252 }
1253
1254 // CRM-11956
1255 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1256 // if non_deductible_amount does NOT exist - then calculate it depending on:
1257 // $ContributionType->is_deductible and whether there is a product (premium).
1258 if (!isset($params['non_deductible_amount']) || (!empty($params['non_deductible_amount']))) {
1259 $contributionType = new CRM_Financial_DAO_FinancialType();
1260 $contributionType->id = $params['financial_type_id'];
1261 if (!$contributionType->find(TRUE)) {
1262 CRM_Core_Error::fatal('Could not find a system table');
1263 }
1264 if ($contributionType->is_deductible) {
1265
1266 if (isset($formValues['product_name'][0])) {
1267 $selectProduct = $formValues['product_name'][0];
1268 }
1269 // if there is a product - compare the value to the contribution amount
1270 if (isset($selectProduct)) {
1271 $productDAO = new CRM_Contribute_DAO_Product();
1272 $productDAO->id = $selectProduct;
1273 $productDAO->find(TRUE);
1274 // product value exceeds contribution amount
1275 if ($params['total_amount'] < $productDAO->price) {
1276 $params['non_deductible_amount'] = $params['total_amount'];
1277 }
1278 // product value does NOT exceed contribution amount
1279 else {
1280 $params['non_deductible_amount'] = $productDAO->price;
1281 }
1282 }
1283 // contribution is deductible - but there is no product
1284 else {
1285 $params['non_deductible_amount'] = '0.00';
1286 }
1287 }
1288 // contribution is NOT deductible
1289 else {
1290 $params['non_deductible_amount'] = $params['total_amount'];
1291 }
1292 }
1293
1294 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1295
1296 // process associated membership / participant, CRM-4395
1297 $relatedComponentStatusMsg = NULL;
1298 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1299 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1300 $contribution->contribution_status_id,
1301 CRM_Utils_Array::value('contribution_status_id',
1302 $this->_values
1303 )
1304 );
1305 }
1306
1307 //process note
1308 if ($contribution->id && isset($formValues['note'])) {
1309 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1310 }
1311
1312 //process premium
1313 if ($contribution->id && isset($formValues['product_name'][0])) {
1314 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1315 $this->_premiumID, $this->_options
1316 );
1317 }
1318
1319 //send receipt mail.
1320 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1321 $formValues['contact_id'] = $this->_contactID;
1322 $formValues['contribution_id'] = $contribution->id;
1323
1324 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1325
1326 // to get 'from email id' for send receipt
1327 $this->fromEmailId = $formValues['from_email_address'];
1328 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1329 }
1330
1331 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1332 $contribution->id,
1333 'id',
1334 'contribution_id'
1335 );
1336
1337 //update pledge payment status.
1338 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1339 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1340 ) {
1341
1342 if ($this->_ppID) {
1343 //store contribution id in payment record.
1344 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1345 }
1346 else {
1347 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1348 $contribution->id,
1349 'id',
1350 'contribution_id'
1351 );
1352 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1353 $contribution->id,
1354 'pledge_id',
1355 'contribution_id'
1356 );
1357 }
1358
1359 $adjustTotalAmount = FALSE;
1360 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1361 $adjustTotalAmount = TRUE;
1362 }
1363
1364 $updatePledgePaymentStatus = FALSE;
1365 //do only if either the status or the amount has changed
1366 if ($this->_action & CRM_Core_Action::ADD) {
1367 $updatePledgePaymentStatus = TRUE;
1368 }
1369 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1370 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1371 ) {
1372 $updatePledgePaymentStatus = TRUE;
1373 }
1374
1375 if ($updatePledgePaymentStatus) {
1376 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1377 array($this->_ppID),
1378 $contribution->contribution_status_id,
1379 NULL,
1380 $contribution->total_amount,
1381 $adjustTotalAmount
1382 );
1383 }
1384 }
1385
1386 $statusMsg = ts('The contribution record has been saved.');
1387 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1388 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1389 }
1390
1391 if ($relatedComponentStatusMsg) {
1392 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1393 }
1394
1395 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1396 //Offline Contribution ends.
1397 }
1398 $buttonName = $this->controller->getButtonName();
1399 if ($this->_context == 'standalone') {
1400 if ($buttonName == $this->getButtonName('upload', 'new')) {
1401 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1402 'reset=1&action=add&context=standalone'
1403 ));
1404 }
1405 else {
1406 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1407 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1408 ));
1409 }
1410 }
1411 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1412 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1413 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1414 ));
1415 }
1416 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1417 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1418 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1419 ));
1420 }
1421
1422 //store contribution ID if not yet set (on create)
1423 if ( empty($this->_id) && !empty($contribution->id) ) {
1424 $this->_id = $contribution->id;
1425 }
1426 }
1427
1428 /**
1429 * @param $submittedValues
1430 * @param $config
1431 * @param $session CRM_Core_Session
1432 * @param $lineItem
1433 *
1434 * @throws CRM_Core_Exception
1435 */
1436 public function processCreditCard($submittedValues, $config, $session, $lineItem) {
1437 $sendReceipt = $contribution = FALSE;
1438 $unsetParams = array(
1439 'trxn_id',
1440 'payment_instrument_id',
1441 'contribution_status_id',
1442 'cancel_date',
1443 'cancel_reason',
1444 );
1445 foreach ($unsetParams as $key) {
1446 if (isset($submittedValues[$key])) {
1447 unset($submittedValues[$key]);
1448 }
1449 }
1450
1451 // CRM-12680 set $_lineItem if its not set
1452 if (empty($this->_lineItem) && !empty($lineItem)) {
1453 $this->_lineItem = $lineItem;
1454 }
1455
1456 //Get the require fields value only.
1457 $params = $this->_params = $submittedValues;
1458
1459 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1460 $this->_mode
1461 );
1462
1463 //get the payment processor id as per mode.
1464 $this->_params['payment_processor'] = $params['payment_processor_id'] =
1465 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1466
1467 $now = date('YmdHis');
1468 $fields = array();
1469
1470 // we need to retrieve email address
1471 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1472 list($this->userDisplayName,
1473 $this->userEmail
1474 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1475 $this->assign('displayName', $this->userDisplayName);
1476 }
1477
1478 //set email for primary location.
1479 $fields['email-Primary'] = 1;
1480 $params['email-Primary'] = $this->userEmail;
1481
1482 // now set the values for the billing location.
1483 foreach (array_keys($this->_fields) as $name) {
1484 $fields[$name] = 1;
1485 }
1486
1487 // also add location name to the array
1488 $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);
1489 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1490 $fields["address_name-{$this->_bltID}"] = 1;
1491
1492 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1493 $this->_contactID,
1494 'contact_type'
1495 );
1496
1497 $nameFields = array('first_name', 'middle_name', 'last_name');
1498 foreach ($nameFields as $name) {
1499 $fields[$name] = 1;
1500 if (array_key_exists("billing_$name", $params)) {
1501 $params[$name] = $params["billing_{$name}"];
1502 $params['preserveDBName'] = TRUE;
1503 }
1504 }
1505
1506 if (!empty($params['source'])) {
1507 unset($params['source']);
1508 }
1509 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1510 $this->_contactID,
1511 NULL, NULL,
1512 $ctype
1513 );
1514
1515 // add all the additional payment params we need
1516 $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}"]);
1517 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1518
1519 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
1520 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1521 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1522 }
1523 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1524 $this->_params['amount'] = $this->_params['total_amount'];
1525 $this->_params['amount_level'] = 0;
1526 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1527 $this->_params,
1528 $config->defaultCurrency
1529 );
1530 $this->_params['payment_action'] = 'Sale';
1531 if (!empty($this->_params['receive_date'])) {
1532 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1533 }
1534
1535 if (!empty($params['soft_credit_to'])) {
1536 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1537 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1538 }
1539
1540 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1541 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1542 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1543
1544 //Add common data to formatted params
1545 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1546
1547 if (empty($this->_params['invoice_id'])) {
1548 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1549 }
1550 else {
1551 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1552 }
1553
1554 // at this point we've created a contact and stored its address etc
1555 // all the payment processors expect the name and address to be in the
1556 // so we copy stuff over to first_name etc.
1557 $paymentParams = $this->_params;
1558 $paymentParams['contactID'] = $this->_contactID;
1559 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1560
1561 $contributionType = new CRM_Financial_DAO_FinancialType();
1562 $contributionType->id = $params['financial_type_id'];
1563 if (!$contributionType->find(TRUE)) {
1564 CRM_Core_Error::fatal('Could not find a system table');
1565 }
1566
1567 // add some financial type details to the params list
1568 // if folks need to use it
1569 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1570 $paymentParams['contributionPageID'] = NULL;
1571 if (!empty($this->_params['is_email_receipt'])) {
1572 $paymentParams['email'] = $this->userEmail;
1573 $paymentParams['is_email_receipt'] = 1;
1574 }
1575 else {
1576 $paymentParams['is_email_receipt'] = 0;
1577 $this->_params['is_email_receipt'] = 0;
1578 }
1579 if (!empty($this->_params['receive_date'])) {
1580 $paymentParams['receive_date'] = $this->_params['receive_date'];
1581 }
1582
1583 $result = NULL;
1584
1585 // For recurring contribution, create Contribution Record first.
1586 // Contribution ID, Recurring ID and Contact ID needed
1587 // When we get a callback from the payment processor, CRM-7115
1588 if (!empty($paymentParams['is_recur'])) {
1589 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1590 $this->_params,
1591 $result,
1592 $this->_contactID,
1593 $contributionType,
1594 FALSE,
1595 TRUE,
1596 FALSE
1597 );
1598 $paymentParams['contributionID'] = $contribution->id;
1599 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1600 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1601 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1602 }
1603
1604 if ($paymentParams['amount'] > 0.0) {
1605 // force a re-get of the payment processor in case the form changed it, CRM-7179
1606 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1607 $result = $payment->doDirectPayment($paymentParams);
1608 }
1609
1610 if (is_a($result, 'CRM_Core_Error')) {
1611 //make sure to cleanup db for recurring case.
1612 if (!empty($paymentParams['contributionID'])) {
1613 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1614 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1615 }
1616 if (!empty($paymentParams['contributionRecurID'])) {
1617 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1618 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1619 }
1620
1621 //set the contribution mode.
1622 $urlParams = "action=add&cid={$this->_contactID}";
1623 if ($this->_mode) {
1624 $urlParams .= "&mode={$this->_mode}";
1625 }
1626 if (!empty($this->_ppID)) {
1627 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1628 }
1629 CRM_Core_Error::displaySessionError($result);
1630 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
1631 }
1632
1633 if ($result) {
1634 $this->_params = array_merge($this->_params, $result);
1635 }
1636
1637 $this->_params['receive_date'] = $now;
1638
1639 if (!empty($this->_params['is_email_receipt'])) {
1640 $this->_params['receipt_date'] = $now;
1641 }
1642 else {
1643 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1644 $params['receipt_date_time'], TRUE
1645 );
1646 }
1647
1648 $this->set('params', $this->_params);
1649 $this->assign('trxn_id', $result['trxn_id']);
1650 $this->assign('receive_date', $this->_params['receive_date']);
1651
1652 // result has all the stuff we need
1653 // lets archive it to a financial transaction
1654 if ($contributionType->is_deductible) {
1655 $this->assign('is_deductible', TRUE);
1656 $this->set('is_deductible', TRUE);
1657 }
1658
1659 // set source if not set
1660 if (empty($this->_params['source'])) {
1661 $userID = $session->get('userID');
1662 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1663 'sort_name'
1664 );
1665 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1666 }
1667
1668 // build custom data getFields array
1669 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1670 CRM_Utils_Array::value('financial_type_id', $params)
1671 );
1672 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1673 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1674 );
1675 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1676 $customFields,
1677 $this->_id,
1678 'Contribution'
1679 );
1680
1681
1682 if (empty($paymentParams['is_recur'])) {
1683 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1684 $this->_params,
1685 $result,
1686 $this->_contactID,
1687 $contributionType,
1688 FALSE, FALSE, FALSE
1689 );
1690 }
1691
1692 //send receipt mail.
1693 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1694 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1695 $this->_params['contact_id'] = $this->_contactID;
1696 $this->_params['contribution_id'] = $contribution->id;
1697 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1698 }
1699
1700 //process the note
1701 if ($contribution->id && isset($params['note'])) {
1702 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1703 }
1704 //process premium
1705 if ($contribution->id && isset($params['product_name'][0])) {
1706 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1707 }
1708
1709 //update pledge payment status.
1710 if ($this->_ppID && $contribution->id) {
1711 //store contribution id in payment record.
1712 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1713
1714 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1715 array($this->_ppID),
1716 $contribution->contribution_status_id,
1717 NULL,
1718 $contribution->total_amount
1719 );
1720 }
1721
1722 if ($contribution->id) {
1723 $statusMsg = ts('The contribution record has been processed.');
1724 if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
1725 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1726 }
1727 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1728 }
1729 }
1730 }
1731