CRM-17457 fix - Enotices when skip participant is used
[civicrm-core.git] / CRM / Event / Form / Registration / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be 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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 *
31 * @package CRM
e7112fa7 32 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
33 * $Id$
34 *
35 */
36
37/**
38 * This class generates form components for processing Event
39 *
40 */
41class CRM_Event_Form_Registration_Confirm extends CRM_Event_Form_Registration {
42
43 /**
66f9e52b 44 * The values for the contribution db object.
6a488035
TO
45 *
46 * @var array
6a488035
TO
47 */
48 public $_values;
49
50 /**
66f9e52b 51 * The total amount.
6a488035
TO
52 *
53 * @var float
6a488035
TO
54 */
55 public $_totalAmount;
56
57 /**
66f9e52b 58 * Set variables up before form is built.
6a488035
TO
59 *
60 * @return void
6a488035 61 */
00be9182 62 public function preProcess() {
6a488035
TO
63 parent::preProcess();
64
65 // lineItem isn't set until Register postProcess
66 $this->_lineItem = $this->get('lineItem');
67
68 $this->_params = $this->get('params');
d91b8b33 69 $this->_params[0]['tax_amount'] = $this->get('tax_amount');
6a488035
TO
70
71 $this->_params[0]['is_pay_later'] = $this->get('is_pay_later');
72 $this->assign('is_pay_later', $this->_params[0]['is_pay_later']);
73 if ($this->_params[0]['is_pay_later']) {
74 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
75 }
76
77 CRM_Utils_Hook::eventDiscount($this, $this->_params);
78
8cc574cf 79 if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
6a488035
TO
80 $this->set('hookDiscount', $this->_params[0]['discount']);
81 $this->assign('hookDiscount', $this->_params[0]['discount']);
82 }
83
6a488035
TO
84 if ($this->_contributeMode == 'express') {
85 $params = array();
86 // rfp == redirect from paypal
87 $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
88 CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
89 );
90
91 //we lost rfp in case of additional participant. So set it explicitly.
92 if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
93 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
94 $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
0479b4c8 95 if (is_object($payment)) {
6a488035 96 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
0479b4c8
TO
97 }
98 else {
6a488035 99 CRM_Core_Error::fatal($paymentObjError);
0479b4c8 100 }
6a488035 101
4233eb14 102 $params['payer'] = CRM_Utils_Array::value('payer', $expressParams);
6a488035
TO
103 $params['payer_id'] = $expressParams['payer_id'];
104 $params['payer_status'] = $expressParams['payer_status'];
105
106 CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $params, FALSE);
107
108 // fix state and country id if present
109 if (isset($params["billing_state_province_id-{$this->_bltID}"])) {
110 $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
111 }
112 if (isset($params['billing_country_id'])) {
113 $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
114 }
115
116 // set a few other parameters for PayPal
117 $params['token'] = $this->get('token');
118 $params['amount'] = $this->_params[0]['amount'];
a7488080 119 if (!empty($this->_params[0]['discount'])) {
6a488035
TO
120 $params['discount'] = $this->_params[0]['discount'];
121 $params['discountAmount'] = $this->_params[0]['discountAmount'];
122 $params['discountMessage'] = $this->_params[0]['discountMessage'];
123 }
4233eb14 124 if (!empty($this->_params[0]['amount_priceset_level_radio'])) {
125 $params['amount_priceset_level_radio'] = $this->_params[0]['amount_priceset_level_radio'];
126 }
6a488035
TO
127 $params['amount_level'] = $this->_params[0]['amount_level'];
128 $params['currencyID'] = $this->_params[0]['currencyID'];
129 $params['payment_action'] = 'Sale';
130
131 // also merge all the other values from the profile fields
132 $values = $this->controller->exportValues('Register');
133 $skipFields = array(
134 'amount',
135 "street_address-{$this->_bltID}",
136 "city-{$this->_bltID}",
137 "state_province_id-{$this->_bltID}",
138 "postal_code-{$this->_bltID}",
139 "country_id-{$this->_bltID}",
140 );
141
142 foreach ($values as $name => $value) {
143 // skip amount field
144 if (!in_array($name, $skipFields)) {
145 $params[$name] = $value;
146 }
bb2240a2 147 if (substr($name, 0, 6) == 'price_') {
b5b712c1 148 $params[$name] = $this->_params[0][$name];
bb2240a2 149 }
6a488035
TO
150 }
151 $this->set('getExpressCheckoutDetails', $params);
152 }
153 else {
154 $params = $this->get('getExpressCheckoutDetails');
155 }
156 $this->_params[0] = $params;
157 $this->_params[0]['is_primary'] = 1;
158 }
159 else {
160 //process only primary participant params.
161 $registerParams = $this->_params[0];
162 if (isset($registerParams["billing_state_province_id-{$this->_bltID}"])
163 && $registerParams["billing_state_province_id-{$this->_bltID}"]
164 ) {
165 $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
166 }
167
168 if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
169 $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
170 }
171 if (isset($registerParams['credit_card_exp_date'])) {
353ffa53 172 $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
6a488035
TO
173 $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
174 }
175 if ($this->_values['event']['is_monetary']) {
176 $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
177 $registerParams['currencyID'] = $this->_params[0]['currencyID'];
178 $registerParams['payment_action'] = 'Sale';
179 }
180 //assign back primary participant params.
181 $this->_params[0] = $registerParams;
182 }
183
184 if ($this->_values['event']['is_monetary']) {
185 $this->_params[0]['invoiceID'] = $this->get('invoiceID');
186 }
187 $this->assign('defaultRole', FALSE);
188 if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
189 $this->assign('defaultRole', TRUE);
190 }
191
a7488080 192 if (empty($this->_params[0]['participant_role_id']) &&
6a488035
TO
193 $this->_values['event']['default_role_id']
194 ) {
195 $this->_params[0]['participant_role_id'] = $this->_values['event']['default_role_id'];
196 }
197
198 if (isset($this->_values['event']['confirm_title'])) {
199 CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
200 }
201
202 if ($this->_pcpId) {
203 $params = CRM_Contribute_Form_Contribution_Confirm::processPcp($this, $this->_params[0]);
204 $this->_params[0] = $params;
205 }
206
207 $this->set('params', $this->_params);
208 }
209
210 /**
100fef9d 211 * Overwrite action, since we are only showing elements in frozen mode
6a488035
TO
212 * no help display needed
213 *
214 * @return int
6a488035 215 */
00be9182 216 public function getAction() {
6a488035
TO
217 if ($this->_action & CRM_Core_Action::PREVIEW) {
218 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
219 }
220 else {
221 return CRM_Core_Action::VIEW;
222 }
223 }
224
225 /**
66f9e52b 226 * Build the form object.
6a488035 227 *
355ba699 228 * @return void
6a488035
TO
229 */
230 public function buildQuickForm() {
231 $this->assignToTemplate();
1909126f 232
233 if ($this->_values['event']['is_monetary'] &&
234 ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0)
235 ) {
6a488035
TO
236 $this->_amount = array();
237
79d001a2 238 $taxAmount = 0;
6a488035 239 foreach ($this->_params as $k => $v) {
7bde3600 240 if ($v == 'skip') {
241 continue;
242 }
75b065ce 243 $individualTaxAmount = 0;
79d001a2
PB
244 //display tax amount on confirmation page
245 $taxAmount += $v['tax_amount'];
6a488035
TO
246 if (is_array($v)) {
247 foreach (array(
353ffa53 248 'first_name',
317fceb4 249 'last_name',
353ffa53 250 ) as $name) {
6a488035
TO
251 if (isset($v['billing_' . $name]) &&
252 !isset($v[$name])
253 ) {
254 $v[$name] = $v['billing_' . $name];
255 }
256 }
257
8cc574cf 258 if (!empty($v['first_name']) && !empty($v['last_name'])) {
6a488035
TO
259 $append = $v['first_name'] . ' ' . $v['last_name'];
260 }
261 else {
262 //use an email if we have one
263 foreach ($v as $v_key => $v_val) {
264 if (substr($v_key, 0, 6) == 'email-') {
265 $append = $v[$v_key];
266 }
267 }
268 }
269
270 $this->_amount[$k]['amount'] = $v['amount'];
a7488080 271 if (!empty($v['discountAmount'])) {
6a488035
TO
272 $this->_amount[$k]['amount'] -= $v['discountAmount'];
273 }
274
275 $this->_amount[$k]['label'] = preg_replace('/\ 1/', '', $v['amount_level']) . ' - ' . $append;
276 $this->_part[$k]['info'] = CRM_Utils_Array::value('first_name', $v) . ' ' . CRM_Utils_Array::value('last_name', $v);
a7488080 277 if (empty($v['first_name'])) {
6a488035
TO
278 $this->_part[$k]['info'] = $append;
279 }
75b065ce 280
281 /*CRM-16320 */
282 $individual[$k]['totalAmtWithTax'] = $this->_amount[$k]['amount'];
283 $individual[$k]['totalTaxAmt'] = $individualTaxAmount + $v['tax_amount'];
6a488035 284 $this->_totalAmount = $this->_totalAmount + $this->_amount[$k]['amount'];
a7488080 285 if (!empty($v['is_primary'])) {
6a488035
TO
286 $this->set('primaryParticipantAmount', $this->_amount[$k]['amount']);
287 }
288 }
289 }
290
0479b4c8 291 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
03b412ae
PB
292 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
293 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
03b412ae
PB
294 if ($invoicing) {
295 $this->assign('totalTaxAmount', $taxAmount);
d9e4ebe7 296 $this->assign('taxTerm', $taxTerm);
75b065ce 297 $this->assign('individual', $individual);
298 $this->set('individual', $individual);
03b412ae 299 }
75b065ce 300
6a488035
TO
301 $this->assign('part', $this->_part);
302 $this->set('part', $this->_part);
303 $this->assign('amounts', $this->_amount);
304 $this->assign('totalAmount', $this->_totalAmount);
305 $this->set('totalAmount', $this->_totalAmount);
306 }
307
9da8dc8c 308 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
6a488035 309 $lineItemForTemplate = array();
03b412ae 310 $getTaxDetails = FALSE;
26fe6f4c 311 if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
312 foreach ($this->_lineItem as $key => $value) {
313 if (!empty($value)) {
314 $lineItemForTemplate[$key] = $value;
315 }
316 if ($invoicing) {
317 foreach ($value as $v) {
318 if (isset($v['tax_rate'])) {
319 $getTaxDetails = TRUE;
320 }
03b412ae
PB
321 }
322 }
323 }
6a488035
TO
324 }
325 if (!empty($lineItemForTemplate)) {
326 $this->assign('lineItem', $lineItemForTemplate);
327 }
d9e4ebe7 328 $this->assign('getTaxDetails', $getTaxDetails);
6a488035
TO
329 }
330
331 //display additional participants profile.
5bdcb00b 332 self::assignProfiles($this);
6a488035
TO
333
334 //consider total amount.
335 $this->assign('isAmountzero', ($this->_totalAmount <= 0) ? TRUE : FALSE);
336
8cc574cf 337 if ($this->_paymentProcessor['payment_processor_type'] == 'Google_Checkout' && empty($this->_params[0]['is_pay_later']) && !($this->_params[0]['amount'] == 0) &&
6a488035
TO
338 !$this->_allowWaitlist && !$this->_requireApproval
339 ) {
340 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
341 $this->add('image',
342 $this->_checkoutButtonName,
343 $this->_paymentProcessor['url_button'],
97e557d7 344 array('class' => 'crm-form-submit')
6a488035
TO
345 );
346
347 $this->addButtons(array(
348 array(
349 'type' => 'back',
f212d37d 350 'name' => ts('Go Back'),
6a488035
TO
351 ),
352 )
353 );
354 }
355 else {
f212d37d 356 $contribButton = ts('Continue');
6a488035 357 $this->addButtons(array(
f2ce2ad2
J
358 array(
359 'type' => 'back',
f212d37d 360 'name' => ts('Go Back'),
f2ce2ad2 361 ),
6a488035
TO
362 array(
363 'type' => 'next',
364 'name' => $contribButton,
365 'isDefault' => TRUE,
366 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
367 ),
6a488035
TO
368 )
369 );
370 }
371
372 $defaults = array();
373 $fields = array();
374 if (!empty($this->_fields)) {
375 foreach ($this->_fields as $name => $dontCare) {
376 $fields[$name] = 1;
377 }
378 }
379 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
380 foreach ($fields as $name => $dontCare) {
381 if (isset($this->_params[0][$name])) {
382 $defaults[$name] = $this->_params[0][$name];
383 if (substr($name, 0, 7) == 'custom_') {
384 $timeField = "{$name}_time";
385 if (isset($this->_params[0][$timeField])) {
386 $defaults[$timeField] = $this->_params[0][$timeField];
387 }
388 if (isset($this->_params[0]["{$name}_id"])) {
389 $defaults["{$name}_id"] = $this->_params[0]["{$name}_id"];
390 }
391 }
392 elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)
393 && !empty($this->_params[0][$name . '_custom'])
394 ) {
395 $defaults[$name . '_custom'] = $this->_params[0][$name . '_custom'];
396 }
397 }
398 }
399
6a488035
TO
400 $this->setDefaults($defaults);
401 $this->freeze();
402
403 //lets give meaningful status message, CRM-4320.
404 $this->assign('isOnWaitlist', $this->_allowWaitlist);
405 $this->assign('isRequireApproval', $this->_requireApproval);
406
407 // Assign Participant Count to Lineitem Table
9da8dc8c 408 $this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
79b152ac 409 $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
6a488035
TO
410 }
411
ca87146b
EM
412 /**
413 * @param $fields
414 * @param $files
415 * @param $self
416 *
417 * @return array|bool
418 */
00be9182 419 public static function formRule($fields, $files, $self) {
79b152ac 420 $errors = array();
421 $eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
422 if ($eventFull && empty($self->_allowConfirmation)) {
423 if (empty($self->_allowWaitlist)) {
0479b4c8 424 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$self->_eventId}", FALSE, NULL, FALSE, TRUE));
79b152ac 425 }
426 }
427 $self->_feeBlock = $self->_values['fee'];
428 CRM_Event_Form_Registration_Register::formatFieldsForOptionFull($self);
429
0dc0b759 430 if (!empty($self->_priceSetId) &&
431 !$self->_requireApproval && !$self->_allowWaitlist
432 ) {
79b152ac 433 $priceSetErrors = self::validatePriceSet($self, $self->_params);
0dc0b759 434 if (!empty($priceSetErrors)) {
2ae4d103 435 CRM_Core_Session::setStatus(ts('You have been returned to the start of the registration process and any sold out events have been removed from your selections. You will not be able to continue until you review your booking and select different events if you wish.'), ts('Unfortunately some of your options have now sold out for one or more participants.'), 'error');
0dc0b759 436 CRM_Core_Session::setStatus(ts('Please note that the options which are marked or selected are sold out for participant being viewed.'), ts('Sold out:'), 'error');
437 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=true&qfKey={$fields['qfKey']}"));
438 }
79b152ac 439 }
440
0dc0b759 441 return empty($priceSetErrors) ? TRUE : $priceSetErrors;
79b152ac 442 }
353ffa53 443
6a488035 444 /**
66f9e52b 445 * Process the form submission.
6a488035 446 *
6a488035 447 *
355ba699 448 * @return void
6a488035
TO
449 */
450 public function postProcess() {
353ffa53 451 $now = date('YmdHis');
af72b8c7 452
6a488035 453 $this->_params = $this->get('params');
a7488080 454 if (!empty($this->_params[0]['contact_id'])) {
e1ce628e 455 // unclear when this would be set & whether it could be checked in getContactID.
456 // perhaps it relates to when cid is in the url
457 //@todo someone who knows add comments on the various contactIDs in this form
6a488035
TO
458 $contactID = $this->_params[0]['contact_id'];
459 }
460 else {
5c280496 461 $contactID = $this->getContactID();
6a488035
TO
462 }
463
464 // if a discount has been applied, lets now deduct it from the amount
465 // and fix the fee level
8cc574cf 466 if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
6a488035 467 foreach ($this->_params as $k => $v) {
8cc574cf 468 if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && !empty($this->_params[$k]['discountAmount'])) {
6a488035
TO
469 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
470 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
471 }
472 }
473 $this->set('params', $this->_params);
474 }
475
476 // CRM-4320, lets build array of cancelled additional participant ids
477 // those are drop or skip by primary at the time of confirmation.
478 // get all in and then unset those we want to process.
479 $cancelledIds = $this->_additionalParticipantIds;
480
481 $params = $this->_params;
1909126f 482 if ($this->_values['event']['is_monetary']) {
483 $this->set('finalAmount', $this->_amount);
484 }
6a488035
TO
485 $participantCount = array();
486
487 //unset the skip participant from params.
488 //build the $participantCount array.
489 //maintain record for all participants.
490 foreach ($params as $participantNum => $record) {
491 if ($record == 'skip') {
492 unset($params[$participantNum]);
493 $participantCount[$participantNum] = 'skip';
494 }
495 elseif ($participantNum) {
496 $participantCount[$participantNum] = 'participant';
497 }
498
499 //lets get additional participant id to cancel.
500 if ($this->_allowConfirmation && is_array($cancelledIds)) {
501 $additonalId = CRM_Utils_Array::value('participant_id', $record);
502 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
503 unset($cancelledIds[$key]);
504 }
505 }
506 }
507
508 $payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
509 $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
510
511 $this->participantIDS = array();
512 $fields = array();
513 foreach ($params as $key => $value) {
a9f7d48b 514 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
6a488035
TO
515 //unset the billing parameters if it is pay later mode
516 //to avoid creation of billing location
8ae4d0d3 517 if ($this->_allowWaitlist
518 || $this->_requireApproval
519 || (!empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater)
520 || empty($value['is_primary'])
521 ) {
6a488035
TO
522 $billingFields = array(
523 "email-{$this->_bltID}",
524 'billing_first_name',
525 'billing_middle_name',
526 'billing_last_name',
527 "billing_street_address-{$this->_bltID}",
528 "billing_city-{$this->_bltID}",
529 "billing_state_province-{$this->_bltID}",
530 "billing_state_province_id-{$this->_bltID}",
531 "billing_postal_code-{$this->_bltID}",
532 "billing_country-{$this->_bltID}",
533 "billing_country_id-{$this->_bltID}",
534 "address_name-{$this->_bltID}",
535 );
536 foreach ($billingFields as $field) {
537 unset($value[$field]);
538 }
a7488080 539 if (!empty($value['is_pay_later'])) {
6a488035
TO
540 $this->_values['params']['is_pay_later'] = TRUE;
541 }
542 }
543
544 //Unset ContactID for additional participants and set RegisterBy Id.
a7488080 545 if (empty($value['is_primary'])) {
6a488035
TO
546 $contactID = CRM_Utils_Array::value('contact_id', $value);
547 $registerByID = $this->get('registerByID');
548 if ($registerByID) {
549 $value['registered_by_id'] = $registerByID;
550 }
551 }
552 else {
553 $value['amount'] = $this->_totalAmount;
554 }
555
a9f7d48b 556 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
6a488035
TO
557
558 // lets store the contactID in the session
559 // we dont store in userID in case the user is doing multiple
560 // transactions etc
561 // for things like tell a friend
8cc574cf 562 if (!$this->getContactID() && !empty($value['is_primary'])) {
af72b8c7 563 $session = CRM_Core_Session::singleton();
6a488035
TO
564 $session->set('transaction.userID', $contactID);
565 }
566
567 $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
568 $value['accountingCode'] = CRM_Utils_Array::value('accountingCode',
569 $this->_values['event']
570 );
571
752f450d 572 $pending = FALSE;
67c8322d
J
573 if ($this->_allowWaitlist || $this->_requireApproval) {
574 //get the participant statuses.
575 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
576 if ($this->_allowWaitlist) {
577 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
578 }
579 else {
580 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
581 }
582
583 //there might be case user seleted pay later and
584 //now becomes part of run time waiting list.
585 $value['is_pay_later'] = FALSE;
586 }
587
6a488035 588 // required only if paid event
67c8322d 589 if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
6a488035
TO
590 if (is_array($this->_paymentProcessor)) {
591 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
592 }
6a488035
TO
593 $result = NULL;
594
67c8322d 595 if (!empty($value['is_pay_later']) ||
6a488035
TO
596 $value['amount'] == 0 ||
597 $this->_contributeMode == 'checkout' ||
598 $this->_contributeMode == 'notify'
599 ) {
600 if ($value['amount'] != 0) {
601 $pending = TRUE;
602 //get the participant statuses.
603 $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
0d8afee2 604 $status = !empty($value['is_pay_later']) ? 'Pending from pay later' : 'Pending from incomplete transaction';
6a488035
TO
605 $value['participant_status_id'] = $value['participant_status'] = array_search($status, $pendingStatuses);
606 }
607 }
8cc574cf 608 elseif ($this->_contributeMode == 'express' && !empty($value['is_primary'])) {
0479b4c8 609 if (is_object($payment)) {
6a488035 610 $result = $payment->doExpressCheckout($value);
0479b4c8
TO
611 }
612 else {
6a488035 613 CRM_Core_Error::fatal($paymentObjError);
0479b4c8 614 }
6a488035 615 }
a7488080 616 elseif (!empty($value['is_primary'])) {
6a488035 617 CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
bd7b39e7
PJ
618 // payment email param can be empty for _bltID mapping
619 // thus provide mapping for it with a different email value
620 if (empty($value['email'])) {
621 $value['email'] = CRM_Utils_Array::valueByRegexKey('/^email-/', $value);
622 }
623
6a488035
TO
624 if (is_object($payment)) {
625 $result = $payment->doDirectPayment($value);
626 }
627 else {
628 CRM_Core_Error::fatal($paymentObjError);
629 }
630 }
631
632 if (is_a($result, 'CRM_Core_Error')) {
633 CRM_Core_Error::displaySessionError($result);
634 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
635 }
636
637 if ($result) {
638 $value = array_merge($value, $result);
639 }
640
641 $value['receive_date'] = $now;
642 if ($this->_allowConfirmation) {
643 $value['participant_register_date'] = $this->_values['participant']['register_date'];
644 }
645
646 $createContrib = ($value['amount'] != 0) ? TRUE : FALSE;
647 // force to create zero amount contribution, CRM-5095
648 if (!$createContrib && ($value['amount'] == 0)
649 && $this->_priceSetId && $this->_lineItem
650 ) {
651 $createContrib = TRUE;
652 }
653
8cc574cf 654 if ($createContrib && !empty($value['is_primary']) &&
6a488035
TO
655 !$this->_allowWaitlist && !$this->_requireApproval
656 ) {
657 // if paid event add a contribution record
658 //if primary participant contributing additional amount
659 //append (multiple participants) to its fee level. CRM-4196.
660 $isAdditionalAmount = FALSE;
661 if (count($params) > 1) {
662 $isAdditionalAmount = TRUE;
663 }
664
665 //passing contribution id is already registered.
317fceb4 666 $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
6a488035
TO
667 $value['contributionID'] = $contribution->id;
668 $value['contributionTypeID'] = $contribution->financial_type_id;
669 $value['receive_date'] = $contribution->receive_date;
670 $value['trxn_id'] = $contribution->trxn_id;
671 $value['contributionID'] = $contribution->id;
672 $value['contributionTypeID'] = $contribution->financial_type_id;
673 }
674 $value['contactID'] = $contactID;
353ffa53 675 $value['eventID'] = $this->_eventId;
6a488035
TO
676 $value['item_name'] = $value['description'];
677 }
9a32a8fc
GC
678
679 if (!empty($value['contributionID'])) {
680 $this->_values['contributionId'] = $value['contributionID'];
681 }
6a488035
TO
682
683 //CRM-4453.
a7488080 684 if (!empty($value['is_primary'])) {
6a488035
TO
685 $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
686 }
a7488080 687 if (empty($value['currencyID'])) {
6a488035
TO
688 $value['currencyID'] = $primaryCurrencyID;
689 }
690
1909126f 691 // CRM-11182 - Confirmation page might not be monetary
692 if ($this->_values['event']['is_monetary']) {
693 if (!$pending && !empty($value['is_primary']) &&
694 !$this->_allowWaitlist && !$this->_requireApproval
695 ) {
696 // transactionID & receive date required while building email template
697 $this->assign('trxn_id', $value['trxn_id']);
698 $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
699 $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
700 $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
701 }
6a488035 702 }
f55dc004 703
ffcec972 704 $value['fee_amount'] = CRM_Utils_Array::value('amount', $value);
6a488035
TO
705 $this->set('value', $value);
706
707 // handle register date CRM-4320
708 if ($this->_allowConfirmation) {
481a74f4 709 $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
6a488035 710 }
a7488080 711 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
712 is_array($params['participant_register_date']) &&
713 !empty($params['participant_register_date'])
714 ) {
715 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
716 }
717 else {
718 $registerDate = date('YmdHis');
719 }
720 $this->assign('register_date', $registerDate);
721
722 $this->confirmPostProcess($contactID, $contribution, $payment);
723 }
724
725 //handle if no additional participant.
726 if (!$registerByID) {
727 $registerByID = $this->get('registerByID');
728 }
729
730 $this->set('participantIDs', $this->_participantIDS);
731
732 // create line items, CRM-5313
733 if ($this->_priceSetId &&
734 !empty($this->_lineItem)
735 ) {
736 // take all processed participant ids.
737 $allParticipantIds = $this->_participantIDS;
738
739 // when participant re-walk wizard.
740 if ($this->_allowConfirmation &&
741 !empty($this->_additionalParticipantIds)
742 ) {
743 $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
744 }
745
746 $entityTable = 'civicrm_participant';
0479b4c8 747 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
03b412ae 748 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
79d001a2
PB
749 $totalTaxAmount = 0;
750 $dataArray = array();
6a488035
TO
751 foreach ($this->_lineItem as $key => $value) {
752 if (($value != 'skip') &&
753 ($entityId = CRM_Utils_Array::value($key, $allParticipantIds))
754 ) {
755
756 // do cleanup line items if participant re-walking wizard.
757 if ($this->_allowConfirmation) {
758 CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
759 }
760 $lineItem[$this->_priceSetId] = $value;
761 CRM_Price_BAO_LineItem::processPriceSet($entityId, $lineItem, $contribution, $entityTable);
762 }
03b412ae
PB
763 if ($invoicing) {
764 foreach ($value as $line) {
765 if (isset($line['tax_amount']) && isset($line['tax_rate'])) {
766 $totalTaxAmount = $line['tax_amount'] + $totalTaxAmount;
767 if (isset($dataArray[$line['tax_rate']])) {
768 $dataArray[$line['tax_rate']] = $dataArray[$line['tax_rate']] + CRM_Utils_Array::value('tax_amount', $line);
769 }
770 else {
771 $dataArray[$line['tax_rate']] = CRM_Utils_Array::value('tax_amount', $line);
772 }
79d001a2
PB
773 }
774 }
775 }
6a488035 776 }
03b412ae
PB
777 if ($invoicing) {
778 $this->assign('dataArray', $dataArray);
779 $this->assign('totalTaxAmount', $totalTaxAmount);
780 }
6a488035
TO
781 }
782
783 //update status and send mail to cancelled additonal participants, CRM-4320
784 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
785 $cancelledId = array_search('Cancelled',
786 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
787 );
788 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
789 }
790
791 $isTest = FALSE;
792 if ($this->_action & CRM_Core_Action::PREVIEW) {
793 $isTest = TRUE;
794 }
795
796 // for Transfer checkout.
797 if (($this->_contributeMode == 'checkout' ||
798 $this->_contributeMode == 'notify'
8cc574cf 799 ) && empty($params[0]['is_pay_later']) &&
6a488035
TO
800 !$this->_allowWaitlist && !$this->_requireApproval &&
801 $this->_totalAmount > 0
802 ) {
803
804 $primaryParticipant = $this->get('primaryParticipant');
805
a7488080 806 if (empty($primaryParticipant['participantID'])) {
6a488035
TO
807 $primaryParticipant['participantID'] = $registerByID;
808 }
809
810 //build an array of custom profile and assigning it to template
811 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
812 if (count($customProfile)) {
813 $this->assign('customProfile', $customProfile);
814 $this->set('customProfile', $customProfile);
815 }
816
817 // do a transfer only if a monetary payment greater than 0
818 if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
819 if ($payment && is_object($payment)) {
03665663 820 //CRM 14512 provide line items of all participants to payment gateway
821 $primaryContactId = $this->get('primaryContactId');
fb3b1f9a 822
03665663 823 //build an array of cId/pId of participants
824 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
825
826 //need to copy, since we are unsetting on the way.
827 $copyParticipantCountLines = $participantCount;
828
829 //lets carry all participant params w/ values.
830 foreach ($additionalIDs as $participantID => $contactId) {
831 $participantNum = NULL;
832 $participantNum = $participantID;
833 if ($participantID == $registerByID) {
834 $participantNum = 0; // is primary particpant
835 }
836 else {
837 if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
838 //if no participant found break.
839 if ($participantNum === NULL) {
840 break;
841 }
842 //unset current particpant so we don't check them again
843 unset($copyParticipantCountLines[$participantNum]);
844 }
845 }
846 // get values of line items
847 if ($this->_amount) {
848 $amount = array();
849 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
850 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
851 $params[$participantNum]['amounts'] = $amount;
852 }
853
854 if (!empty($this->_lineItem)) {
353ffa53
TO
855 $lineItems = $this->_lineItem;
856 $lineItem = array();
03665663 857 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
858 $lineItem[] = $lineItemValue;
859 }
860 $params[$participantNum]['lineItem'] = $lineItem;
861 }
862
863 //only add additional particpants and not the primary particpant as we already have that
864 //added to $primaryParticipant so that this change doesn't break or require changes to
865 //existing gateway implementations
866 $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];
867 }
868
869 //get event custom field information
870 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
871 $primaryParticipant['eventCustomFields'] = $groupTree;
fb3b1f9a 872
6a488035
TO
873 // call postprocess hook before leaving
874 $this->postProcessHook();
875 // this does not return
876 $payment->doTransferCheckout($primaryParticipant, 'event');
877 }
878 else {
879 CRM_Core_Error::fatal($paymentObjError);
880 }
881 }
882 }
883 else {
884 //otherwise send mail Confirmation/Receipt
885 $primaryContactId = $this->get('primaryContactId');
886
887 //build an array of cId/pId of participants
888 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID,
889 NULL, $primaryContactId, $isTest,
890 TRUE
891 );
892 //lets send mails to all with meaningful text, CRM-4320.
893 $this->assign('isOnWaitlist', $this->_allowWaitlist);
894 $this->assign('isRequireApproval', $this->_requireApproval);
895
896 //need to copy, since we are unsetting on the way.
897 $copyParticipantCount = $participantCount;
898
899 //lets carry all paticipant params w/ values.
900 foreach ($additionalIDs as $participantID => $contactId) {
901 $participantNum = NULL;
902 if ($participantID == $registerByID) {
903 $participantNum = 0;
904 }
905 else {
906 if ($participantNum = array_search('participant', $copyParticipantCount)) {
907 unset($copyParticipantCount[$participantNum]);
908 }
909 }
0479b4c8
TO
910 if ($participantNum === NULL) {
911 break;
912 }
6a488035
TO
913
914 //carry the participant submitted values.
915 $this->_values['params'][$participantID] = $params[$participantNum];
916 }
917
918 foreach ($additionalIDs as $participantID => $contactId) {
919 $participantNum = 0;
920 if ($participantID == $registerByID) {
921 //set as Primary Participant
922 $this->assign('isPrimary', 1);
923 //build an array of custom profile and assigning it to template.
924 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
925
926 if (count($customProfile)) {
927 $this->assign('customProfile', $customProfile);
928 $this->set('customProfile', $customProfile);
929 }
930 $this->_values['params']['additionalParticipant'] = FALSE;
931 }
932 else {
933 //take the Additional participant number.
934 if ($participantNum = array_search('participant', $participantCount)) {
935 unset($participantCount[$participantNum]);
936 }
937 $this->assign('isPrimary', 0);
938 $this->assign('customProfile', NULL);
939 //Additional Participant should get only it's payment information
1909126f 940 if (!empty($this->_amount)) {
6a488035
TO
941 $amount = array();
942 $params = $this->get('params');
943 $amount[$participantNum]['label'] = preg_replace('/\ 1/', '', $params[$participantNum]['amount_level']);
944 $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
945 $this->assign('amounts', $amount);
946 }
947 if ($this->_lineItem) {
353ffa53
TO
948 $lineItems = $this->_lineItem;
949 $lineItem = array();
6a488035
TO
950 if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
951 $lineItem[] = $lineItemValue;
952 }
75b065ce 953 if ($invoicing) {
954 $individual = $this->get('individual');
955 $dataArray[key($dataArray)] = $individual[$participantNum]['totalTaxAmt'];
956 $this->assign('dataArray', $dataArray);
957 $this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
958 $this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
959 $this->assign('individual', array($individual[$participantNum]));
960 }
6a488035
TO
961 $this->assign('lineItem', $lineItem);
962 }
963 $this->_values['params']['additionalParticipant'] = TRUE;
7d92d486 964 $this->assign('isAdditionalParticipant', $this->_values['params']['additionalParticipant']);
6a488035
TO
965 }
966
967 //pass these variables since these are run time calculated.
968 $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
969 $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
970
971 //send mail to primary as well as additional participants.
972 $this->assign('contactID', $contactId);
973 $this->assign('participantID', $participantID);
974 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
975 }
976 }
977 }
6a488035
TO
978
979 /**
66f9e52b 980 * Process the contribution.
6a488035 981 *
c490a46a
CW
982 * @param CRM_Core_Form $form
983 * @param array $params
dd244018 984 * @param $result
100fef9d 985 * @param int $contactID
dd244018
EM
986 * @param bool $pending
987 * @param bool $isAdditionalAmount
988 *
6a488035 989 * @return void
6a488035 990 */
317fceb4 991 public static function processContribution(
ddca8f33 992 &$form, $params, $result, $contactID,
6a488035
TO
993 $pending = FALSE, $isAdditionalAmount = FALSE
994 ) {
995 $transaction = new CRM_Core_Transaction();
996
353ffa53 997 $now = date('YmdHis');
6a488035
TO
998 $receiptDate = NULL;
999
bf2c70af 1000 if (!empty($form->_values['event']['is_email_confirm'])) {
6a488035
TO
1001 $receiptDate = $now;
1002 }
1003 //CRM-4196
1004 if ($isAdditionalAmount) {
1005 $params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR;
1006 }
1007
1008 $contribParams = array(
1009 'contact_id' => $contactID,
353ffa53 1010 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
6a488035
TO
1011 'receive_date' => $now,
1012 'total_amount' => $params['amount'],
d91b8b33 1013 'tax_amount' => $params['tax_amount'],
6a488035
TO
1014 'amount_level' => $params['amount_level'],
1015 'invoice_id' => $params['invoiceID'],
1016 'currency' => $params['currencyID'],
13bb29e4 1017 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
6a488035
TO
1018 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
1019 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
1020 );
1021
a7488080 1022 if (empty($params['is_pay_later'])) {
6a488035
TO
1023 $contribParams['payment_instrument_id'] = 1;
1024 }
1025
1026 if (!$pending && $result) {
1027 $contribParams += array(
1028 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1029 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
1030 'trxn_id' => $result['trxn_id'],
1031 'receipt_date' => $receiptDate,
1032 );
1033 }
1034
1035 $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1036 $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
1037 if ($pending) {
1038 $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
1039 }
1040
1041 $contribParams['is_test'] = 0;
1042 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
1043 $contribParams['is_test'] = 1;
1044 }
1045
1046 $contribID = NULL;
a7488080 1047 if (!empty($contribParams['invoice_id'])) {
6a488035
TO
1048 $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1049 $contribParams['invoice_id'],
1050 'id',
1051 'invoice_id'
1052 );
1053 }
1054
1055 $ids = array();
1056 if ($contribID) {
1057 $ids['contribution'] = $contribID;
1058 $contribParams['id'] = $contribID;
1059 }
1060
1061 //create an contribution address
8cc574cf 1062 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
6a488035
TO
1063 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1064 }
1065
1066 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
8cc574cf 1067 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
6a488035
TO
1068
1069 // if its due to pcp
a7488080 1070 if (!empty($params['pcp_made_through_id'])) {
6a488035
TO
1071 $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
1072 $params['pcp_made_through_id'],
1073 'contact_id'
1074 );
1075 }
1076 else {
1077 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1078 }
1079
1080 // Pass these details onto with the contribution to make them
1081 // available at hook_post_process, CRM-8908
1082 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
1083 }
1084 $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params);
1085 $contribParams['skipLineItem'] = 1;
1086 // create contribution record
1087 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
1088 // CRM-11124
b03a5fb5 1089 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, CRM_Utils_Array::value('amount_priceset_level_radio', $params, NULL));
6a488035
TO
1090
1091 // process soft credit / pcp pages
1092 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1093
1094 $transaction->commit();
1095
1096 return $contribution;
1097 }
1098
1099 /**
66f9e52b 1100 * Fix the Location Fields.
6a488035 1101 *
c490a46a 1102 * @param array $params
dd244018 1103 * @param $fields
c490a46a 1104 * @param CRM_Core_Form $form
dd244018 1105 *
6a488035 1106 * @return void
6a488035 1107 */
4fb756af 1108 public static function fixLocationFields(&$params, &$fields, &$form) {
a9f7d48b
AS
1109 if (!empty($form->_fields)) {
1110 foreach ($form->_fields as $name => $dontCare) {
6a488035
TO
1111 $fields[$name] = 1;
1112 }
1113 }
1114
1115 if (is_array($fields)) {
1116 if (!array_key_exists('first_name', $fields)) {
1117 $nameFields = array('first_name', 'middle_name', 'last_name');
1118 foreach ($nameFields as $name) {
1119 $fields[$name] = 1;
1120 if (array_key_exists("billing_$name", $params)) {
1121 $params[$name] = $params["billing_{$name}"];
1122 $params['preserveDBName'] = TRUE;
1123 }
1124 }
1125 }
1126 }
1127
1128 // also add location name to the array
a9f7d48b
AS
1129 if ($form->_values['event']['is_monetary']) {
1130 $params["address_name-{$form->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
1131 $fields["address_name-{$form->_bltID}"] = 1;
6a488035 1132 }
a9f7d48b 1133 $fields["email-{$form->_bltID}"] = 1;
6a488035
TO
1134 $fields['email-Primary'] = 1;
1135
1136 //if its pay later or additional participant set email address as primary.
8cc574cf 1137 if ((!empty($params['is_pay_later']) || empty($params['is_primary']) ||
a9f7d48b
AS
1138 !$form->_values['event']['is_monetary'] ||
1139 $form->_allowWaitlist ||
1140 $form->_requireApproval
353ffa53
TO
1141 ) && !empty($params["email-{$form->_bltID}"])
1142 ) {
a9f7d48b 1143 $params['email-Primary'] = $params["email-{$form->_bltID}"];
6a488035
TO
1144 }
1145 }
1146
1147 /**
66f9e52b 1148 * Update contact fields.
6a488035 1149 *
100fef9d 1150 * @param int $contactID
c490a46a 1151 * @param array $params
dd244018 1152 * @param $fields
c490a46a 1153 * @param CRM_Core_Form $form
dd244018 1154 *
6a488035 1155 * @return void
6a488035 1156 */
4fb756af 1157 public static function updateContactFields($contactID, $params, $fields, &$form) {
6a488035
TO
1158 //add the contact to group, if add to group is selected for a
1159 //particular uf group
1160
1161 // get the add to groups
1162 $addToGroups = array();
1163
a9f7d48b
AS
1164 if (!empty($form->_fields)) {
1165 foreach ($form->_fields as $key => $value) {
a7488080 1166 if (!empty($value['add_to_group_id'])) {
6a488035
TO
1167 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
1168 }
1169 }
1170 }
1171
1172 // check for profile double opt-in and get groups to be subscribed
1173 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
1174
1175 foreach ($addToGroups as $k) {
1176 if (array_key_exists($k, $subscribeGroupIds)) {
1177 unset($addToGroups[$k]);
1178 }
1179 }
1180
1181 // since we are directly adding contact to group lets unset it from mailing
1182 if (!empty($addToGroups)) {
1183 foreach ($addToGroups as $groupId) {
1184 if (isset($subscribeGroupIds[$groupId])) {
1185 unset($subscribeGroupIds[$groupId]);
1186 }
1187 }
1188 }
1189 if ($contactID) {
1190 $ctype = CRM_Core_DAO::getFieldValue(
1191 'CRM_Contact_DAO_Contact',
1192 $contactID,
1193 'contact_type'
1194 );
e1ce628e 1195
22e263ad 1196 if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) {
e1ce628e 1197 // we unset this here because the downstream function ignores the contactID we give it
1198 // if it is set & it is difficult to understand the implications of 'fixing' this downstream
1199 // but if we are passing a contact id into this function it's reasonable to assume we don't
1200 // want it ignored
1201 unset($params['contact_id']);
1202 }
1203
6a488035
TO
1204 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
1205 $params,
1206 $fields,
1207 $contactID,
1208 $addToGroups,
1209 NULL,
1210 $ctype,
1211 TRUE
1212 );
1213 }
1214 else {
1215
1216 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1217 if (!isset($params[$greeting . '_id'])) {
1218 $params[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
1219 }
1220 }
1221
1222 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params,
1223 $fields,
1224 NULL,
1225 $addToGroups,
1226 NULL,
1227 NULL,
1228 TRUE
1229 );
a9f7d48b 1230 $form->set('contactID', $contactID);
6a488035
TO
1231 }
1232
1233 //get email primary first if exist
1234 $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
1235 if (!$subscribtionEmail['email']) {
a9f7d48b 1236 $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
6a488035
TO
1237 }
1238 // subscribing contact to groups
1239 if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) {
1240 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID);
1241 }
1242
1243 return $contactID;
1244 }
5bdcb00b 1245
0cf587a7
EM
1246 /**
1247 * @param $form
1248 */
5bdcb00b 1249 public static function assignProfiles(&$form) {
5bdcb00b
PJ
1250 $participantParams = $form->_params;
1251 $formattedValues = $profileFields = array();
353ffa53 1252 $count = 1;
5bdcb00b
PJ
1253 foreach ($participantParams as $participantNum => $participantValue) {
1254 if ($participantNum) {
0479b4c8
TO
1255 $prefix1 = 'additional';
1256 $prefix2 = 'additional_';
0db6c3e1
TO
1257 }
1258 else {
0479b4c8
TO
1259 $prefix1 = '';
1260 $prefix2 = '';
5bdcb00b
PJ
1261 }
1262 if ($participantValue != 'skip') {
1263 //get the customPre profile info
1264 if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
1265 $values = $groupName = array();
1266 CRM_Event_BAO_Event::displayProfile($participantValue,
0479b4c8 1267 $form->_values[$prefix2 . 'custom_pre_id'],
5bdcb00b
PJ
1268 $groupName,
1269 $values,
1270 $profileFields
1271 );
1272
1273 if (count($values)) {
1274 $formattedValues[$count][$prefix1 . 'CustomPre'] = $values;
1275 }
1276 $formattedValues[$count][$prefix1 . 'CustomPreGroupTitle'] = CRM_Utils_Array::value('groupTitle', $groupName);
1277 }
1278 //get the customPost profile info
1279 if (!empty($form->_values[$prefix2 . 'custom_post_id'])) {
1280 $values = $groupName = array();
1281 foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) {
1282 $val = array();
1283 CRM_Event_BAO_Event::displayProfile($participantValue,
1284 $gids,
1285 $group,
1286 $val,
1287 $profileFields
1288 );
1289 $values[$gids] = $val;
1290 $groupName[$gids] = $group;
1291 }
1292
1293 if (count($values)) {
1294 $formattedValues[$count][$prefix1 . 'CustomPost'] = $values;
1295 }
1296
1297 if (isset($formattedValues[$count][$prefix1 . 'CustomPre'])) {
1298 $formattedValues[$count][$prefix1 . 'CustomPost'] = array_diff_assoc($formattedValues[$count][$prefix1 . 'CustomPost'],
1299 $formattedValues[$count][$prefix1 . 'CustomPre']
1300 );
1301 }
1302
1303 $formattedValues[$count][$prefix1 . 'CustomPostGroupTitle'] = $groupName;
1304 }
1305 $count++;
1306 }
1307 $form->_fields = $profileFields;
1308 }
481a74f4 1309 if (!empty($formattedValues)) {
5bdcb00b 1310 $form->assign('primaryParticipantProfile', $formattedValues[1]);
0479b4c8 1311 $form->set('primaryParticipantProfile', $formattedValues[1]);
5bdcb00b
PJ
1312 if ($count > 2) {
1313 unset($formattedValues[1]);
1314 $form->assign('addParticipantProfile', $formattedValues);
0479b4c8 1315 $form->set('addParticipantProfile', $formattedValues);
5bdcb00b
PJ
1316 }
1317 }
1318 }
96025800 1319
6a488035 1320}