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