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