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