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