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