Post-upgrade messages no longer being displayed (part 2)
[civicrm-core.git] / CRM / Event / Form / Registration.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17 /**
18 * This class generates form components for processing Event.
19 */
20 class CRM_Event_Form_Registration extends CRM_Core_Form {
21
22 use CRM_Financial_Form_FrontEndPaymentFormTrait;
23
24 /**
25 * How many locationBlocks should we display?
26 *
27 * @var int
28 * @const
29 */
30 const LOCATION_BLOCKS = 1;
31
32 /**
33 * The id of the event we are processing.
34 *
35 * @var int
36 */
37 public $_eventId;
38
39 /**
40 * Get the event it.
41 *
42 * @return int
43 */
44 protected function getEventID(): int {
45 return $this->_eventId;
46 }
47
48 /**
49 * The array of ids of all the participant we are processing.
50 *
51 * @var int
52 */
53 protected $_participantIDS = NULL;
54
55 /**
56 * The id of the participant we are processing.
57 *
58 * @var int
59 */
60 protected $_participantId;
61
62 /**
63 * Is participant able to walk registration wizard.
64 *
65 * @var bool
66 */
67 public $_allowConfirmation;
68
69 /**
70 * Is participant requires approval.
71 *
72 * @var bool
73 */
74 public $_requireApproval;
75
76 /**
77 * Is event configured for waitlist.
78 *
79 * @var bool
80 */
81 public $_allowWaitlist;
82
83 /**
84 * Store additional participant ids.
85 * when there are pre-registered.
86 *
87 * @var array
88 */
89 public $_additionalParticipantIds;
90
91 /**
92 * The values for the contribution db object.
93 *
94 * @var array
95 */
96 public $_values;
97
98 /**
99 * The paymentProcessor attributes for this page.
100 *
101 * @var array
102 */
103 public $_paymentProcessor;
104
105 /**
106 * The params submitted by the form and computed by the app.
107 *
108 * @var array
109 */
110 protected $_params;
111
112 /**
113 * The fields involved in this contribution page.
114 *
115 * @var array
116 */
117 public $_fields;
118
119 /**
120 * The billing location id for this contribution page.
121 *
122 * @var int
123 */
124 public $_bltID;
125
126 /**
127 * Price Set ID, if the new price set method is used
128 *
129 * @var int
130 */
131 public $_priceSetId = NULL;
132
133 /**
134 * Array of fields for the price set.
135 *
136 * @var array
137 */
138 public $_priceSet;
139
140 public $_action;
141
142 public $_pcpId;
143
144 /**
145 * Is event already full.
146 *
147 * @var bool
148 *
149 */
150 public $_isEventFull;
151
152 public $_lineItem;
153
154 public $_lineItemParticipantsCount;
155
156 public $_availableRegistrations;
157
158 /**
159 * @var bool
160 * @deprecated
161 */
162 public $_isBillingAddressRequiredForPayLater;
163
164 /**
165 * Is this a back office form
166 *
167 * @var bool
168 */
169 public $isBackOffice = FALSE;
170
171 /**
172 * Payment instrument iD for the transaction.
173 *
174 * This will generally be drawn from the payment processor and is ignored for
175 * front end forms.
176 *
177 * @var int
178 */
179 public $paymentInstrumentID;
180
181 /**
182 * Set variables up before form is built.
183 */
184 public function preProcess() {
185 $this->_eventId = (int) CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
186 $this->_action = CRM_Utils_Request::retrieve('action', 'Alphanumeric', $this, FALSE, CRM_Core_Action::ADD);
187 //CRM-4320
188 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
189 $this->setPaymentMode();
190
191 $this->_values = $this->get('values');
192 $this->_fields = $this->get('fields');
193 $this->_bltID = $this->get('bltID');
194 $this->_paymentProcessor = $this->get('paymentProcessor');
195 $this->_priceSetId = $this->get('priceSetId');
196 $this->_priceSet = $this->get('priceSet');
197 $this->_lineItem = $this->get('lineItem');
198 $this->_isEventFull = $this->get('isEventFull');
199 $this->_lineItemParticipantsCount = $this->get('lineItemParticipants');
200 if (!is_array($this->_lineItem)) {
201 $this->_lineItem = [];
202 }
203 if (!is_array($this->_lineItemParticipantsCount)) {
204 $this->_lineItemParticipantsCount = [];
205 }
206 $this->_availableRegistrations = $this->get('availableRegistrations');
207 $this->_participantIDS = $this->get('participantIDs');
208
209 //check if participant allow to walk registration wizard.
210 $this->_allowConfirmation = $this->get('allowConfirmation');
211
212 // check for Approval
213 $this->_requireApproval = $this->get('requireApproval');
214
215 // check for waitlisting.
216 $this->_allowWaitlist = $this->get('allowWaitlist');
217
218 //get the additional participant ids.
219 $this->_additionalParticipantIds = $this->get('additionalParticipantIds');
220
221 if (!$this->_values) {
222 // this is the first time we are hitting this, so check for permissions here
223 if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) {
224 CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $this->getInfoPageUrl());
225 }
226
227 // get all the values from the dao object
228 $this->_values = $this->_fields = [];
229
230 //retrieve event information
231 $params = ['id' => $this->_eventId];
232 CRM_Event_BAO_Event::retrieve($params, $this->_values['event']);
233
234 CRM_Event_BAO_Event::setOutputTimeZone($this->_values['event'], $this->_values['event']['event_tz']);
235
236 // check for is_monetary status
237 $isMonetary = $this->_values['event']['is_monetary'] ?? NULL;
238 // check for ability to add contributions of type
239 if ($isMonetary
240 && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
241 && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['event']['financial_type_id']))
242 ) {
243 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
244 }
245
246 $this->checkValidEvent();
247 // get the participant values, CRM-4320
248 $this->_allowConfirmation = FALSE;
249 if ($this->_participantId) {
250 $this->processFirstParticipant($this->_participantId);
251 }
252 //check for additional participants.
253 if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) {
254 $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
255 $cnt = 1;
256 foreach ($additionalParticipantIds as $additionalParticipantId) {
257 $this->_additionalParticipantIds[$cnt] = $additionalParticipantId;
258 $cnt++;
259 }
260 $this->set('additionalParticipantIds', $this->_additionalParticipantIds);
261 }
262
263 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE,
264 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
265 );
266
267 $this->_allowWaitlist = $this->_isEventFull = FALSE;
268 if ($eventFull && !$this->_allowConfirmation) {
269 $this->_isEventFull = TRUE;
270 //lets redirecting to info only when to waiting list.
271 $this->_allowWaitlist = $this->_values['event']['has_waitlist'] ?? NULL;
272 if (!$this->_allowWaitlist) {
273 CRM_Utils_System::redirect($this->getInfoPageUrl());
274 }
275 }
276 $this->set('isEventFull', $this->_isEventFull);
277 $this->set('allowWaitlist', $this->_allowWaitlist);
278
279 //check for require requires approval.
280 $this->_requireApproval = FALSE;
281 if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) {
282 $this->_requireApproval = TRUE;
283 }
284 $this->set('requireApproval', $this->_requireApproval);
285
286 if (isset($this->_values['event']['default_role_id'])) {
287 $participant_role = CRM_Core_OptionGroup::values('participant_role');
288 $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"];
289 }
290 $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later');
291 $this->setPayLaterLabel($isPayLater ? $this->_values['event']['pay_later_text'] : '');
292 //check for various combinations for paylater, payment
293 //process with paid event.
294 if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) {
295 $this->_paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor',
296 $this->_values['event']
297 ));
298 $this->assignPaymentProcessor($isPayLater);
299 }
300 //init event fee.
301 self::initEventFee($this, $this->_eventId);
302
303 // get the profile ids
304 $ufJoinParams = [
305 'entity_table' => 'civicrm_event',
306 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
307 'module' => 'CiviEvent',
308 'entity_id' => $this->_eventId,
309 ];
310 [$this->_values['custom_pre_id'], $this->_values['custom_post_id']] = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
311
312 // set profiles for additional participants
313 if ($this->_values['event']['is_multiple_registrations']) {
314 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
315 $ufJoinParams['module'] = 'CiviEvent_Additional';
316
317 [$this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive] = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
318
319 // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact
320 // set same profile for additional contacts.
321 if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) {
322 $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id'];
323 }
324
325 if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) {
326 $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id'];
327 }
328 // now check for no profile condition, in that case is_active = 0
329 if (isset($preActive) && !$preActive) {
330 unset($this->_values['additional_custom_pre_id']);
331 }
332 if (isset($postActive) && !$postActive) {
333 unset($this->_values['additional_custom_post_id']);
334 }
335 }
336
337 $this->assignBillingType();
338
339 if ($this->_values['event']['is_monetary']) {
340 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
341 }
342 $params = ['entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event'];
343 $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
344
345 $this->set('values', $this->_values);
346 $this->set('fields', $this->_fields);
347
348 $this->_availableRegistrations
349 = CRM_Event_BAO_Participant::eventFull(
350 $this->_values['event']['id'], TRUE,
351 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
352 );
353 $this->set('availableRegistrations', $this->_availableRegistrations);
354 }
355 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
356
357 // check if this is a paypal auto return and redirect accordingly
358 if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
359 $url = CRM_Utils_System::url('civicrm/event/register',
360 "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"
361 );
362 CRM_Utils_System::redirect($url);
363 }
364 // The concept of contributeMode is deprecated.
365 $this->_contributeMode = $this->get('contributeMode');
366 $this->assign('contributeMode', $this->_contributeMode);
367
368 $this->setTitle($this->_values['event']['title']);
369
370 $this->assign('paidEvent', $this->_values['event']['is_monetary']);
371
372 // we do not want to display recently viewed items on Registration pages
373 $this->assign('displayRecent', FALSE);
374
375 $isShowLocation = $this->_values['event']['is_show_location'] ?? NULL;
376 $this->assign('isShowLocation', $isShowLocation);
377 // Handle PCP
378 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
379 if ($pcpId) {
380 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']);
381 $this->_pcpId = $pcp['pcpId'];
382 $this->_values['event']['intro_text'] = $pcp['pcpInfo']['intro_text'] ?? NULL;
383 }
384
385 // assign all event properties so wizard templates can display event info.
386 $this->assign('event', $this->_values['event']);
387 $this->assign('location', $this->_values['location']);
388 $this->assign('bltID', $this->_bltID);
389 $isShowLocation = $this->_values['event']['is_show_location'] ?? NULL;
390 $this->assign('isShowLocation', $isShowLocation);
391 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values['event']);
392
393 //lets allow user to override campaign.
394 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
395 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
396 $this->_values['event']['campaign_id'] = $campID;
397 }
398
399 // Set the same value for is_billing_required as contribution page so code can be shared.
400 $this->_values['is_billing_required'] = $this->_values['event']['is_billing_required'] ?? NULL;
401 // check if billing block is required for pay later
402 // note that I have started removing the use of isBillingAddressRequiredForPayLater in favour of letting
403 // the CRM_Core_Payment_Manual class handle it - but there are ~300 references to it in the code base so only
404 // removing in very limited cases.
405 if (!empty($this->_values['event']['is_pay_later'])) {
406 $this->_isBillingAddressRequiredForPayLater = $this->_values['event']['is_billing_required'] ?? NULL;
407 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
408 }
409 }
410
411 /**
412 * Assign the minimal set of variables to the template.
413 */
414 public function assignToTemplate() {
415 //process only primary participant params
416 $this->_params = $this->get('params');
417 if (isset($this->_params[0])) {
418 $params = $this->_params[0];
419 }
420 $name = '';
421 if (!empty($params['billing_first_name'])) {
422 $name = $params['billing_first_name'];
423 }
424
425 if (!empty($params['billing_middle_name'])) {
426 $name .= " {$params['billing_middle_name']}";
427 }
428
429 if (!empty($params['billing_last_name'])) {
430 $name .= " {$params['billing_last_name']}";
431 }
432 $this->assign('billingName', $name);
433 $this->set('name', $name);
434
435 $vars = [
436 'amount',
437 'currencyID',
438 'credit_card_type',
439 'trxn_id',
440 'amount_level',
441 'receive_date',
442 ];
443
444 foreach ($vars as $v) {
445 if (!empty($params[$v])) {
446 if ($v === 'receive_date') {
447 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
448 }
449 else {
450 $this->assign($v, $params[$v]);
451 }
452 }
453 elseif (empty($params['amount'])) {
454 $this->assign($v, CRM_Utils_Array::value($v, $params));
455 }
456 }
457
458 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
459
460 // The concept of contributeMode is deprecated.
461 if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
462 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
463 $date = CRM_Utils_Date::mysqlToIso($date);
464 $this->assign('credit_card_exp_date', $date);
465 $this->assign('credit_card_number',
466 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params))
467 );
468 }
469
470 // assign is_email_confirm to templates
471 if (isset($this->_values['event']['is_email_confirm'])) {
472 $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
473 }
474
475 // assign pay later stuff
476 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
477 $this->assign('is_pay_later', $params['is_pay_later']);
478 if ($params['is_pay_later']) {
479 $this->assign('pay_later_text', $this->getPayLaterLabel());
480 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
481 }
482
483 // also assign all participantIDs to the template
484 // useful in generating confirmation numbers if needed
485 $this->assign('participantIDs', $this->_participantIDS);
486 }
487
488 /**
489 * Add the custom fields.
490 *
491 * @param int $id
492 * @param string $name
493 */
494 public function buildCustom($id, $name) {
495 if (!$id) {
496 return;
497 }
498
499 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
500 $contactID = CRM_Core_Session::getLoggedInContactID();
501 $fields = [];
502
503 // we don't allow conflicting fields to be
504 // configured via profile
505 $fieldsToIgnore = [
506 'participant_fee_amount' => 1,
507 'participant_fee_level' => 1,
508 ];
509 if ($contactID) {
510 //FIX CRM-9653
511 if (is_array($id)) {
512 $fields = [];
513 foreach ($id as $profileID) {
514 $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD,
515 NULL, NULL, FALSE, NULL,
516 FALSE, NULL, CRM_Core_Permission::CREATE,
517 'field_name', TRUE
518 );
519 $fields = array_merge($fields, $field);
520 }
521 }
522 else {
523 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
524 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
525 NULL, NULL, FALSE, NULL,
526 FALSE, NULL, CRM_Core_Permission::CREATE,
527 'field_name', TRUE
528 );
529 }
530 }
531 }
532 else {
533 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
534 NULL, NULL, FALSE, NULL,
535 FALSE, NULL, CRM_Core_Permission::CREATE,
536 'field_name', TRUE
537 );
538 }
539
540 if (array_intersect_key($fields, $fieldsToIgnore)) {
541 $fields = array_diff_key($fields, $fieldsToIgnore);
542 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'));
543 }
544 $addCaptcha = FALSE;
545
546 if (!empty($this->_fields)) {
547 $fields = @array_diff_assoc($fields, $this->_fields);
548 }
549
550 if (empty($this->_params[0]['additional_participants']) &&
551 is_null($cid)
552 ) {
553 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
554 }
555 $this->assign($name, $fields);
556 if (is_array($fields)) {
557 $button = substr($this->controller->getButtonName(), -4);
558 foreach ($fields as $key => $field) {
559 //make the field optional if primary participant
560 //have been skip the additional participant.
561 if ($button == 'skip') {
562 $field['is_required'] = FALSE;
563 }
564 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
565 elseif ($field['add_captcha'] && !$contactID) {
566 // only add captcha for first page
567 $addCaptcha = TRUE;
568 }
569 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
570
571 $this->_fields[$key] = $field;
572 }
573 }
574
575 if ($addCaptcha) {
576 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
577 }
578 }
579
580 /**
581 * Initiate event fee.
582 *
583 * @param CRM_Core_Form $form
584 * @param int $eventID
585 * @param bool $doNotIncludeExpiredFields
586 * See CRM-16456.
587 *
588 * @throws Exception
589 */
590 public static function initEventFee(&$form, $eventID, $doNotIncludeExpiredFields = TRUE) {
591 // get price info
592
593 // retrive all active price set fields.
594 $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
595 if (property_exists($form, '_discountId') && $form->_discountId) {
596 $discountId = $form->_discountId;
597 }
598
599 if ($discountId) {
600 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
601 }
602 else {
603 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID);
604 }
605 CRM_Price_BAO_PriceSet::initSet($form, 'civicrm_event', $doNotIncludeExpiredFields, $priceSetId);
606
607 if (property_exists($form, '_context') && ($form->_context == 'standalone'
608 || $form->_context == 'participant')
609 ) {
610 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
611 if (is_array($discountedEvent)) {
612 foreach ($discountedEvent as $key => $priceSetId) {
613 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
614 $priceSet = $priceSet[$priceSetId] ?? NULL;
615 $form->_values['discount'][$key] = $priceSet['fields'] ?? NULL;
616 $fieldID = key($form->_values['discount'][$key]);
617 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue(
618 'CRM_Price_DAO_PriceSet',
619 $priceSetId,
620 'title'
621 );
622 }
623 }
624 }
625 $eventFee = $form->_values['fee'] ?? NULL;
626 if (!is_array($eventFee) || empty($eventFee)) {
627 $form->_values['fee'] = [];
628 }
629
630 //fix for non-upgraded price sets.CRM-4256.
631 if (isset($form->_isPaidEvent)) {
632 $isPaidEvent = $form->_isPaidEvent;
633 }
634 else {
635 $isPaidEvent = $form->_values['event']['is_monetary'] ?? NULL;
636 }
637 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
638 && !empty($form->_values['fee'])
639 ) {
640 foreach ($form->_values['fee'] as $k => $fees) {
641 foreach ($fees['options'] as $options) {
642 if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
643 unset($form->_values['fee'][$k]);
644 }
645 }
646 }
647 }
648 if ($isPaidEvent && empty($form->_values['fee'])) {
649 if (!in_array(CRM_Utils_System::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
650 CRM_Core_Error::statusBounce(ts('No Fee Level(s) or Price Set is configured for this event.<br />Click <a href=\'%1\'>CiviEvent >> Manage Event >> Configure >> Event Fees</a> to configure the Fee Level(s) or Price Set for this event.', [1 => CRM_Utils_System::url('civicrm/event/manage/fee', 'reset=1&action=update&id=' . $form->_eventId)]));
651 }
652 }
653 }
654
655 /**
656 * Handle process after the confirmation of payment by User.
657 *
658 * @param int $contactID
659 * @param \CRM_Contribute_BAO_Contribution $contribution
660 *
661 * @throws \CiviCRM_API3_Exception
662 */
663 public function confirmPostProcess($contactID = NULL, $contribution = NULL) {
664 // add/update contact information
665 unset($this->_params['note']);
666
667 //to avoid conflict overwrite $this->_params
668 $this->_params = $this->get('value');
669
670 //get the amount of primary participant
671 if (!empty($this->_params['is_primary'])) {
672 $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
673 }
674
675 // add participant record
676 $participant = $this->addParticipant($this, $contactID);
677 $this->_participantIDS[] = $participant->id;
678
679 //setting register_by_id field and primaryContactId
680 if (!empty($this->_params['is_primary'])) {
681 $this->set('registerByID', $participant->id);
682 $this->set('primaryContactId', $contactID);
683
684 // CRM-10032
685 $this->processFirstParticipant($participant->id);
686 }
687
688 if (!empty($this->_params['is_primary'])) {
689 $this->_params['participantID'] = $participant->id;
690 $this->set('primaryParticipant', $this->_params);
691 }
692
693 $createPayment = (CRM_Utils_Array::value('amount', $this->_params, 0) != 0) ? TRUE : FALSE;
694
695 // force to create zero amount payment, CRM-5095
696 // we know the amout is zero since createPayment is false
697 if (!$createPayment &&
698 (isset($contribution) && $contribution->id) &&
699 $this->_priceSetId &&
700 $this->_lineItem
701 ) {
702 $createPayment = TRUE;
703 }
704
705 if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
706 $paymentParams = [
707 'participant_id' => $participant->id,
708 'contribution_id' => $contribution->id,
709 ];
710 civicrm_api3('ParticipantPayment', 'create', $paymentParams);
711 }
712
713 $this->assign('action', $this->_action);
714
715 // create CMS user
716 if (!empty($this->_params['cms_create_account'])) {
717 $this->_params['contactID'] = $contactID;
718
719 if (array_key_exists('email-5', $this->_params)) {
720 $mail = 'email-5';
721 }
722 else {
723 foreach ($this->_params as $name => $dontCare) {
724 if (substr($name, 0, 5) == 'email') {
725 $mail = $name;
726 break;
727 }
728 }
729 }
730
731 // we should use primary email for
732 // 1. pay later participant.
733 // 2. waiting list participant.
734 // 3. require approval participant.
735 if (!empty($this->_params['is_pay_later']) ||
736 $this->_allowWaitlist || $this->_requireApproval
737 ) {
738 $mail = 'email-Primary';
739 }
740
741 if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
742 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
743 }
744 }
745 }
746
747 /**
748 * Process the participant.
749 *
750 * @param CRM_Core_Form $form
751 * @param int $contactID
752 *
753 * @return \CRM_Event_BAO_Participant
754 * @throws \CiviCRM_API3_Exception
755 */
756 protected function addParticipant(&$form, $contactID) {
757 if (empty($form->_params)) {
758 return NULL;
759 }
760 // Note this used to be shared with the backoffice form & no longer is, some code may no longer be required.
761 $params = $form->_params;
762 $transaction = new CRM_Core_Transaction();
763
764 // handle register date CRM-4320
765 $registerDate = NULL;
766 if (!empty($form->_allowConfirmation) && $form->_participantId) {
767 $registerDate = $params['participant_register_date'];
768 }
769 elseif (!empty($params['participant_register_date']) &&
770 is_array($params['participant_register_date']) &&
771 !empty($params['participant_register_date'])
772 ) {
773 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
774 }
775
776 $participantFields = CRM_Event_DAO_Participant::fields();
777 $participantParams = [
778 'id' => $params['participant_id'] ?? NULL,
779 'contact_id' => $contactID,
780 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
781 'status_id' => CRM_Utils_Array::value('participant_status',
782 $params, 1
783 ),
784 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: CRM_Event_BAO_Participant::getDefaultRoleID(),
785 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
786 'source' => CRM_Utils_String::ellipsify(
787 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
788 $participantFields['participant_source']['maxlength']
789 ),
790 'fee_level' => $params['amount_level'] ?? NULL,
791 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
792 'fee_amount' => $params['fee_amount'] ?? NULL,
793 'registered_by_id' => $params['registered_by_id'] ?? NULL,
794 'discount_id' => $params['discount_id'] ?? NULL,
795 'fee_currency' => $params['currencyID'] ?? NULL,
796 'campaign_id' => $params['campaign_id'] ?? NULL,
797 ];
798
799 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
800 $participantParams['is_test'] = 1;
801 }
802 else {
803 $participantParams['is_test'] = 0;
804 }
805
806 if (!empty($form->_params['note'])) {
807 $participantParams['note'] = $form->_params['note'];
808 }
809 elseif (!empty($form->_params['participant_note'])) {
810 $participantParams['note'] = $form->_params['participant_note'];
811 }
812
813 // reuse id if one already exists for this one (can happen
814 // with back button being hit etc)
815 if (!$participantParams['id'] && !empty($params['contributionID'])) {
816 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
817 $params['contributionID'],
818 'participant_id',
819 'contribution_id'
820 );
821 $participantParams['id'] = $pID;
822 }
823 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
824
825 if (!$participantParams['discount_id']) {
826 $participantParams['discount_id'] = "null";
827 }
828
829 $participantParams['custom'] = [];
830 foreach ($form->_params as $paramName => $paramValue) {
831 if (strpos($paramName, 'custom_') === 0) {
832 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($paramName, TRUE);
833 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $participantParams['custom'], $paramValue, 'Participant', $customValueID);
834
835 }
836 }
837
838 $participant = CRM_Event_BAO_Participant::create($participantParams);
839
840 $transaction->commit();
841
842 return $participant;
843 }
844
845 /**
846 * Calculate the total participant count as per params.
847 *
848 * @param CRM_Core_Form $form
849 * @param array $params
850 * User params.
851 * @param bool $skipCurrent
852 *
853 * @return int
854 */
855 public static function getParticipantCount(&$form, $params, $skipCurrent = FALSE) {
856 $totalCount = 0;
857 if (!is_array($params) || empty($params)) {
858 return $totalCount;
859 }
860
861 $priceSetId = $form->get('priceSetId');
862 $addParticipantNum = substr($form->_name, 12);
863 $priceSetFields = $priceSetDetails = [];
864 $hasPriceFieldsCount = FALSE;
865 if ($priceSetId) {
866 $priceSetDetails = $form->get('priceSet');
867 if (isset($priceSetDetails['optionsCountTotal'])
868 && $priceSetDetails['optionsCountTotal']
869 ) {
870 $hasPriceFieldsCount = TRUE;
871 $priceSetFields = $priceSetDetails['optionsCountDetails']['fields'];
872 }
873 }
874
875 $singleFormParams = FALSE;
876 foreach ($params as $key => $val) {
877 if (!is_numeric($key)) {
878 $singleFormParams = TRUE;
879 break;
880 }
881 }
882
883 //first format the params.
884 if ($singleFormParams) {
885 $params = self::formatPriceSetParams($form, $params);
886 $params = [$params];
887 }
888
889 foreach ($params as $key => $values) {
890 if (!is_numeric($key) ||
891 $values == 'skip' ||
892 ($skipCurrent && ($addParticipantNum == $key))
893 ) {
894 continue;
895 }
896 $count = 1;
897
898 $usedCache = FALSE;
899 $cacheCount = $form->_lineItemParticipantsCount[$key] ?? NULL;
900 if ($cacheCount && is_numeric($cacheCount)) {
901 $count = $cacheCount;
902 $usedCache = TRUE;
903 }
904
905 if (!$usedCache && $hasPriceFieldsCount) {
906 $count = 0;
907 foreach ($values as $valKey => $value) {
908 if (strpos($valKey, 'price_') === FALSE) {
909 continue;
910 }
911 $priceFieldId = substr($valKey, 6);
912 if (!$priceFieldId ||
913 !is_array($value) ||
914 !array_key_exists($priceFieldId, $priceSetFields)
915 ) {
916 continue;
917 }
918 foreach ($value as $optId => $optVal) {
919 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
920 if ($currentCount) {
921 $count += $currentCount;
922 }
923 }
924 }
925 if (!$count) {
926 $count = 1;
927 }
928 }
929 $totalCount += $count;
930 }
931 if (!$totalCount) {
932 $totalCount = 1;
933 }
934
935 return $totalCount;
936 }
937
938 /**
939 * Format user submitted price set params.
940 *
941 * Convert price set each param as an array.
942 *
943 * @param CRM_Core_Form $form
944 * @param array $params
945 * An array of user submitted params.
946 *
947 * @return array
948 * Formatted price set params.
949 */
950 public static function formatPriceSetParams(&$form, $params) {
951 if (!is_array($params) || empty($params)) {
952 return $params;
953 }
954
955 $priceSetId = $form->get('priceSetId');
956 if (!$priceSetId) {
957 return $params;
958 }
959 $priceSetDetails = $form->get('priceSet');
960
961 foreach ($params as $key => & $value) {
962 $vals = [];
963 if (strpos($key, 'price_') !== FALSE) {
964 $fieldId = substr($key, 6);
965 if (!array_key_exists($fieldId, $priceSetDetails['fields']) ||
966 is_array($value) ||
967 !$value
968 ) {
969 continue;
970 }
971 $field = $priceSetDetails['fields'][$fieldId];
972 if ($field['html_type'] == 'Text') {
973 $fieldOption = current($field['options']);
974 $value = [$fieldOption['id'] => $value];
975 }
976 else {
977 $value = [$value => TRUE];
978 }
979 }
980 }
981
982 return $params;
983 }
984
985 /**
986 * Calculate total count for each price set options.
987 *
988 * - currently selected by user.
989 *
990 * @param CRM_Core_Form $form
991 * Form object.
992 *
993 * @return array
994 * array of each option w/ count total.
995 */
996 public static function getPriceSetOptionCount(&$form) {
997 $params = $form->get('params');
998 $priceSet = $form->get('priceSet');
999 $priceSetId = $form->get('priceSetId');
1000
1001 $optionsCount = [];
1002 if (!$priceSetId ||
1003 !is_array($priceSet) ||
1004 empty($priceSet) ||
1005 !is_array($params) ||
1006 empty($params)
1007 ) {
1008 return $optionsCount;
1009 }
1010
1011 $priceSetFields = $priceMaxFieldDetails = [];
1012 if (!empty($priceSet['optionsCountTotal'])) {
1013 $priceSetFields = $priceSet['optionsCountDetails']['fields'];
1014 }
1015
1016 if (!empty($priceSet['optionsMaxValueTotal'])) {
1017 $priceMaxFieldDetails = $priceSet['optionsMaxValueDetails']['fields'];
1018 }
1019
1020 $addParticipantNum = substr($form->_name, 12);
1021 foreach ($params as $pCnt => $values) {
1022 if ($values == 'skip' ||
1023 $pCnt === $addParticipantNum
1024 ) {
1025 continue;
1026 }
1027
1028 foreach ($values as $valKey => $value) {
1029 if (strpos($valKey, 'price_') === FALSE) {
1030 continue;
1031 }
1032
1033 $priceFieldId = substr($valKey, 6);
1034 if (!$priceFieldId ||
1035 !is_array($value) ||
1036 !(array_key_exists($priceFieldId, $priceSetFields) || array_key_exists($priceFieldId, $priceMaxFieldDetails))
1037 ) {
1038 continue;
1039 }
1040
1041 foreach ($value as $optId => $optVal) {
1042 if (CRM_Utils_Array::value('html_type', $priceSet['fields'][$priceFieldId]) == 'Text') {
1043 $currentCount = $optVal;
1044 }
1045 else {
1046 $currentCount = 1;
1047 }
1048
1049 if (isset($priceSetFields[$priceFieldId]) && isset($priceSetFields[$priceFieldId]['options'][$optId])) {
1050 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1051 }
1052
1053 $optionsCount[$optId] = $currentCount + CRM_Utils_Array::value($optId, $optionsCount, 0);
1054 }
1055 }
1056 }
1057
1058 return $optionsCount;
1059 }
1060
1061 /**
1062 * Check template file exists.
1063 *
1064 * @param string|null $suffix
1065 *
1066 * @return string|null
1067 * Template file path, else null
1068 */
1069 public function checkTemplateFileExists($suffix = NULL) {
1070 if ($this->_eventId) {
1071 $templateName = $this->_name;
1072 if (substr($templateName, 0, 12) == 'Participant_') {
1073 $templateName = 'AdditionalParticipant';
1074 }
1075
1076 $templateFile = "CRM/Event/Form/Registration/{$this->_eventId}/{$templateName}.{$suffix}tpl";
1077 $template = CRM_Core_Form::getTemplate();
1078 if ($template->template_exists($templateFile)) {
1079 return $templateFile;
1080 }
1081 }
1082 return NULL;
1083 }
1084
1085 /**
1086 * Get template file name.
1087 *
1088 * @return null|string
1089 */
1090 public function getTemplateFileName() {
1091 $fileName = $this->checkTemplateFileExists();
1092 return $fileName ? $fileName : parent::getTemplateFileName();
1093 }
1094
1095 /**
1096 * Override extra template name.
1097 *
1098 * @return null|string
1099 */
1100 public function overrideExtraTemplateFileName() {
1101 $fileName = $this->checkTemplateFileExists('extra.');
1102 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1103 }
1104
1105 /**
1106 * Reset values for all options those are full.
1107 *
1108 * @param array $optionFullIds
1109 * @param CRM_Core_Form $form
1110 */
1111 public static function resetElementValue($optionFullIds, &$form) {
1112 if (!is_array($optionFullIds) ||
1113 empty($optionFullIds) ||
1114 !$form->isSubmitted()
1115 ) {
1116 return;
1117 }
1118
1119 foreach ($optionFullIds as $fldId => $optIds) {
1120 $name = "price_$fldId";
1121 if (!$form->elementExists($name)) {
1122 continue;
1123 }
1124
1125 $element = $form->getElement($name);
1126 $eleType = $element->getType();
1127
1128 $resetSubmitted = FALSE;
1129 switch ($eleType) {
1130 case 'text':
1131 if ($element->getValue() && $element->isFrozen()) {
1132 $label = "{$element->getLabel()}<tt>(x)</tt>";
1133 $element->setLabel($label);
1134 $element->setPersistantFreeze();
1135 $resetSubmitted = TRUE;
1136 }
1137 break;
1138
1139 case 'group':
1140 if (is_array($element->_elements)) {
1141 foreach ($element->_elements as $child) {
1142 $childType = $child->getType();
1143 $methodName = 'getName';
1144 if ($childType) {
1145 $methodName = 'getValue';
1146 }
1147 if (in_array($child->{$methodName}(), $optIds) && $child->isFrozen()) {
1148 $resetSubmitted = TRUE;
1149 $child->setPersistantFreeze();
1150 }
1151 }
1152 }
1153 break;
1154
1155 case 'select':
1156 $value = $element->getValue();
1157 if (in_array($value[0], $optIds)) {
1158 foreach ($element->_options as $option) {
1159 if ($option['attr']['value'] === "crm_disabled_opt-{$value[0]}") {
1160 $placeholder = html_entity_decode($option['text'], ENT_QUOTES, "UTF-8");
1161 $element->updateAttributes(['placeholder' => $placeholder]);
1162 break;
1163 }
1164 }
1165 $resetSubmitted = TRUE;
1166 }
1167 break;
1168 }
1169
1170 //finally unset values from submitted.
1171 if ($resetSubmitted) {
1172 self::resetSubmittedValue($name, $optIds, $form);
1173 }
1174 }
1175 }
1176
1177 /**
1178 * Reset submitted value.
1179 *
1180 * @param string $elementName
1181 * @param array $optionIds
1182 * @param CRM_Core_Form $form
1183 */
1184 public static function resetSubmittedValue($elementName, $optionIds, &$form) {
1185 if (empty($elementName) ||
1186 !$form->elementExists($elementName) ||
1187 !$form->getSubmitValue($elementName)
1188 ) {
1189 return;
1190 }
1191 foreach (['constantValues', 'submitValues', 'defaultValues'] as $val) {
1192 $values = $form->{"_$val"};
1193 if (!is_array($values) || empty($values)) {
1194 continue;
1195 }
1196 $eleVal = $values[$elementName] ?? NULL;
1197 if (empty($eleVal)) {
1198 continue;
1199 }
1200 if (is_array($eleVal)) {
1201 $found = FALSE;
1202 foreach ($eleVal as $keyId => $ignore) {
1203 if (in_array($keyId, $optionIds)) {
1204 $found = TRUE;
1205 unset($values[$elementName][$keyId]);
1206 }
1207 }
1208 if ($found && empty($values[$elementName][$keyId])) {
1209 $values[$elementName][$keyId] = NULL;
1210 }
1211 }
1212 else {
1213 if (!empty($keyId)) {
1214 $values[$elementName][$keyId] = NULL;
1215 }
1216 }
1217 }
1218 }
1219
1220 /**
1221 * Validate price set submitted params for price option limit.
1222 *
1223 * User should select at least one price field option.
1224 *
1225 * @param CRM_Core_Form $form
1226 * @param array $params
1227 *
1228 * @return array
1229 */
1230 public static function validatePriceSet(&$form, $params) {
1231 $errors = [];
1232 $hasOptMaxValue = FALSE;
1233 if (!is_array($params) || empty($params)) {
1234 return $errors;
1235 }
1236
1237 $currentParticipantNum = substr($form->_name, 12);
1238 if (!$currentParticipantNum) {
1239 $currentParticipantNum = 0;
1240 }
1241
1242 $priceSetId = $form->get('priceSetId');
1243 $priceSetDetails = $form->get('priceSet');
1244 if (
1245 !$priceSetId ||
1246 !is_array($priceSetDetails) ||
1247 empty($priceSetDetails)
1248 ) {
1249 return $errors;
1250 }
1251
1252 $optionsCountDetails = $optionsMaxValueDetails = [];
1253 if (
1254 isset($priceSetDetails['optionsMaxValueTotal'])
1255 && $priceSetDetails['optionsMaxValueTotal']
1256 ) {
1257 $hasOptMaxValue = TRUE;
1258 $optionsMaxValueDetails = $priceSetDetails['optionsMaxValueDetails']['fields'];
1259 }
1260 if (
1261 isset($priceSetDetails['optionsCountTotal'])
1262 && $priceSetDetails['optionsCountTotal']
1263 ) {
1264 $hasOptCount = TRUE;
1265 $optionsCountDetails = $priceSetDetails['optionsCountDetails']['fields'];
1266 }
1267 $feeBlock = $form->_feeBlock;
1268
1269 if (empty($feeBlock)) {
1270 $feeBlock = $priceSetDetails['fields'];
1271 }
1272
1273 $optionMaxValues = $fieldSelected = [];
1274 foreach ($params as $pNum => $values) {
1275 if (!is_array($values) || $values == 'skip') {
1276 continue;
1277 }
1278
1279 foreach ($values as $valKey => $value) {
1280 if (strpos($valKey, 'price_') === FALSE) {
1281 continue;
1282 }
1283 $priceFieldId = substr($valKey, 6);
1284 $noneOptionValueSelected = FALSE;
1285 if (!$feeBlock[$priceFieldId]['is_required'] && $value == 0) {
1286 $noneOptionValueSelected = TRUE;
1287 }
1288
1289 if (
1290 !$priceFieldId ||
1291 (!$noneOptionValueSelected && !is_array($value))
1292 ) {
1293 continue;
1294 }
1295
1296 $fieldSelected[$pNum] = TRUE;
1297
1298 if (!$hasOptMaxValue || !is_array($value)) {
1299 continue;
1300 }
1301
1302 foreach ($value as $optId => $optVal) {
1303 if (CRM_Utils_Array::value('html_type', $feeBlock[$priceFieldId]) == 'Text') {
1304 $currentMaxValue = $optVal;
1305 }
1306 else {
1307 $currentMaxValue = 1;
1308 }
1309
1310 if (isset($optionsCountDetails[$priceFieldId]) && isset($optionsCountDetails[$priceFieldId]['options'][$optId])) {
1311 $currentMaxValue = $optionsCountDetails[$priceFieldId]['options'][$optId] * $optVal;
1312 }
1313 if (empty($optionMaxValues)) {
1314 $optionMaxValues[$priceFieldId][$optId] = $currentMaxValue;
1315 }
1316 else {
1317 $optionMaxValues[$priceFieldId][$optId]
1318 = $currentMaxValue + CRM_Utils_Array::value($optId, CRM_Utils_Array::value($priceFieldId, $optionMaxValues), 0);
1319 }
1320 $soldOutPnum[$optId] = $pNum;
1321 }
1322 }
1323
1324 //validate for price field selection.
1325 if (empty($fieldSelected[$pNum])) {
1326 $errors[$pNum]['_qf_default'] = ts('SELECT at least one OPTION FROM EVENT Fee(s).');
1327 }
1328 }
1329
1330 //validate for option max value.
1331 foreach ($optionMaxValues as $fieldId => $values) {
1332 $options = CRM_Utils_Array::value('options', $feeBlock[$fieldId], []);
1333 foreach ($values as $optId => $total) {
1334 $optMax = $optionsMaxValueDetails[$fieldId]['options'][$optId];
1335 $opDbCount = CRM_Utils_Array::value('db_total_count', $options[$optId], 0);
1336 $total += $opDbCount;
1337 if ($optMax && ($total > $optMax)) {
1338 if ($opDbCount && ($opDbCount >= $optMax)) {
1339 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1340 = ts('Sorry, this option is currently sold out.');
1341 }
1342 elseif (($optMax - $opDbCount) == 1) {
1343 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1344 = ts('Sorry, currently only a single space is available for this option.', [1 => ($optMax - $opDbCount)]);
1345 }
1346 else {
1347 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1348 = ts('Sorry, currently only %1 spaces are available for this option.', [1 => ($optMax - $opDbCount)]);
1349 }
1350 }
1351 }
1352 }
1353 return $errors;
1354 }
1355
1356 /**
1357 * Set the first participant ID if not set.
1358 *
1359 * CRM-10032.
1360 *
1361 * @param int $participantID
1362 */
1363 public function processFirstParticipant($participantID) {
1364 $this->_participantId = $participantID;
1365 $this->set('participantId', $this->_participantId);
1366
1367 $ids = $participantValues = [];
1368 $participantParams = ['id' => $this->_participantId];
1369 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
1370 $this->_values['participant'] = $participantValues[$this->_participantId];
1371 $this->set('values', $this->_values);
1372
1373 // also set the allow confirmation stuff
1374 if (array_key_exists(
1375 $this->_values['participant']['status_id'],
1376 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
1377 )) {
1378 $this->_allowConfirmation = TRUE;
1379 $this->set('allowConfirmation', TRUE);
1380 }
1381 }
1382
1383 /**
1384 * Check if event is valid.
1385 *
1386 * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
1387 * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
1388 * those belong in the form layer)
1389 *
1390 */
1391 protected function checkValidEvent(): void {
1392 // is the event active (enabled)?
1393 if (!$this->_values['event']['is_active']) {
1394 // form is inactive, die a fatal death
1395 CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
1396 }
1397
1398 // is online registration is enabled?
1399 if (!$this->_values['event']['is_online_registration']) {
1400 CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $this->getInfoPageUrl());
1401 }
1402
1403 // is this an event template ?
1404 if (!empty($this->_values['event']['is_template'])) {
1405 CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $this->getInfoPageUrl());
1406 }
1407
1408 $now = date('YmdHis');
1409 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date',
1410 $this->_values['event']
1411 ));
1412
1413 if (
1414 $startDate &&
1415 $startDate >= $now
1416 ) {
1417 CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', [1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event']))]), $this->getInfoPageUrl(), ts('Sorry'));
1418 }
1419
1420 $regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
1421 $this->_values['event']
1422 ));
1423 $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
1424 if (($regEndDate && ($regEndDate < $now)) || (empty($regEndDate) && !empty($eventEndDate) && ($eventEndDate < $now))) {
1425 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
1426 if (empty($regEndDate)) {
1427 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
1428 }
1429 CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', [1 => $endDate]), $this->getInfoPageUrl(), ts('Sorry'));
1430 }
1431 }
1432
1433 /**
1434 * Get the amount level for the event payment.
1435 *
1436 * The amount level is the string stored on the contribution record that describes the purchase.
1437 *
1438 * @param array $params
1439 * @param int|null $discountID
1440 *
1441 * @return string
1442 */
1443 protected function getAmountLevel($params, $discountID) {
1444 // @todo move handling of discount ID to the BAO function - preferably by converting it to a price_set with
1445 // time settings.
1446 if (!empty($this->_values['discount'][$discountID])) {
1447 return $this->_values['discount'][$discountID][$params['amount']]['label'];
1448 }
1449 if (empty($params['priceSetId'])) {
1450 // CRM-17509 An example of this is where the person is being waitlisted & there is no payment.
1451 // ideally we would have calculated amount first & only call this is there is an
1452 // amount but the flow needs more changes for that.
1453 return '';
1454 }
1455 return CRM_Price_BAO_PriceSet::getAmountLevelText($params);
1456 }
1457
1458 /**
1459 * Process Registration of free event.
1460 *
1461 * @param array $params
1462 * Form values.
1463 * @param int $contactID
1464 *
1465 * @throws \CiviCRM_API3_Exception
1466 */
1467 public function processRegistration($params, $contactID = NULL) {
1468 $session = CRM_Core_Session::singleton();
1469 $this->_participantInfo = [];
1470
1471 // CRM-4320, lets build array of cancelled additional participant ids
1472 // those are drop or skip by primary at the time of confirmation.
1473 // get all in and then unset those are confirmed.
1474 $cancelledIds = $this->_additionalParticipantIds;
1475
1476 $participantCount = [];
1477 foreach ($params as $participantNum => $record) {
1478 if ($record == 'skip') {
1479 $participantCount[$participantNum] = 'skip';
1480 }
1481 elseif ($participantNum) {
1482 $participantCount[$participantNum] = 'participant';
1483 }
1484 }
1485
1486 $registerByID = NULL;
1487 foreach ($params as $key => $value) {
1488 if ($value != 'skip') {
1489 $fields = NULL;
1490
1491 // setting register by Id and unset contactId.
1492 if (empty($value['is_primary'])) {
1493 $contactID = NULL;
1494 $registerByID = $this->get('registerByID');
1495 if ($registerByID) {
1496 $value['registered_by_id'] = $registerByID;
1497 }
1498 // get an email if one exists for the participant
1499 $participantEmail = '';
1500 foreach (array_keys($value) as $valueName) {
1501 if (substr($valueName, 0, 6) == 'email-') {
1502 $participantEmail = $value[$valueName];
1503 }
1504 }
1505 if ($participantEmail) {
1506 $this->_participantInfo[] = $participantEmail;
1507 }
1508 else {
1509 $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
1510 }
1511 }
1512 elseif (!empty($value['contact_id'])) {
1513 $contactID = $value['contact_id'];
1514 }
1515 else {
1516 $contactID = $this->getContactID();
1517 }
1518
1519 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
1520 //for free event or additional participant, dont create billing email address.
1521 if (empty($value['is_primary']) || !$this->_values['event']['is_monetary']) {
1522 unset($value["email-{$this->_bltID}"]);
1523 }
1524
1525 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
1526
1527 // lets store the contactID in the session
1528 // we dont store in userID in case the user is doing multiple
1529 // transactions etc
1530 // for things like tell a friend
1531 if (!$this->getContactID() && !empty($value['is_primary'])) {
1532 $session->set('transaction.userID', $contactID);
1533 }
1534
1535 //lets get the status if require approval or waiting.
1536
1537 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1538 if ($this->_allowWaitlist && !$this->_allowConfirmation) {
1539 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
1540 }
1541 elseif ($this->_requireApproval && !$this->_allowConfirmation) {
1542 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
1543 }
1544
1545 $this->set('value', $value);
1546 $this->confirmPostProcess($contactID, NULL);
1547
1548 //lets get additional participant id to cancel.
1549 if ($this->_allowConfirmation && is_array($cancelledIds)) {
1550 $additonalId = $value['participant_id'] ?? NULL;
1551 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
1552 unset($cancelledIds[$key]);
1553 }
1554 }
1555 }
1556 }
1557
1558 // update status and send mail to cancelled additional participants, CRM-4320
1559 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
1560 $cancelledId = array_search('Cancelled',
1561 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
1562 );
1563 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
1564 }
1565
1566 //set information about additional participants if exists
1567 if (count($this->_participantInfo)) {
1568 $this->set('participantInfo', $this->_participantInfo);
1569 }
1570
1571 //send mail Confirmation/Receipt
1572 if ($this->_contributeMode != 'checkout' ||
1573 $this->_contributeMode != 'notify'
1574 ) {
1575 $this->sendMails($params, $registerByID, $participantCount);
1576 }
1577 }
1578
1579 /**
1580 * Send Mail to participants.
1581 *
1582 * @param $params
1583 * @param $registerByID
1584 * @param array $participantCount
1585 *
1586 * @throws \CiviCRM_API3_Exception
1587 */
1588 private function sendMails($params, $registerByID, array $participantCount) {
1589 $isTest = FALSE;
1590 if ($this->_action & CRM_Core_Action::PREVIEW) {
1591 $isTest = TRUE;
1592 }
1593
1594 //handle if no additional participant.
1595 if (!$registerByID) {
1596 $registerByID = $this->get('registerByID');
1597 }
1598 $primaryContactId = $this->get('primaryContactId');
1599
1600 //build an array of custom profile and assigning it to template.
1601 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
1602 $primaryContactId, $isTest, TRUE
1603 );
1604
1605 //lets carry all participant params w/ values.
1606 foreach ($additionalIDs as $participantID => $contactId) {
1607 $participantNum = NULL;
1608 if ($participantID == $registerByID) {
1609 $participantNum = 0;
1610 }
1611 else {
1612 if ($participantNum = array_search('participant', $participantCount)) {
1613 unset($participantCount[$participantNum]);
1614 }
1615 }
1616
1617 if ($participantNum === NULL) {
1618 break;
1619 }
1620
1621 //carry the participant submitted values.
1622 $this->_values['params'][$participantID] = $params[$participantNum];
1623 }
1624
1625 //lets send mails to all with meanigful text, CRM-4320.
1626 $this->assign('isOnWaitlist', $this->_allowWaitlist);
1627 $this->assign('isRequireApproval', $this->_requireApproval);
1628
1629 foreach ($additionalIDs as $participantID => $contactId) {
1630 if ($participantID == $registerByID) {
1631 //set as Primary Participant
1632 $this->assign('isPrimary', 1);
1633
1634 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
1635
1636 if (count($customProfile)) {
1637 $this->assign('customProfile', $customProfile);
1638 $this->set('customProfile', $customProfile);
1639 }
1640 }
1641 else {
1642 $this->assign('isPrimary', 0);
1643 $this->assign('customProfile', NULL);
1644 }
1645
1646 //send Confirmation mail to Primary & additional Participants if exists
1647 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
1648 }
1649 }
1650
1651 /**
1652 * Get redirect URL to send folks back to event info page is registration not available.
1653 *
1654 * @return string
1655 */
1656 private function getInfoPageUrl(): string {
1657 return CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $this->getEventID(),
1658 FALSE, NULL, FALSE, TRUE
1659 );
1660 }
1661
1662 }