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