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