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