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