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