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