VAT-572 Display Invoicing functionality based on admin globle setting under CiviContr...
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 useful, 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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * form to process actions on the group aspect of Custom Data
38 */
39 class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
40
41 /**
42 * the id of the contact associated with this contribution
43 *
44 * @var int
45 * @public
46 */
47 public $_contactID;
48
49
50 /**
51 * The id of the contribution object that is created when the form is submitted
52 *
53 * @var int
54 * @public
55 */
56 public $_contributionID;
57
58 /**
59 * Function to set variables up before form is built
60 *
61 * @return void
62 * @access public
63 */
64 public function preProcess() {
65 $config = CRM_Core_Config::singleton();
66 parent::preProcess();
67
68 // lineItem isn't set until Register postProcess
69 $this->_lineItem = $this->get('lineItem');
70 $this->_paymentProcessor = $this->get('paymentProcessor');
71
72 if ($this->_contributeMode == 'express') {
73 // rfp == redirect from paypal
74 $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
75 CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
76 );
77 if ($rfp) {
78 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
79 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
80
81 $this->_params['payer'] = $expressParams['payer'];
82 $this->_params['payer_id'] = $expressParams['payer_id'];
83 $this->_params['payer_status'] = $expressParams['payer_status'];
84
85 CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE);
86
87 // fix state and country id if present
88 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"]) && $this->_params["billing_state_province_id-{$this->_bltID}"]) {
89 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
90 }
91 if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) {
92 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
93 }
94
95 // set a few other parameters for PayPal
96 $this->_params['token'] = $this->get('token');
97
98 $this->_params['amount'] = $this->get('amount');
99
100 if (!empty($this->_membershipBlock)){
101 $this->_params['selectMembership'] = $this->get('selectMembership');
102 }
103 // we use this here to incorporate any changes made by folks in hooks
104 $this->_params['currencyID'] = $config->defaultCurrency;
105
106 $this->_params['payment_action'] = 'Sale';
107
108 // also merge all the other values from the profile fields
109 $values = $this->controller->exportValues('Main');
110 $skipFields = array(
111 'amount', 'amount_other',
112 "billing_street_address-{$this->_bltID}",
113 "billing_city-{$this->_bltID}",
114 "billing_state_province_id-{$this->_bltID}",
115 "billing_postal_code-{$this->_bltID}",
116 "billing_country_id-{$this->_bltID}",
117 );
118 foreach ($values as $name => $value) {
119 // skip amount field
120 if (!in_array($name, $skipFields)) {
121 $this->_params[$name] = $value;
122 }
123 }
124 $this->set('getExpressCheckoutDetails', $this->_params);
125 }
126 else {
127 $this->_params = $this->get('getExpressCheckoutDetails');
128 }
129 }
130 else {
131 $this->_params = $this->controller->exportValues('Main');
132
133 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
134 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
135 }
136 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
137 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
138 }
139
140 if (isset($this->_params['credit_card_exp_date'])) {
141 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
142 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
143 }
144
145 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
146 $this->_params['amount'] = $this->get('amount');
147 $this->_params['tax_amount'] = $this->get('tax_amount');
148
149 $this->_useForMember = $this->get('useForMember');
150
151 if (isset($this->_params['amount'])) {
152 $priceField = new CRM_Price_DAO_PriceField();
153 $priceField->price_set_id = $this->_params['priceSetId'];
154 $priceField->orderBy('weight');
155 $priceField->find();
156 $contriPriceId = NULL;
157 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
158 while ($priceField->fetch()) {
159 if ($priceField->name == "contribution_amount") {
160 $contriPriceId = $priceField->id;
161 }
162 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
163 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
164 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
165 $this->_params["price_{$priceField->id}"], 'label');
166 }
167 if ($priceField->name == "membership_amount") {
168 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
169 $this->_params["price_{$priceField->id}"], 'membership_type_id');
170 }
171 } // if separate payment we set contribution amount to be null, so that it will not show contribution amount same as membership amount.
172 elseif ((CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)) && !empty($this->_values['fee'][$priceField->id]) && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
173 && CRM_Utils_Array::value("price_{$contriPriceId}", $this->_params) < 1 && empty($this->_params["price_{$priceField->id}"])) {
174 $this->_params['amount'] = null;
175 }
176
177 // Fix for CRM-14375 - If we are using separate payments and "no
178 // thank you" is selected for the additional contribution, set
179 // contribution amount to be null, so that it will not show
180 // contribution amount same as membership amount.
181 if ($this->_membershipBlock['is_separate_payment']
182 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
183 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
184 ) {
185 $this->_params['amount'] = null;
186 }
187 }
188 }
189 $this->_params['currencyID'] = $config->defaultCurrency;
190 $this->_params['payment_action'] = 'Sale';
191 }
192
193 $this->_params['is_pay_later'] = $this->get('is_pay_later');
194 $this->assign('is_pay_later', $this->_params['is_pay_later']);
195 if ($this->_params['is_pay_later']) {
196 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
197 }
198 // if onbehalf-of-organization
199 if (!empty($this->_params['hidden_onbehalf_profile'])) {
200 if (!empty($this->_params['org_option']) && !empty($this->_params['organization_id'])) {
201 if (!empty($this->_params['onbehalfof_id'])) {
202 $this->_params['organization_id'] = $this->_params['onbehalfof_id'];
203 }
204 }
205
206 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
207 $addressBlocks = array(
208 'street_address', 'city', 'state_province',
209 'postal_code', 'country', 'supplemental_address_1',
210 'supplemental_address_2', 'supplemental_address_3',
211 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name',
212 );
213
214 $blocks = array('email', 'phone', 'im', 'url', 'openid');
215 foreach ($this->_params['onbehalf'] as $loc => $value) {
216 $field = $typeId = NULL;
217 if (strstr($loc, '-')) {
218 list($field, $locType) = explode('-', $loc);
219 }
220
221 if (in_array($field, $addressBlocks)) {
222 if ($locType == 'Primary') {
223 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
224 $locType = $defaultLocationType->id;
225 }
226
227 if ($field == 'country') {
228 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
229 }
230 elseif ($field == 'state_province') {
231 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
232 }
233
234 $isPrimary = 1;
235 if (isset($this->_params['onbehalf_location']['address'])
236 && count($this->_params['onbehalf_location']['address']) > 0) {
237 $isPrimary = 0;
238 }
239
240 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
241 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
242 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
243 }
244 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
245 }
246 elseif (in_array($field, $blocks)) {
247 if (!$typeId || is_numeric($typeId)) {
248 $blockName = $fieldName = $field;
249 $locationType = 'location_type_id';
250 if ( $locType == 'Primary' ) {
251 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
252 $locationValue = $defaultLocationType->id;
253 }
254 else {
255 $locationValue = $locType;
256 }
257 $locTypeId = '';
258 $phoneExtField = array();
259
260 if ($field == 'url') {
261 $blockName = 'website';
262 $locationType = 'website_type_id';
263 list($field, $locationValue) = explode('-', $loc);
264 }
265 elseif ($field == 'im') {
266 $fieldName = 'name';
267 $locTypeId = 'provider_id';
268 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
269 }
270 elseif ($field == 'phone') {
271 list($field, $locType, $typeId) = explode('-', $loc);
272 $locTypeId = 'phone_type_id';
273
274 //check if extension field exists
275 $extField = str_replace('phone','phone_ext', $loc);
276 if (isset($this->_params['onbehalf'][$extField])) {
277 $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
278 }
279 }
280
281 $isPrimary = 1;
282 if ( isset ($this->_params['onbehalf_location'][$blockName] )
283 && count( $this->_params['onbehalf_location'][$blockName] ) > 0 ) {
284 $isPrimary = 0;
285 }
286 if ($locationValue) {
287 $blockValues = array(
288 $fieldName => $value,
289 $locationType => $locationValue,
290 'is_primary' => $isPrimary,
291 );
292
293 if ($locTypeId) {
294 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
295 }
296 if (!empty($phoneExtField)) {
297 $blockValues = array_merge($blockValues, $phoneExtField);
298 }
299
300 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
301 }
302 }
303 }
304 elseif (strstr($loc, 'custom')) {
305 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
306 $value = $this->_params['onbehalf']["{$loc}_id"];
307 }
308 $this->_params['onbehalf_location']["{$loc}"] = $value;
309 }
310 else {
311 if ($loc == 'contact_sub_type') {
312 $this->_params['onbehalf_location'][$loc] = $value;
313 }
314 else {
315 $this->_params['onbehalf_location'][$field] = $value;
316 }
317 }
318 }
319 }
320 elseif (!empty($this->_values['is_for_organization'])) {
321 // no on behalf of an organization, CRM-5519
322 // so reset loc blocks from main params.
323 foreach (array(
324 'phone', 'email', 'address') as $blk) {
325 if (isset($this->_params[$blk])) {
326 unset($this->_params[$blk]);
327 }
328 }
329 }
330
331 // if auto renew checkbox is set, initiate a open-ended recurring membership
332 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) &&
333 CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) {
334
335 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
336 // check if price set is not quick config
337 if (!empty($this->_params['priceSetId']) && !$isQuickConfig) {
338 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
339 }
340 else {
341 // FIXME: set interval and unit based on selected membership type
342 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
343 $this->_params['selectMembership'], 'duration_interval'
344 );
345 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
346 $this->_params['selectMembership'], 'duration_unit'
347 );
348 }
349 }
350
351 if ($this->_pcpId) {
352 $params = $this->processPcp($this, $this->_params);
353 $this->_params = $params;
354 }
355 $this->_params['invoiceID'] = $this->get('invoiceID');
356
357 //carry campaign from profile.
358 if (array_key_exists('contribution_campaign_id', $this->_params)) {
359 $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
360 }
361
362 // assign contribution page id to the template so we can add css class for it
363 $this->assign('contributionPageID', $this->_id);
364
365 $this->set('params', $this->_params);
366 }
367
368 /**
369 * Function to actually build the form
370 *
371 * @return void
372 * @access public
373 */
374 public function buildQuickForm() {
375 $this->assignToTemplate();
376
377 $params = $this->_params;
378 // make sure we have values for it
379 if ($this->_honor_block_is_active && !empty($params['soft_credit_type_id'])) {
380 $honorName = null;
381 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
382
383 $this->assign('honor_block_is_active', $this->_honor_block_is_active);
384 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
385 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
386
387 $fieldTypes = array('Contact');
388 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']);
389 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
390 }
391 $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
392 $amount_block_is_active = $this->get('amount_block_is_active');
393 $this->assign('amount_block_is_active', $amount_block_is_active);
394
395 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
396 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
397 if ($invoicing) {
398 $getTaxDetails = FALSE;
399 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
400 foreach ($this->_lineItem as $key => $value) {
401 foreach ($value as $v) {
402 if (isset($v['tax_rate'])) {
403 if ($v['tax_rate'] != '') {
404 $getTaxDetails = TRUE;
405 }
406 }
407 }
408 }
409 $this->assign('getTaxDetails', $getTaxDetails);
410 $this->assign('taxTerm', $taxTerm);
411 $this->assign('totalTaxAmount', $params['tax_amount']);
412 }
413 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
414 $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
415 $productID = $params['selectProduct'];
416 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
417 $productID, $option
418 );
419 $this->set('productID', $productID);
420 $this->set('option', $option);
421 }
422 $config = CRM_Core_Config::singleton();
423 if (in_array('CiviMember', $config->enableComponents)) {
424 if (isset($params['selectMembership']) &&
425 $params['selectMembership'] != 'no_thanks'
426 ) {
427 CRM_Member_BAO_Membership::buildMembershipBlock($this,
428 $this->_id,
429 $this->_membershipContactID,
430 FALSE,
431 $params['selectMembership'],
432 FALSE
433 );
434 }
435 else {
436 $this->assign('membershipBlock', FALSE);
437 }
438 }
439 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
440 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
441
442 if (!empty($params['hidden_onbehalf_profile'])) {
443 $ufJoinParams = array(
444 'module' => 'onBehalf',
445 'entity_table' => 'civicrm_contribution_page',
446 'entity_id' => $this->_id,
447 );
448 $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
449 $profileId = $OnBehalfProfile[0];
450
451 $fieldTypes = array('Contact', 'Organization');
452 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
453 $fieldTypes = array_merge($fieldTypes, $contactSubType);
454 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
455 $fieldTypes = array_merge($fieldTypes, array('Membership'));
456 }
457 else {
458 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
459 }
460
461 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
462 }
463
464 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
465 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
466 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
467 $this->assign('lineItem', $this->_lineItem);
468 } else {
469 $this->assign('is_quick_config', 1);
470 $this->_params['is_quick_config'] = 1;
471 }
472 $this->assign('priceSetID', $this->_priceSetId);
473 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name');
474 if ($this->_paymentProcessor &&
475 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType)
476 && !$this->_params['is_pay_later'] && !($this->_amount == 0)
477 ) {
478 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
479 $this->add('image',
480 $this->_checkoutButtonName,
481 $this->_paymentProcessor['url_button'],
482 array('class' => 'form-submit')
483 );
484
485 $this->addButtons(array(
486 array(
487 'type' => 'back',
488 'name' => ts('<< Go Back'),
489 ),
490 )
491 );
492 }
493 else {
494 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
495 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
496 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
497 ) {
498 $contribButton = ts('Continue >>');
499 $this->assign('button', ts('Continue'));
500 }
501 else {
502 $contribButton = ts('Make Contribution');
503 $this->assign('button', ts('Make Contribution'));
504 }
505 $this->addButtons(array(
506 array(
507 'type' => 'next',
508 'name' => $contribButton,
509 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
510 'isDefault' => TRUE,
511 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
512 ),
513 array(
514 'type' => 'back',
515 'name' => ts('Go Back'),
516 ),
517 )
518 );
519 }
520
521 $defaults = array();
522 $fields = array();
523 foreach ($this->_fields as $name => $dontCare) {
524 if ($name != 'onbehalf' || $name != 'honor') {
525 $fields[$name] = 1;
526 }
527 }
528 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
529
530 $contact = $this->_params;
531 foreach ($fields as $name => $dontCare) {
532 if (isset($contact[$name])) {
533 $defaults[$name] = $contact[$name];
534 if (substr($name, 0, 7) == 'custom_') {
535 $timeField = "{$name}_time";
536 if (isset($contact[$timeField])) {
537 $defaults[$timeField] = $contact[$timeField];
538 }
539 if (isset($contact["{$name}_id"])) {
540 $defaults["{$name}_id"] = $contact["{$name}_id"];
541 }
542 }
543 elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) {
544 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
545 }
546 }
547 }
548
549 $this->assign('useForMember', $this->get('useForMember'));
550
551 // now fix all state country selectors
552 CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults);
553
554 $this->setDefaults($defaults);
555
556 $this->freeze();
557 }
558
559 /**
560 * overwrite action, since we are only showing elements in frozen mode
561 * no help display needed
562 *
563 * @return int
564 * @access public
565 */
566 function getAction() {
567 if ($this->_action & CRM_Core_Action::PREVIEW) {
568 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
569 }
570 else {
571 return CRM_Core_Action::VIEW;
572 }
573 }
574
575 /**
576 * This function sets the default values for the form. Note that in edit/view mode
577 * the default values are retrieved from the database
578 *
579 * @access public
580 *
581 * @return void
582 */
583 function setDefaultValues() {}
584
585 /**
586 * Process the form
587 *
588 * @return void
589 * @access public
590 */
591 public function postProcess() {
592 $contactID = $this->getContactID();
593
594 // add a description field at the very beginning
595 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
596
597 // also add accounting code
598 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode',
599 $this->_values
600 );
601
602 // fix currency ID
603 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
604
605 $premiumParams = $membershipParams = $tempParams = $params = $this->_params;
606
607 //carry payment processor id.
608 if ($paymentProcessorId = CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
609 $this->_params['payment_processor_id'] = $paymentProcessorId;
610 foreach (array(
611 'premiumParams', 'membershipParams', 'tempParams', 'params') as $p) {
612 ${$p}['payment_processor_id'] = $paymentProcessorId;
613 }
614 }
615
616 $fields = array();
617
618 if (!empty($params['image_URL'])) {
619 CRM_Contact_BAO_Contact::processImageParams($params);
620 }
621
622 // set email for primary location.
623 $fields['email-Primary'] = 1;
624
625 // get the add to groups
626 $addToGroups = array();
627
628 // now set the values for the billing location.
629 foreach ($this->_fields as $name => $value) {
630 $fields[$name] = 1;
631
632 // get the add to groups for uf fields
633 if (!empty($value['add_to_group_id'])) {
634 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
635 }
636 }
637
638 if (!array_key_exists('first_name', $fields)) {
639 $nameFields = array('first_name', 'middle_name', 'last_name');
640 foreach ($nameFields as $name) {
641 $fields[$name] = 1;
642 if (array_key_exists("billing_$name", $params)) {
643 $params[$name] = $params["billing_{$name}"];
644 $params['preserveDBName'] = TRUE;
645 }
646 }
647 }
648
649 // billing email address
650 $fields["email-{$this->_bltID}"] = 1;
651
652 //unset the billing parameters if it is pay later mode
653 //to avoid creation of billing location
654 if ($params['is_pay_later']) {
655 $billingFields = array(
656 'billing_first_name',
657 'billing_middle_name',
658 'billing_last_name',
659 "billing_street_address-{$this->_bltID}",
660 "billing_city-{$this->_bltID}",
661 "billing_state_province-{$this->_bltID}",
662 "billing_state_province_id-{$this->_bltID}",
663 "billing_postal_code-{$this->_bltID}",
664 "billing_country-{$this->_bltID}",
665 "billing_country_id-{$this->_bltID}",
666 );
667
668 foreach ($billingFields as $value) {
669 unset($params[$value]);
670 unset($fields[$value]);
671 }
672 }
673
674 // if onbehalf-of-organization contribution, take out
675 // organization params in a separate variable, to make sure
676 // normal behavior is continued. And use that variable to
677 // process on-behalf-of functionality.
678 if (!empty($this->_params['hidden_onbehalf_profile'])) {
679 $behalfOrganization = array();
680 $orgFields = array('organization_name', 'organization_id', 'org_option');
681 foreach ($orgFields as $fld) {
682 if (array_key_exists($fld, $params)) {
683 $behalfOrganization[$fld] = $params[$fld];
684 unset($params[$fld]);
685 }
686 }
687
688 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
689 foreach ($params['onbehalf'] as $fld => $values) {
690 if (strstr($fld, 'custom_')) {
691 $behalfOrganization[$fld] = $values;
692 }
693 elseif (!(strstr($fld, '-'))) {
694 if (in_array($fld, array(
695 'contribution_campaign_id', 'member_campaign_id'))) {
696 $fld = 'campaign_id';
697 }
698 else {
699 $behalfOrganization[$fld] = $values;
700 }
701 $this->_params[$fld] = $values;
702 }
703 }
704 }
705
706 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
707 foreach ($params['onbehalf_location'] as $block => $vals) {
708 //fix for custom data (of type checkbox, multi-select)
709 if ( substr($block, 0, 7) == 'custom_' ) {
710 continue;
711 }
712 // fix the index of block elements
713 if (is_array($vals) ) {
714 foreach ( $vals as $key => $val ) {
715 //dont adjust the index of address block as
716 //it's index is WRT to location type
717 $newKey = ($block == 'address') ? $key : ++$key;
718 $behalfOrganization[$block][$newKey] = $val;
719 }
720 }
721 }
722 unset($params['onbehalf_location']);
723 }
724 if (!empty($params['onbehalf[image_URL]'])) {
725 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
726 }
727 }
728
729 // check for profile double opt-in and get groups to be subscribed
730 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
731
732 // since we are directly adding contact to group lets unset it from mailing
733 if (!empty($addToGroups)) {
734 foreach ($addToGroups as $groupId) {
735 if (isset($subscribeGroupIds[$groupId])) {
736 unset($subscribeGroupIds[$groupId]);
737 }
738 }
739 }
740
741 foreach ($addToGroups as $k) {
742 if (array_key_exists($k, $subscribeGroupIds)) {
743 unset($addToGroups[$k]);
744 }
745 }
746
747 if (empty($contactID)) {
748 $dupeParams = $params;
749 if (!empty($dupeParams['onbehalf'])) {
750 unset($dupeParams['onbehalf']);
751 }
752
753 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
754 $dedupeParams['check_permission'] = FALSE;
755 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
756
757 // if we find more than one contact, use the first one
758 $contact_id = CRM_Utils_Array::value(0, $ids);
759
760 // Fetch default greeting id's if creating a contact
761 if (!$contact_id) {
762 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
763 if (!isset($params[$greeting])) {
764 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
765 }
766 }
767 }
768 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
769 $params,
770 $fields,
771 $contact_id,
772 $addToGroups,
773 NULL,
774 NULL,
775 TRUE
776 );
777 }
778 else {
779 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
780 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
781 $params,
782 $fields,
783 $contactID,
784 $addToGroups,
785 NULL,
786 $ctype,
787 TRUE
788 );
789 }
790
791 // Make the contact ID associated with the contribution available at the Class level.
792 // Also make available to the session.
793 //@todo consider handling this in $this->getContactID();
794 $this->set('contactID', $contactID);
795 $this->_contactID = $contactID;
796
797 //get email primary first if exist
798 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
799 if (!$subscriptionEmail['email']) {
800 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
801 }
802 // subscribing contact to groups
803 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
804 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
805 }
806
807 // If onbehalf-of-organization contribution / signup, add organization
808 // and it's location.
809 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
810 $ufFields = array();
811 foreach ($this->_fields['onbehalf'] as $name => $value) {
812 $ufFields[$name] = 1;
813 }
814 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
815 $this->_params, $ufFields
816 );
817 } else if (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
818 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
819 // store current user id as related contact for later use for mailing / activity..
820 $this->_values['related_contact'] = $contactID;
821 $this->_params['related_contact'] = $contactID;
822 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
823 $contactID = $this->_membershipContactID;
824 }
825
826 // lets store the contactID in the session
827 // for things like tell a friend
828 $session = CRM_Core_Session::singleton();
829 if (!$session->get('userID')) {
830 $session->set('transaction.userID', $contactID);
831 }
832 else {
833 $session->set('transaction.userID', NULL);
834 }
835
836 $this->_useForMember = $this->get('useForMember');
837
838 // store the fact that this is a membership and membership type is selected
839 $processMembership = FALSE;
840 if ((!empty($membershipParams['selectMembership']) &&
841 $membershipParams['selectMembership'] != 'no_thanks'
842 ) ||
843 $this->_useForMember
844 ) {
845 $processMembership = TRUE;
846
847 if (!$this->_useForMember) {
848 $this->assign('membership_assign', TRUE);
849 $this->set('membershipTypeID', $this->_params['selectMembership']);
850 }
851
852 if ($this->_action & CRM_Core_Action::PREVIEW) {
853 $membershipParams['is_test'] = 1;
854 }
855 if ($this->_params['is_pay_later']) {
856 $membershipParams['is_pay_later'] = 1;
857 }
858 }
859
860 if ($processMembership) {
861 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
862
863 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
864 if (isset($this->_params['related_contact'])) {
865 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
866 }
867 else {
868 $membershipParams['cms_contactID'] = $contactID;
869 }
870
871 //inherit campaign from contirb page.
872 if (!array_key_exists('campaign_id', $membershipParams)) {
873 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
874 }
875
876 if (!empty($membershipParams['onbehalf']) &&
877 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
878 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
879 }
880
881 $customFieldsFormatted = $fieldTypes = array();
882 if (!empty($membershipParams['onbehalf']) &&
883 is_array($membershipParams['onbehalf'])) {
884 foreach ($membershipParams['onbehalf'] as $key => $value) {
885 if (strstr($key, 'custom_')) {
886 $customFieldId = explode('_', $key);
887 CRM_Core_BAO_CustomField::formatCustomField(
888 $customFieldId[1],
889 $customFieldsFormatted,
890 $value,
891 'Membership',
892 NULL,
893 $contactID
894 );
895 }
896 }
897 $fieldTypes = array('Contact', 'Organization', 'Membership');
898 }
899
900 $priceFieldIds = $this->get('memberPriceFieldIDS');
901
902 if (!empty($priceFieldIds)) {
903 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
904 unset($priceFieldIds['id']);
905 $membershipTypeIds = array();
906 $membershipTypeTerms = array();
907 foreach ($priceFieldIds as $priceFieldId) {
908 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
909 $membershipTypeIds[] = $id;
910 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
911 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
912 $term = 1;
913 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
914 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
915 }
916 else {
917 $membershipTypeTerms[$id] = 1;
918 }
919 }
920 }
921 $membershipParams['selectMembership'] = $membershipTypeIds;
922 $membershipParams['financial_type_id'] = $contributionTypeID;
923 $membershipParams['types_terms'] = $membershipTypeTerms;
924 }
925 if (!empty($membershipParams['selectMembership'])) {
926 // CRM-12233
927 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
928 foreach ($this->_values['fee'] as $key => $feeValues) {
929 if ($feeValues['name'] == 'membership_amount') {
930 $fieldId = $this->_params['price_' . $key];
931 $this->_memLineItem[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
932 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
933 break;
934 }
935 }
936 }
937
938 try {
939 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
940 $this, $premiumParams, $customFieldsFormatted,
941 $fieldTypes
942 );
943 } catch (CRM_Core_Exception $e) {
944 CRM_Core_Session::singleton()->setStatus($e->getMessage());
945 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
946 }
947 }
948 }
949 else {
950 // at this point we've created a contact and stored its address etc
951 // all the payment processors expect the name and address to be in the
952 // so we copy stuff over to first_name etc.
953 $paymentParams = $this->_params;
954 $contributionTypeId = $this->_values['financial_type_id'];
955
956 $fieldTypes = array();
957 if (!empty($paymentParams['onbehalf']) &&
958 is_array($paymentParams['onbehalf'])
959 ) {
960 foreach ($paymentParams['onbehalf'] as $key => $value) {
961 if (strstr($key, 'custom_')) {
962 $this->_params[$key] = $value;
963 }
964 }
965 $fieldTypes = array('Contact', 'Organization', 'Contribution');
966 }
967
968 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
969 $premiumParams, $contactID,
970 $contributionTypeId,
971 'contribution',
972 $fieldTypes
973 );
974 }
975 }
976
977 /**
978 * Process the form
979 *
980 * @param $premiumParams
981 * @param $contribution
982 *
983 * @return void
984 * @access public
985 */
986 public function postProcessPremium($premiumParams, $contribution) {
987 // assigning Premium information to receipt tpl
988 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
989 if ($selectProduct &&
990 $selectProduct != 'no_thanks'
991 ) {
992 $startDate = $endDate = "";
993 $this->assign('selectPremium', TRUE);
994 $productDAO = new CRM_Contribute_DAO_Product();
995 $productDAO->id = $selectProduct;
996 $productDAO->find(TRUE);
997 $this->assign('product_name', $productDAO->name);
998 $this->assign('price', $productDAO->price);
999 $this->assign('sku', $productDAO->sku);
1000 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1001
1002 $periodType = $productDAO->period_type;
1003
1004 if ($periodType) {
1005 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1006 $duration_unit = $productDAO->duration_unit;
1007 $duration_interval = $productDAO->duration_interval;
1008 if ($periodType == 'rolling') {
1009 $startDate = date('Y-m-d');
1010 }
1011 elseif ($periodType == 'fixed') {
1012 if ($fixed_period_start_day) {
1013 $date = explode('-', date('Y-m-d'));
1014 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1015 $day = substr($fixed_period_start_day, -2) . "<br>";
1016 $year = $date[0];
1017 $startDate = $year . '-' . $month . '-' . $day;
1018 }
1019 else {
1020 $startDate = date('Y-m-d');
1021 }
1022 }
1023
1024 $date = explode('-', $startDate);
1025 $year = $date[0];
1026 $month = $date[1];
1027 $day = $date[2];
1028
1029 switch ($duration_unit) {
1030 case 'year':
1031 $year = $year + $duration_interval;
1032 break;
1033
1034 case 'month':
1035 $month = $month + $duration_interval;
1036 break;
1037
1038 case 'day':
1039 $day = $day + $duration_interval;
1040 break;
1041
1042 case 'week':
1043 $day = $day + ($duration_interval * 7);
1044 }
1045 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1046 $this->assign('start_date', $startDate);
1047 $this->assign('end_date', $endDate);
1048 }
1049
1050 $dao = new CRM_Contribute_DAO_Premium();
1051 $dao->entity_table = 'civicrm_contribution_page';
1052 $dao->entity_id = $this->_id;
1053 $dao->find(TRUE);
1054 $this->assign('contact_phone', $dao->premiums_contact_phone);
1055 $this->assign('contact_email', $dao->premiums_contact_email);
1056
1057 //create Premium record
1058 $params = array(
1059 'product_id' => $premiumParams['selectProduct'],
1060 'contribution_id' => $contribution->id,
1061 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1062 'quantity' => 1,
1063 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1064 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1065 );
1066 if (!empty($premiumParams['selectProduct'])){
1067 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1068 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1069 $daoPremiumsProduct->premiums_id = $dao->id;
1070 $daoPremiumsProduct->find(true);
1071 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1072 }
1073 //Fixed For CRM-3901
1074 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1075 $daoContrProd->contribution_id = $contribution->id;
1076 if ($daoContrProd->find(TRUE)) {
1077 $params['id'] = $daoContrProd->id;
1078 }
1079
1080 CRM_Contribute_BAO_Contribution::addPremium($params);
1081 if ($productDAO->cost && !empty($params['financial_type_id'])) {
1082 $trxnParams = array(
1083 'cost' => $productDAO->cost,
1084 'currency' => $productDAO->currency,
1085 'financial_type_id' => $params['financial_type_id'],
1086 'contributionId' => $contribution->id
1087 );
1088 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1089 }
1090 }
1091 elseif ($selectProduct == 'no_thanks') {
1092 //Fixed For CRM-3901
1093 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1094 $daoContrProd->contribution_id = $contribution->id;
1095 if ($daoContrProd->find(TRUE)) {
1096 $daoContrProd->delete();
1097 }
1098 }
1099 }
1100
1101 /**
1102 * Process the contribution
1103 *
1104 * @param $form
1105 * @param $params
1106 * @param $result
1107 * @param $contactID
1108 * @param $contributionType
1109 * @param bool $deductibleMode
1110 * @param bool $pending
1111 * @param bool $online
1112 *
1113 * @return CRM_Contribute_DAO_Contribution
1114 * @access public
1115 */
1116 static function processContribution(
1117 &$form,
1118 $params,
1119 $result,
1120 $contactID,
1121 $contributionType,
1122 $deductibleMode = TRUE,
1123 $pending = FALSE,
1124 $online = TRUE
1125 ) {
1126 $transaction = new CRM_Core_Transaction();
1127 $className = get_class($form);
1128 $recurringContributionID = NULL;
1129
1130 // add these values for the recurringContrib function ,CRM-10188
1131 $params['financial_type_id'] = $contributionType->id;
1132 //@todo - this is being set from the form to resolve CRM-10188 - an
1133 // eNotice caused by it not being set @ the front end
1134 // however, we then get it being over-written with null for backend contributions
1135 // a better fix would be to set the values in the respective forms rather than require
1136 // a function being shared by two forms to deal with their respective values
1137 // moving it to the BAO & not taking the $form as a param would make sense here.
1138 if(!isset($params['is_email_receipt'])){
1139 $params['is_email_receipt'] = CRM_Utils_Array::value( 'is_email_receipt', $form->_values );
1140 }
1141 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
1142
1143 // CRM-11885
1144 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1145 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1146 $nonDeductibleAmount = $params['non_deductible_amount'];
1147 }
1148 // if non_deductible_amount does NOT exist - then calculate it depending on:
1149 // $contributionType->is_deductible and whether there is a product (premium).
1150 else {
1151 //if ($contributionType->is_deductible && $deductibleMode) {
1152 if ($contributionType->is_deductible) {
1153 if ($online && isset($params['selectProduct'])) {
1154 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1155 }
1156 if (!$online && isset($params['product_name'][0])) {
1157 $selectProduct = $params['product_name'][0];
1158 }
1159 // if there is a product - compare the value to the contribution amount
1160 if (isset($selectProduct) &&
1161 $selectProduct != 'no_thanks'
1162 ) {
1163 $productDAO = new CRM_Contribute_DAO_Product();
1164 $productDAO->id = $selectProduct;
1165 $productDAO->find(TRUE);
1166 // product value exceeds contribution amount
1167 if ($params['amount'] < $productDAO->price) {
1168 $nonDeductibleAmount = $params['amount'];
1169 }
1170 // product value does NOT exceed contribution amount
1171 else {
1172 $nonDeductibleAmount = $productDAO->price;
1173 }
1174 }
1175 // contribution is deductible - but there is no product
1176 else {
1177 $nonDeductibleAmount = '0.00';
1178 }
1179 }
1180 // contribution is NOT deductible
1181 else {
1182 $nonDeductibleAmount = $params['amount'];
1183 }
1184 }
1185
1186 $now = date('YmdHis');
1187 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
1188 if (!empty($form->_values['is_email_receipt'])) {
1189 $receiptDate = $now;
1190 }
1191
1192 //get the contrib page id.
1193 $contributionPageId = NULL;
1194 if ($online) {
1195 $contributionPageId = $form->_id;
1196 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1197 if (!array_key_exists('campaign_id', $params)) {
1198 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1199 }
1200 }
1201 else {
1202 //also for offline we do support - CRM-7290
1203 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1204 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1205 }
1206
1207 // first create the contribution record
1208 $contribParams = array(
1209 'contact_id' => $contactID,
1210 'financial_type_id' => $contributionType->id,
1211 'contribution_page_id' => $contributionPageId,
1212 'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
1213 'non_deductible_amount' => $nonDeductibleAmount,
1214 'total_amount' => $params['amount'],
1215 'tax_amount' => $params['tax_amount'],
1216 'amount_level' => CRM_Utils_Array::value('amount_level', $params),
1217 'invoice_id' => $params['invoiceID'],
1218 'currency' => $params['currencyID'],
1219 'source' =>
1220 (!$online || !empty($params['source'])) ?
1221 CRM_Utils_Array::value('source', $params) :
1222 CRM_Utils_Array::value('description', $params),
1223 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
1224 //configure cancel reason, cancel date and thankyou date
1225 //from 'contribution' type profile if included
1226 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
1227 'cancel_date' =>
1228 isset($params['cancel_date']) ?
1229 CRM_Utils_Date::format($params['cancel_date']) :
1230 NULL,
1231 'thankyou_date' =>
1232 isset($params['thankyou_date']) ?
1233 CRM_Utils_Date::format($params['thankyou_date']) :
1234 NULL,
1235 'campaign_id' => $campaignId,
1236 );
1237
1238 if (!$online && isset($params['thankyou_date'])) {
1239 $contribParams['thankyou_date'] = $params['thankyou_date'];
1240 }
1241
1242 if (!$online || $form->_values['is_monetary']) {
1243 if (empty($params['is_pay_later'])) {
1244 $contribParams['payment_instrument_id'] = 1;
1245 }
1246 }
1247
1248 if (!$pending && $result) {
1249 $contribParams += array(
1250 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1251 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
1252 'trxn_id' => $result['trxn_id'],
1253 'receipt_date' => $receiptDate,
1254 // also add financial_trxn details as part of fix for CRM-4724
1255 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result),
1256 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result),
1257 );
1258 }
1259
1260 if ($recurringContributionID) {
1261 $contribParams['contribution_recur_id'] = $recurringContributionID;
1262 }
1263
1264 $contribParams['contribution_status_id'] = $pending ? 2 : 1;
1265
1266 $contribParams['is_test'] = 0;
1267 if ($form->_mode == 'test') {
1268 $contribParams['is_test'] = 1;
1269 }
1270
1271 $ids = array();
1272 if (isset($contribParams['invoice_id'])) {
1273 $contribID = CRM_Core_DAO::getFieldValue(
1274 'CRM_Contribute_DAO_Contribution',
1275 $contribParams['invoice_id'],
1276 'id',
1277 'invoice_id'
1278 );
1279 if (isset($contribID)) {
1280 $ids['contribution'] = $contribID;
1281 $contribParams['id'] = $contribID;
1282 }
1283 }
1284
1285
1286 //create an contribution address
1287 if (
1288 $form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
1289 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1290 }
1291
1292 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
1293 $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
1294 $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
1295
1296 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1297 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
1298 // if its due to pcp
1299 if (!empty($params['pcp_made_through_id'])) {
1300 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
1301 'CRM_PCP_DAO_PCP',
1302 $params['pcp_made_through_id'],
1303 'contact_id'
1304 );
1305 }
1306 else {
1307 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1308 }
1309
1310 // Pass these details onto with the contribution to make them
1311 // available at hook_post_process, CRM-8908
1312 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
1313 }
1314
1315 if (isset($params['amount'])) {
1316 $contribParams['line_item'] = $form->_lineItem;
1317 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
1318 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1319 if ($invoicing) {
1320 $totalTaxAmount = 0;
1321 $dataArray = array();
1322 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1323 foreach ($lineItemValue as $key => $value) {
1324 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1325 if (isset($dataArray[$value['tax_rate']])) {
1326 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1327 }
1328 else {
1329 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1330 }
1331 }
1332 }
1333 }
1334 $smarty = CRM_Core_Smarty::singleton();
1335 $smarty->assign('dataArray', $dataArray);
1336 $smarty->assign('totalTaxAmount', $params['tax_amount']);
1337 }
1338 //add contribution record
1339 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
1340 if (is_a($contribution, 'CRM_Core_Error')) {
1341 $message = CRM_Core_Error::getMessages($contribution);
1342 CRM_Core_Error::fatal($message);
1343 }
1344
1345 // lets store it in the form variable so postProcess hook can get to this and use it
1346 $form->_contributionID = $contribution->id;
1347 }
1348
1349 //CRM-13981, processing honor contact into soft-credit contribution
1350 CRM_Contact_Form_ProfileContact::postProcess($form);
1351
1352 // process soft credit / pcp pages
1353 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1354
1355 //handle pledge stuff.
1356 if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) &&
1357 (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))
1358 ) {
1359
1360 if (!empty($form->_values['pledge_id'])) {
1361
1362 //when user doing pledge payments.
1363 //update the schedule when payment(s) are made
1364 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1365 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1366 'CRM_Pledge_DAO_PledgePayment',
1367 $paymentId,
1368 'scheduled_amount',
1369 'id'
1370 );
1371
1372 $pledgePaymentParams = array(
1373 'id' => $paymentId,
1374 'contribution_id' => $contribution->id,
1375 'status_id' => $contribution->contribution_status_id,
1376 'actual_amount' => $scheduledAmount,
1377 );
1378
1379
1380 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1381 }
1382
1383 //update pledge status according to the new payment statuses
1384 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1385 }
1386 else {
1387 //when user creating pledge record.
1388 $pledgeParams = array();
1389 $pledgeParams['contact_id'] = $contribution->contact_id;
1390 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1391 $pledgeParams['contribution_id'] = $contribution->id;
1392 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1393 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1394 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1395 $pledgeParams['installments'] = $params['pledge_installments'];
1396 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1397 if ($pledgeParams['frequency_unit'] == 'month') {
1398 $pledgeParams['frequency_day'] = intval(date("d"));
1399 }
1400 else {
1401 $pledgeParams['frequency_day'] = 1;
1402 }
1403 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1404 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1405 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1406 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1407 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1408 $pledgeParams['is_test'] = $contribution->is_test;
1409 $pledgeParams['acknowledge_date'] = date('Ymd');
1410 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1411
1412 //inherit campaign from contirb page.
1413 $pledgeParams['campaign_id'] = $campaignId;
1414
1415 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1416
1417 $form->_params['pledge_id'] = $pledge->id;
1418
1419 //send acknowledgment email. only when pledge is created
1420 if ($pledge->id) {
1421 //build params to send acknowledgment.
1422 $pledgeParams['id'] = $pledge->id;
1423 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1424 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1425
1426 //scheduled amount will be same as installment_amount.
1427 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1428
1429 //get total pledge amount.
1430 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1431
1432 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1433 }
1434 }
1435 }
1436
1437 if ($online && $contribution) {
1438 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1439 CRM_Core_DAO::$_nullArray,
1440 'civicrm_contribution',
1441 $contribution->id,
1442 'Contribution'
1443 );
1444 }
1445 elseif ($contribution) {
1446 //handle custom data.
1447 $params['contribution_id'] = $contribution->id;
1448 if (!empty($params['custom']) &&
1449 is_array($params['custom']) &&
1450 !is_a($contribution, 'CRM_Core_Error')
1451 ) {
1452 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1453 }
1454 }
1455 // Save note
1456 if ($contribution && !empty($params['contribution_note'])) {
1457 $noteParams = array(
1458 'entity_table' => 'civicrm_contribution',
1459 'note' => $params['contribution_note'],
1460 'entity_id' => $contribution->id,
1461 'contact_id' => $contribution->contact_id,
1462 'modified_date' => date('Ymd'),
1463 );
1464
1465 CRM_Core_BAO_Note::add($noteParams, array());
1466 }
1467
1468
1469 if (isset($params['related_contact'])) {
1470 $contactID = $params['related_contact'];
1471 }
1472 elseif (isset($params['cms_contactID'])) {
1473 $contactID = $params['cms_contactID'];
1474 }
1475
1476 //create contribution activity w/ individual and target
1477 //activity w/ organisation contact id when onbelf, CRM-4027
1478 $targetContactID = NULL;
1479 if (!empty($params['hidden_onbehalf_profile'])) {
1480 $targetContactID = $contribution->contact_id;
1481 $contribution->contact_id = $contactID;
1482 }
1483
1484 // create an activity record
1485 if ($contribution) {
1486 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1487 }
1488
1489 $transaction->commit();
1490 // CRM-13074 - create the CMSUser after the transaction is completed as it
1491 // is not appropriate to delete a valid contribution if a user create problem occurs
1492 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1493 $contactID,
1494 'email-' . $form->_bltID
1495 );
1496 return $contribution;
1497 }
1498
1499 /**
1500 * Create the recurring contribution record
1501 *
1502 */
1503 static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1504 // return if this page is not set for recurring
1505 // or the user has not chosen the recurring option
1506
1507 //this is online case validation.
1508 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
1509 return NULL;
1510 }
1511
1512 $recurParams = array('contact_id' => $contactID);
1513 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1514 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1515 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1516 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1517 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1518 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1519
1520 // CRM-14354: For an auto-renewing membership with an additional contribution,
1521 // if separate payments is not enabled, make sure only the membership fee recurs
1522 if ($form->_membershipBlock['is_separate_payment'] === '0'
1523 && isset($params['selectMembership'])
1524 && $form->_values['is_allow_other_amount'] == '1'
1525 ) {
1526 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1527 }
1528
1529 $recurParams['is_test'] = 0;
1530 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1531 (isset($form->_mode) && ($form->_mode == 'test'))
1532 ) {
1533 $recurParams['is_test'] = 1;
1534 }
1535
1536 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1537 if (!empty($params['receive_date'])) {
1538 $recurParams['start_date'] = $params['receive_date'];
1539 }
1540 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1541 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1542 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1543 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1544 // we need to add a unique trxn_id to avoid a unique key error
1545 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1546 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1547 $recurParams['financial_type_id'] = $contributionType->id;
1548
1549 if (!$online || $form->_values['is_monetary']) {
1550 $recurParams['payment_instrument_id'] = 1;
1551 }
1552
1553 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1554 if ($online) {
1555 if (!array_key_exists('campaign_id', $params)) {
1556 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1557 }
1558 }
1559 $recurParams['campaign_id'] = $campaignId;
1560
1561 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1562 if (is_a($recurring, 'CRM_Core_Error')) {
1563 CRM_Core_Error::displaySessionError($recurring);
1564 $urlString = 'civicrm/contribute/transact';
1565 $urlParams = '_qf_Main_display=true';
1566 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1567 $urlString = 'civicrm/contact/view/contribution';
1568 $urlParams = "action=add&cid={$form->_contactID}";
1569 if ($form->_mode) {
1570 $urlParams .= "&mode={$form->_mode}";
1571 }
1572 }
1573 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1574 }
1575
1576 return $recurring->id;
1577 }
1578
1579 /**
1580 * Function to add on behalf of organization and it's location
1581 *
1582 * @param $behalfOrganization array array of organization info
1583 * @param $contactID int individual contact id. One
1584 * who is doing the process of signup / contribution.
1585 *
1586 * @param $values array form values array
1587 * @param $params
1588 * @param null $fields
1589 *
1590 * @return void
1591 * @access public
1592 */
1593 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1594 $isCurrentEmployer = FALSE;
1595 $dupeIDs = array();
1596 $orgID = NULL;
1597 if (!empty($behalfOrganization['organization_id']) && !empty($behalfOrganization['org_option'])) {
1598 $orgID = $behalfOrganization['organization_id'];
1599 unset($behalfOrganization['organization_id']);
1600 $isCurrentEmployer = TRUE;
1601 }
1602
1603 // formalities for creating / editing organization.
1604 $behalfOrganization['contact_type'] = 'Organization';
1605
1606 // get the relationship type id
1607 $relType = new CRM_Contact_DAO_RelationshipType();
1608 $relType->name_a_b = 'Employee of';
1609 $relType->find(TRUE);
1610 $relTypeId = $relType->id;
1611
1612 // keep relationship params ready
1613 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1614 $relParams['is_permission_a_b'] = 1;
1615 $relParams['is_active'] = 1;
1616
1617 if (!$orgID) {
1618 // check if matching organization contact exists
1619 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1620 $dedupeParams['check_permission'] = FALSE;
1621 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1622
1623 // CRM-6243 says to pick the first org even if more than one match
1624 if (count($dupeIDs) >= 1) {
1625 $behalfOrganization['contact_id'] = $dupeIDs[0];
1626 // don't allow name edit
1627 unset($behalfOrganization['organization_name']);
1628 }
1629 }
1630 else {
1631 // if found permissioned related organization, allow location edit
1632 $behalfOrganization['contact_id'] = $orgID;
1633 // don't allow name edit
1634 unset($behalfOrganization['organization_name']);
1635 }
1636
1637 // handling for image url
1638 if (!empty($behalfOrganization['image_URL'])) {
1639 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1640 }
1641
1642 // create organization, add location
1643 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1644 NULL, NULL, 'Organization'
1645 );
1646 // create relationship
1647 $relParams['contact_check'][$orgID] = 1;
1648 $cid = array('contact' => $contactID);
1649 CRM_Contact_BAO_Relationship::create($relParams, $cid);
1650
1651 // if multiple match - send a duplicate alert
1652 if ($dupeIDs && (count($dupeIDs) > 1)) {
1653 $values['onbehalf_dupe_alert'] = 1;
1654 // required for IPN
1655 $params['onbehalf_dupe_alert'] = 1;
1656 }
1657
1658 // make sure organization-contact-id is considered for recording
1659 // contribution/membership etc..
1660 if ($contactID != $orgID) {
1661 // take a note of contact-id, so we can send the
1662 // receipt to individual contact as well.
1663
1664 // required for mailing/template display ..etc
1665 $values['related_contact'] = $contactID;
1666 // required for IPN
1667 $params['related_contact'] = $contactID;
1668
1669 //make this employee of relationship as current
1670 //employer / employee relationship, CRM-3532
1671 if ($isCurrentEmployer &&
1672 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1673 ) {
1674 $isCurrentEmployer = FALSE;
1675 }
1676
1677 if (!$isCurrentEmployer && $orgID) {
1678 //build current employer params
1679 $currentEmpParams[$contactID] = $orgID;
1680 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1681 }
1682
1683 // contribution / signup will be done using this
1684 // organization id.
1685 $contactID = $orgID;
1686 }
1687 }
1688
1689 /**
1690 * Function used to save pcp / soft credit entry
1691 * This is used by contribution and also event pcps
1692 *
1693 * @param array $params associated array
1694 * @param object $contribution contribution object
1695 *
1696 * @static
1697 * @access public
1698 */
1699 static function processPcpSoft(&$params, &$contribution) {
1700 //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1701 if (!empty($params['soft_credit_to'])) {
1702 $contributionSoftParams = array();
1703 foreach (array(
1704 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) {
1705 if (!empty($params[$val])) {
1706 $contributionSoftParams[$val] = $params[$val];
1707 }
1708 }
1709
1710 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1711 // add contribution id
1712 $contributionSoftParams['contribution_id'] = $contribution->id;
1713 // add pcp id
1714 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1715
1716 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
1717
1718 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
1719 }
1720 }
1721
1722 /**
1723 * Function used to se pcp related defaults / params
1724 * This is used by contribution and also event pcps
1725 *
1726 * @param object $page form object
1727 * @param array $params associated array
1728 *
1729 * @return array
1730 * @static
1731 * @access public
1732 */
1733 static function processPcp(&$page, $params) {
1734 $params['pcp_made_through_id'] = $page->_pcpId;
1735 $page->assign('pcpBlock', TRUE);
1736 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1737 $params['pcp_roll_nickname'] = ts('Anonymous');
1738 $params['pcp_is_anonymous'] = 1;
1739 }
1740 else {
1741 $params['pcp_is_anonymous'] = 0;
1742 }
1743 foreach (array(
1744 'pcp_display_in_roll',
1745 'pcp_is_anonymous',
1746 'pcp_roll_nickname',
1747 'pcp_personal_note'
1748 ) as $val) {
1749 if (!empty($params[$val])) {
1750 $page->assign($val, $params[$val]);
1751 }
1752 }
1753
1754 return $params;
1755 }
1756 }