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