Merge branch 'CRM-13014' of git://github.com/eileenmcnaughton/civicrm-core into pull...
[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 foreach (array_keys($lineItems) as $id) {
1066 $lineItems[$id]['id'] = $id;
1067 }
1068 $itemId = key($lineItems);
1069 $fieldType = NULL;
1070 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
1071 $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
1072 }
1073 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1074 // 10117 update th line items for participants
1075 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1076 $lineItem[$this->_priceSetId] = $lineItems;
1077 }
1078 $isQuickConfig = 0;
1079 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
1080 $isQuickConfig = 1;
1081 }
1082 //CRM-11529 for quick config backoffice transactions
1083 //when financial_type_id is passed in form, update the
1084 //lineitems with the financial type selected in form
1085 if ($isQuickConfig && CRM_Utils_Array::value('financial_type_id', $submittedValues)
1086 && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
1087 foreach ($lineItem[$this->_priceSetId] as &$values) {
1088 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1089 }
1090 }
1091
1092 if (!isset($submittedValues['total_amount'])) {
1093 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1094 }
1095 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1096
1097 if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
1098 $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
1099 }
1100
1101 // set the contact, when contact is selected
1102 if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
1103 $this->_contactID = $submittedValues['contact_select_id'][1];
1104 }
1105
1106 $config = CRM_Core_Config::singleton();
1107
1108 //Credit Card Contribution.
1109 if ($this->_mode) {
1110 $this->processCreditCard($submittedValues, $config, $session, $pId, $lineItem);
1111 }
1112 else {
1113 //Offline Contribution.
1114 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1115
1116 // get the required field value only.
1117 $formValues = $submittedValues;
1118 $params = $ids = array();
1119
1120 $params['contact_id'] = $this->_contactID;
1121
1122 $params['currency'] = $this->getCurrency($submittedValues);
1123
1124 $fields = array(
1125 'financial_type_id',
1126 'contribution_status_id',
1127 'payment_instrument_id',
1128 'cancel_reason',
1129 'source',
1130 'check_number',
1131 'soft_credit_to',
1132 'pcp_made_through_id',
1133 'pcp_display_in_roll',
1134 'pcp_roll_nickname',
1135 'pcp_personal_note',
1136 );
1137 foreach ($fields as $f) {
1138 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1139 }
1140
1141 if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
1142 $params['softID'] = $softID;
1143 }
1144 //if priceset is used, no need to cleanup money
1145 //CRM-5740
1146 if ($priceSetId) {
1147 $params['skipCleanMoney'] = 1;
1148 }
1149
1150 $dates = array(
1151 'receive_date',
1152 'receipt_date',
1153 'cancel_date',
1154 );
1155
1156 foreach ($dates as $d) {
1157 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1158 }
1159
1160 if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1161 $params['receipt_date'] = date("Y-m-d");
1162 }
1163
1164 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1165 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
1166 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1167 $params['cancel_date'] = date("Y-m-d");
1168 }
1169 }
1170 else {
1171 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1172 }
1173
1174 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1175 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1176 $params['is_pay_later'] = 1;
1177 }
1178
1179 $ids['contribution'] = $params['id'] = $this->_id;
1180
1181 //Add Additional common information to formatted params
1182 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1183 if ($pId) {
1184 $params['contribution_mode'] = 'participant';
1185 $params['participant_id'] = $pId;
1186 $params['skipLineItem'] = 1;
1187 }
1188 $params['line_item'] = $lineItem;
1189 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1190 //create contribution.
1191 if ($isQuickConfig) {
1192 $params['is_quick_config'] = 1;
1193 }
1194
1195 // CRM-11956
1196 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1197 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1198 $params['non_deductible_amount'] = $params['non_deductible_amount'];
1199 }
1200 // if non_deductible_amount does NOT exist - then calculate it depending on:
1201 // $ContributionType->is_deductible and whether there is a product (premium).
1202 else {
1203 $contributionType = new CRM_Financial_DAO_FinancialType();
1204 $contributionType->id = $params['financial_type_id'];
1205 if (!$contributionType->find(TRUE)) {
1206 CRM_Core_Error::fatal('Could not find a system table');
1207 }
1208 if ($contributionType->is_deductible) {
1209
1210 if (isset($formValues['product_name'][0])) {
1211 $selectProduct = $formValues['product_name'][0];
1212 }
1213 // if there is a product - compare the value to the contribution amount
1214 if (isset($selectProduct))
1215 {
1216 $productDAO = new CRM_Contribute_DAO_Product();
1217 $productDAO->id = $selectProduct;
1218 $productDAO->find(TRUE);
1219 // product value exceeds contribution amount
1220 if ($params['total_amount'] < $productDAO->price) {
1221 $params['non_deductible_amount'] = $params['total_amount'];
1222 }
1223 // product value does NOT exceed contribution amount
1224 else {
1225 $params['non_deductible_amount'] = $productDAO->price;
1226 }
1227 }
1228 // contribution is deductible - but there is no product
1229 else {
1230 $params['non_deductible_amount'] = '0.00';
1231 }
1232 }
1233 // contribution is NOT deductible
1234 else {
1235 $params['non_deductible_amount'] = $params['total_amount'];
1236 }
1237 }
1238
1239 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1240
1241 // process associated membership / participant, CRM-4395
1242 $relatedComponentStatusMsg = NULL;
1243 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1244 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1245 $contribution->contribution_status_id,
1246 CRM_Utils_Array::value('contribution_status_id',
1247 $this->_values
1248 )
1249 );
1250 }
1251
1252 //process note
1253 if ($contribution->id && isset($formValues['note'])) {
1254 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1255 }
1256
1257 //process premium
1258 if ($contribution->id && isset($formValues['product_name'][0])) {
1259 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1260 $this->_premiumID, $this->_options
1261 );
1262 }
1263
1264 //send receipt mail.
1265 if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1266 $formValues['contact_id'] = $this->_contactID;
1267 $formValues['contribution_id'] = $contribution->id;
1268
1269 // to get 'from email id' for send receipt
1270 $this->fromEmailId = $formValues['from_email_address'];
1271 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1272 }
1273
1274 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1275 $contribution->id,
1276 'id',
1277 'contribution_id'
1278 );
1279
1280 //update pledge payment status.
1281 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1282 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1283 ) {
1284
1285 if ($this->_ppID) {
1286 //store contribution id in payment record.
1287 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1288 }
1289 else {
1290 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1291 $contribution->id,
1292 'id',
1293 'contribution_id'
1294 );
1295 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1296 $contribution->id,
1297 'pledge_id',
1298 'contribution_id'
1299 );
1300 }
1301
1302 $adjustTotalAmount = FALSE;
1303 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1304 $adjustTotalAmount = TRUE;
1305 }
1306
1307 $updatePledgePaymentStatus = FALSE;
1308 //do only if either the status or the amount has changed
1309 if ($this->_action & CRM_Core_Action::ADD) {
1310 $updatePledgePaymentStatus = TRUE;
1311 }
1312 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1313 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1314 ) {
1315 $updatePledgePaymentStatus = TRUE;
1316 }
1317
1318 if ($updatePledgePaymentStatus) {
1319 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1320 array($this->_ppID),
1321 $contribution->contribution_status_id,
1322 NULL,
1323 $contribution->total_amount,
1324 $adjustTotalAmount
1325 );
1326 }
1327 }
1328
1329 $statusMsg = ts('The contribution record has been saved.');
1330 if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
1331 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1332 }
1333
1334 if ($relatedComponentStatusMsg) {
1335 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1336 }
1337
1338 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1339 //Offline Contribution ends.
1340 }
1341 $buttonName = $this->controller->getButtonName();
1342 if ($this->_context == 'standalone') {
1343 if ($buttonName == $this->getButtonName('upload', 'new')) {
1344 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1345 'reset=1&action=add&context=standalone'
1346 ));
1347 }
1348 else {
1349 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1350 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1351 ));
1352 }
1353 }
1354 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1355 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1356 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1357 ));
1358 }
1359 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1360 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1361 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1362 ));
1363 }
1364 }
1365
1366 public function processCreditCard($submittedValues, $config, $session, $pId, $lineItem) {
1367 $unsetParams = array(
1368 'trxn_id',
1369 'payment_instrument_id',
1370 'contribution_status_id',
1371 'cancel_date',
1372 'cancel_reason',
1373 );
1374 foreach ($unsetParams as $key) {
1375 if (isset($submittedValues[$key])) {
1376 unset($submittedValues[$key]);
1377 }
1378 }
1379
1380 // CRM-12680 set $_lineItem if its not set
1381 if (empty($this->_lineItem) && !empty($lineItem)) {
1382 $this->_lineItem = $lineItem;
1383 }
1384
1385 //Get the rquire fields value only.
1386 $params = $this->_params = $submittedValues;
1387
1388 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1389 $this->_mode
1390 );
1391
1392 //get the payment processor id as per mode.
1393 $this->_params['payment_processor'] = $params['payment_processor_id'] =
1394 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1395
1396 $now = date('YmdHis');
1397 $fields = array();
1398
1399 // we need to retrieve email address
1400 if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
1401 list($this->userDisplayName,
1402 $this->userEmail
1403 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1404 $this->assign('displayName', $this->userDisplayName);
1405 }
1406
1407 //set email for primary location.
1408 $fields['email-Primary'] = 1;
1409 $params['email-Primary'] = $this->userEmail;
1410
1411 // now set the values for the billing location.
1412 foreach ($this->_fields as $name => $dontCare) {
1413 $fields[$name] = 1;
1414 }
1415
1416 // also add location name to the array
1417 $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);
1418 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1419 $fields["address_name-{$this->_bltID}"] = 1;
1420
1421 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1422 $this->_contactID,
1423 'contact_type'
1424 );
1425
1426 $nameFields = array('first_name', 'middle_name', 'last_name');
1427 foreach ($nameFields as $name) {
1428 $fields[$name] = 1;
1429 if (array_key_exists("billing_$name", $params)) {
1430 $params[$name] = $params["billing_{$name}"];
1431 $params['preserveDBName'] = TRUE;
1432 }
1433 }
1434
1435 if (CRM_Utils_Array::value('source', $params)) {
1436 unset($params['source']);
1437 }
1438 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1439 $this->_contactID,
1440 NULL, NULL,
1441 $ctype
1442 );
1443
1444 // add all the additioanl payment params we need
1445 $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}"]);
1446 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1447
1448 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
1449 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1450 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1451 }
1452 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1453 $this->_params['amount'] = $this->_params['total_amount'];
1454 $this->_params['amount_level'] = 0;
1455 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1456 $this->_params,
1457 $config->defaultCurrency
1458 );
1459 $this->_params['payment_action'] = 'Sale';
1460 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1461 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1462 }
1463
1464 if (CRM_Utils_Array::value('soft_credit_to', $params)) {
1465 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1466 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1467 }
1468
1469 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1470 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1471 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1472
1473 //Add common data to formatted params
1474 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1475
1476 if (empty($this->_params['invoice_id'])) {
1477 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1478 }
1479 else {
1480 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1481 }
1482
1483 // at this point we've created a contact and stored its address etc
1484 // all the payment processors expect the name and address to be in the
1485 // so we copy stuff over to first_name etc.
1486 $paymentParams = $this->_params;
1487 $paymentParams['contactID'] = $this->_contactID;
1488 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1489
1490 $contributionType = new CRM_Financial_DAO_FinancialType();
1491 $contributionType->id = $params['financial_type_id'];
1492 if (!$contributionType->find(TRUE)) {
1493 CRM_Core_Error::fatal('Could not find a system table');
1494 }
1495
1496 // add some financial type details to the params list
1497 // if folks need to use it
1498 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1499 $paymentParams['contributionPageID'] = NULL;
1500 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1501 $paymentParams['email'] = $this->userEmail;
1502 $paymentParams['is_email_receipt'] = 1;
1503 }
1504 else {
1505 $paymentParams['is_email_receipt'] = 0;
1506 $this->_params['is_email_receipt'] = 0;
1507 }
1508 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1509 $paymentParams['receive_date'] = $this->_params['receive_date'];
1510 }
1511 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1512 $paymentParams['receive_date'] = $this->_params['receive_date'];
1513 }
1514
1515 $result = NULL;
1516
1517 // For recurring contribution, create Contribution Record first.
1518 // Contribution ID, Recurring ID and Contact ID needed
1519 // When we get a callback from the payment processor, CRM-7115
1520 if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
1521 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1522 $this->_params,
1523 $result,
1524 $this->_contactID,
1525 $contributionType,
1526 FALSE,
1527 TRUE,
1528 FALSE
1529 );
1530 $paymentParams['contributionID'] = $contribution->id;
1531 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1532 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1533 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1534 }
1535
1536 if ($paymentParams['amount'] > 0.0) {
1537 // force a reget of the payment processor in case the form changed it, CRM-7179
1538 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1539 $result = $payment->doDirectPayment($paymentParams);
1540 }
1541
1542 if (is_a($result, 'CRM_Core_Error')) {
1543 //make sure to cleanup db for recurring case.
1544 if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
1545 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1546 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1547 }
1548 if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
1549 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1550 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1551 }
1552
1553 //set the contribution mode.
1554 $urlParams = "action=add&cid={$this->_contactID}";
1555 if ($this->_mode) {
1556 $urlParams .= "&mode={$this->_mode}";
1557 }
1558 if (!empty($this->_ppID)) {
1559 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1560 }
1561 CRM_Core_Error::displaySessionError($result);
1562 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
1563 }
1564
1565 if ($result) {
1566 $this->_params = array_merge($this->_params, $result);
1567 }
1568
1569 $this->_params['receive_date'] = $now;
1570
1571 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1572 $this->_params['receipt_date'] = $now;
1573 }
1574 else {
1575 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1576 $params['receipt_date_time'], TRUE
1577 );
1578 }
1579
1580 $this->set('params', $this->_params);
1581 $this->assign('trxn_id', $result['trxn_id']);
1582 $this->assign('receive_date', $this->_params['receive_date']);
1583
1584 // result has all the stuff we need
1585 // lets archive it to a financial transaction
1586 if ($contributionType->is_deductible) {
1587 $this->assign('is_deductible', TRUE);
1588 $this->set('is_deductible', TRUE);
1589 }
1590
1591 // set source if not set
1592 if (empty($this->_params['source'])) {
1593 $userID = $session->get('userID');
1594 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1595 'sort_name'
1596 );
1597 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1598 }
1599
1600 // build custom data getFields array
1601 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1602 CRM_Utils_Array::value('financial_type_id', $params)
1603 );
1604 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1605 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1606 );
1607 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1608 $customFields,
1609 $this->_id,
1610 'Contribution'
1611 );
1612
1613
1614 if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
1615 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1616 $this->_params,
1617 $result,
1618 $this->_contactID,
1619 $contributionType,
1620 FALSE, FALSE, FALSE
1621 );
1622 }
1623
1624 //send receipt mail.
1625 if ($contribution->id &&
1626 CRM_Utils_Array::value('is_email_receipt', $this->_params)
1627 ) {
1628 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1629 $this->_params['contact_id'] = $this->_contactID;
1630 $this->_params['contribution_id'] = $contribution->id;
1631 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1632 }
1633
1634 //process the note
1635 if ($contribution->id && isset($params['note'])) {
1636 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1637 }
1638 //process premium
1639 if ($contribution->id && isset($params['product_name'][0])) {
1640 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1641 }
1642
1643 //update pledge payment status.
1644 if ($this->_ppID && $contribution->id) {
1645 //store contribution id in payment record.
1646 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1647
1648 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1649 array($this->_ppID),
1650 $contribution->contribution_status_id,
1651 NULL,
1652 $contribution->total_amount
1653 );
1654 }
1655
1656 if ($contribution->id) {
1657 $statusMsg = ts('The contribution record has been processed.');
1658 if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
1659 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1660 }
1661 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1662 }
1663 }
1664 }
1665