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