Merge pull request #16008 from civicrm/5.20
[civicrm-core.git] / CRM / Event / Form / Registration / Register.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17 /**
18 * This class generates form components for processing Event.
19 */
20 class CRM_Event_Form_Registration_Register extends CRM_Event_Form_Registration {
21
22 /**
23 * The fields involved in this page.
24 *
25 * @var array
26 */
27 public $_fields;
28
29 /**
30 * The status message that user view.
31 *
32 * @var string
33 */
34 protected $_waitlistMsg;
35 protected $_requireApprovalMsg;
36
37 /**
38 * Deprecated parameter that we hope to remove.
39 *
40 * @var bool
41 */
42 public $_quickConfig;
43
44 /**
45 * Skip duplicate check.
46 *
47 * This can be set using hook_civicrm_buildForm() to override the registration dupe check.
48 * CRM-7604
49 *
50 * @var bool
51 */
52 public $_skipDupeRegistrationCheck = FALSE;
53
54 public $_paymentProcessorID;
55
56 /**
57 * Show fee block or not.
58 *
59 * @var bool
60 */
61 public $_noFees;
62
63 /**
64 * Fee Block.
65 *
66 * @var array
67 */
68 public $_feeBlock;
69
70 /**
71 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields).
72 *
73 * This is rendered via billingBlock.tpl.
74 *
75 * @var array
76 */
77 public $_paymentFields = [];
78
79 /**
80 * Is this submission incurring no costs.
81 *
82 * @param array $fields
83 * @param \CRM_Event_Form_Registration_Register $form
84 *
85 * @return bool
86 */
87 protected static function isZeroAmount($fields, $form): bool {
88 $isZeroAmount = FALSE;
89 if (!empty($fields['priceSetId'])) {
90 if (empty($fields['amount'])) {
91 $isZeroAmount = TRUE;
92 }
93 }
94 elseif (!empty($fields['amount']) &&
95 (isset($form->_values['discount'][$fields['amount']])
96 && CRM_Utils_Array::value('value', $form->_values['discount'][$fields['amount']]) == 0
97 )
98 ) {
99 $isZeroAmount = TRUE;
100 }
101 elseif (!empty($fields['amount']) &&
102 (isset($form->_values['fee'][$fields['amount']])
103 && CRM_Utils_Array::value('value', $form->_values['fee'][$fields['amount']]) == 0
104 )
105 ) {
106 $isZeroAmount = TRUE;
107 }
108 return $isZeroAmount;
109 }
110
111 /**
112 * Get the contact id for the registration.
113 *
114 * @param array $fields
115 * @param CRM_Event_Form_Registration $form
116 * @param bool $isAdditional
117 *
118 * @return int|null
119 */
120 public static function getRegistrationContactID($fields, $form, $isAdditional) {
121 $contactID = NULL;
122 if (!$isAdditional) {
123 $contactID = $form->getContactID();
124 }
125 if (!$contactID && is_array($fields) && $fields) {
126 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $form->_values['event']), ['event_id' => CRM_Utils_Array::value('id', $form->_values['event'])]);
127 }
128 return $contactID;
129 }
130
131 /**
132 * Set variables up before form is built.
133 *
134 * @throws \CRM_Core_Exception
135 */
136 public function preProcess() {
137 parent::preProcess();
138
139 //CRM-4320.
140 //here we can't use parent $this->_allowWaitlist as user might
141 //walk back and we might set this value in this postProcess.
142 //(we set when spaces < group count and want to allow become part of waiting )
143 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
144
145 // Get payment processors if appropriate for this event
146 // We hide the payment fields if the event is full or requires approval,
147 // and the current user has not yet been approved CRM-12279
148 $this->_noFees = (($eventFull || $this->_requireApproval) && !$this->_allowConfirmation);
149 $this->_paymentProcessors = $this->_noFees ? [] : $this->get('paymentProcessors');
150 $this->preProcessPaymentOptions();
151
152 $this->_allowWaitlist = FALSE;
153 if ($eventFull && !$this->_allowConfirmation && !empty($this->_values['event']['has_waitlist'])) {
154 $this->_allowWaitlist = TRUE;
155 $this->_waitlistMsg = CRM_Utils_Array::value('waitlist_text', $this->_values['event']);
156 if (!$this->_waitlistMsg) {
157 $this->_waitlistMsg = ts('This event is currently full. However you can register now and get added to a waiting list. You will be notified if spaces become available.');
158 }
159 }
160 $this->set('allowWaitlist', $this->_allowWaitlist);
161
162 //To check if the user is already registered for the event(CRM-2426)
163 if (!$this->_skipDupeRegistrationCheck) {
164 self::checkRegistration(NULL, $this);
165 }
166
167 $this->assign('availableRegistrations', $this->_availableRegistrations);
168
169 // get the participant values from EventFees.php, CRM-4320
170 if ($this->_allowConfirmation) {
171 CRM_Event_Form_EventFees::preProcess($this);
172 }
173 }
174
175 /**
176 * Set default values for the form.
177 *
178 * @return array
179 *
180 * @throws \CRM_Core_Exception
181 * @throws \CiviCRM_API3_Exception
182 */
183 public function setDefaultValues() {
184 $this->_defaults = [];
185 if (!$this->_allowConfirmation && $this->_requireApproval) {
186 $this->_defaults['bypass_payment'] = 1;
187 }
188 $contactID = $this->getContactID();
189 CRM_Core_Payment_Form::setDefaultValues($this, $contactID);
190
191 CRM_Event_BAO_Participant::formatFieldsAndSetProfileDefaults($contactID, $this);
192
193 // Set default payment processor as default payment_processor radio button value
194 if (!empty($this->_paymentProcessors)) {
195 foreach ($this->_paymentProcessors as $pid => $value) {
196 if (!empty($value['is_default'])) {
197 $this->_defaults['payment_processor_id'] = $pid;
198 }
199 }
200 }
201
202 //if event is monetary and pay later is enabled and payment
203 //processor is not available then freeze the pay later checkbox with
204 //default check
205 if (!empty($this->_values['event']['is_pay_later']) &&
206 !is_array($this->_paymentProcessor)
207 ) {
208 $this->_defaults['is_pay_later'] = 1;
209 }
210
211 //set custom field defaults
212 if (!empty($this->_fields)) {
213 //load default campaign from page.
214 if (array_key_exists('participant_campaign_id', $this->_fields)) {
215 $this->_defaults['participant_campaign_id'] = CRM_Utils_Array::value('campaign_id',
216 $this->_values['event']
217 );
218 }
219
220 foreach ($this->_fields as $name => $field) {
221 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
222 // fix for CRM-1743
223 if (!isset($this->_defaults[$name])) {
224 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
225 NULL, CRM_Profile_Form::MODE_REGISTER
226 );
227 }
228 }
229 }
230 }
231
232 //fix for CRM-3088, default value for discount set.
233 $discountId = NULL;
234 if (!empty($this->_values['discount'])) {
235 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
236 if ($discountId) {
237 if (isset($this->_values['event']['default_discount_fee_id'])) {
238 $discountKey = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
239 $this->_values['event']['default_discount_fee_id'],
240 'weight', 'id'
241 );
242
243 $this->_defaults['amount'] = key(array_slice($this->_values['discount'][$discountId],
244 $discountKey - 1, $discountKey, TRUE
245 ));
246 }
247 }
248 }
249
250 // add this event's default participant role to defaults array
251 // (for cases where participant_role field is included in form via profile)
252 if ($this->_values['event']['default_role_id']) {
253 $this->_defaults['participant_role']
254 = $this->_defaults['participant_role_id'] = $this->_values['event']['default_role_id'];
255 }
256 if ($this->_priceSetId && !empty($this->_feeBlock)) {
257 foreach ($this->_feeBlock as $key => $val) {
258 if (empty($val['options'])) {
259 continue;
260 }
261 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, []);
262 foreach ($val['options'] as $keys => $values) {
263 if ($values['is_default'] && empty($values['is_full'])) {
264
265 if ($val['html_type'] == 'CheckBox') {
266 $this->_defaults["price_{$key}"][$keys] = 1;
267 }
268 else {
269 $this->_defaults["price_{$key}"] = $keys;
270 }
271 }
272 }
273 $unsetSubmittedOptions[$val['id']] = $optionFullIds;
274 }
275 //reset values for all options those are full.
276 CRM_Event_Form_Registration::resetElementValue($unsetSubmittedOptions, $this);
277 }
278
279 //set default participant fields, CRM-4320.
280 $hasAdditionalParticipants = FALSE;
281 if ($this->_allowConfirmation) {
282 $this->_contactId = $contactID;
283 $this->_discountId = $discountId;
284 $forcePayLater = CRM_Utils_Array::value('is_pay_later', $this->_defaults, FALSE);
285 $this->_defaults = array_merge($this->_defaults, CRM_Event_Form_EventFees::setDefaultValues($this));
286 $this->_defaults['is_pay_later'] = $forcePayLater;
287
288 if ($this->_additionalParticipantIds) {
289 $hasAdditionalParticipants = TRUE;
290 $this->_defaults['additional_participants'] = count($this->_additionalParticipantIds);
291 }
292 }
293 $this->assign('hasAdditionalParticipants', $hasAdditionalParticipants);
294
295 // //hack to simplify credit card entry for testing
296 // $this->_defaults['credit_card_type'] = 'Visa';
297 // $this->_defaults['credit_card_number'] = '4807731747657838';
298 // $this->_defaults['cvv2'] = '000';
299 // $this->_defaults['credit_card_exp_date'] = array( 'Y' => '2010', 'M' => '05' );
300
301 // to process Custom data that are appended to URL
302 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution', 'Participant'");
303 if (!empty($getDefaults)) {
304 $this->_defaults = array_merge($this->_defaults, $getDefaults);
305 }
306
307 return $this->_defaults;
308 }
309
310 /**
311 * Build the form object.
312 */
313 public function buildQuickForm() {
314 // build profiles first so that we can determine address fields etc
315 // and then show copy address checkbox
316 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
317 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
318
319 // CRM-18399: used by template to pass pre profile id as a url arg
320 $this->assign('custom_pre_id', $this->_values['custom_pre_id']);
321
322 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
323
324 $contactID = $this->getContactID();
325 if ($contactID) {
326 $this->assign('contact_id', $contactID);
327 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
328 }
329
330 $bypassPayment = $allowGroupOnWaitlist = $isAdditionalParticipants = FALSE;
331 if ($this->_values['event']['is_multiple_registrations']) {
332 // don't allow to add additional during confirmation if not preregistered.
333 if (!$this->_allowConfirmation || $this->_additionalParticipantIds) {
334 // CRM-17745: Make maximum additional participants configurable
335 // Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
336 $additionalOptions = [];
337 $additionalOptions[''] = 1;
338 for ($i = 1; $i <= $this->_values['event']['max_additional_participants']; $i++) {
339 $additionalOptions[$i] = $i + 1;
340 }
341 $this->add('select', 'additional_participants',
342 ts('How many people are you registering?'),
343 $additionalOptions,
344 NULL,
345 ['onChange' => "allowParticipant()"]
346 );
347 $isAdditionalParticipants = TRUE;
348 }
349 }
350
351 if (!$this->_allowConfirmation) {
352 $bypassPayment = TRUE;
353 }
354
355 //hack to allow group to register w/ waiting
356 if ((!empty($this->_values['event']['is_multiple_registrations']) ||
357 $this->_priceSetId
358 ) &&
359 !$this->_allowConfirmation &&
360 is_numeric($this->_availableRegistrations) && !empty($this->_values['event']['has_waitlist'])
361 ) {
362 $bypassPayment = TRUE;
363 //case might be group become as a part of waitlist.
364 //If not waitlist then they require admin approve.
365 $allowGroupOnWaitlist = TRUE;
366 $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", [1 => $this->_availableRegistrations]);
367
368 if ($this->_requireApproval) {
369 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
370 ts('Registration for this event requires approval. Once your registration(s) have been reviewed, you will receive an email with a link to a web page where you can complete the registration process.')
371 );
372 }
373 }
374
375 //case where only approval needed - no waitlist.
376 if ($this->_requireApproval &&
377 !$this->_allowWaitlist && !$bypassPayment
378 ) {
379 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
380 ts('Registration for this event requires approval. Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.')
381 );
382 }
383
384 //lets display status to primary page only.
385 $this->assign('waitlistMsg', $this->_waitlistMsg);
386 $this->assign('requireApprovalMsg', $this->_requireApprovalMsg);
387 $this->assign('allowGroupOnWaitlist', $allowGroupOnWaitlist);
388 $this->assign('isAdditionalParticipants', $isAdditionalParticipants);
389
390 if ($this->_values['event']['is_monetary']) {
391 self::buildAmount($this);
392 }
393
394 $pps = $this->getProcessors();
395 if ($this->getContactID() === 0 && !$this->_values['event']['is_multiple_registrations']) {
396 //@todo we are blocking for multiple registrations because we haven't tested
397 $this->addCIDZeroOptions();
398 }
399
400 if ($this->_values['event']['is_monetary']) {
401 if (count($pps) > 1) {
402 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
403 NULL, "&nbsp;"
404 );
405 }
406 elseif (!empty($pps)) {
407 $ppKeys = array_keys($pps);
408 $currentPP = array_pop($ppKeys);
409 $this->addElement('hidden', 'payment_processor_id', $currentPP);
410 }
411 }
412
413 $this->addElement('hidden', 'bypass_payment', NULL, ['id' => 'bypass_payment']);
414
415 $this->assign('bypassPayment', $bypassPayment);
416
417 $userID = $this->getContactID();
418
419 if (!$userID) {
420 $createCMSUser = FALSE;
421
422 if ($this->_values['custom_pre_id']) {
423 $profileID = $this->_values['custom_pre_id'];
424 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
425 }
426
427 if (!$createCMSUser &&
428 $this->_values['custom_post_id']
429 ) {
430 if (!is_array($this->_values['custom_post_id'])) {
431 $profileIDs = [$this->_values['custom_post_id']];
432 }
433 else {
434 $profileIDs = $this->_values['custom_post_id'];
435 }
436 foreach ($profileIDs as $pid) {
437 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
438 $profileID = $pid;
439 $createCMSUser = TRUE;
440 break;
441 }
442 }
443 }
444
445 if ($createCMSUser) {
446 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
447 }
448 }
449
450 //we have to load confirm contribution button in template
451 //when multiple payment processor as the user
452 //can toggle with payment processor selection
453 $billingModePaymentProcessors = 0;
454 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
455 foreach ($this->_paymentProcessors as $key => $values) {
456 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
457 $billingModePaymentProcessors++;
458 }
459 }
460 }
461
462 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
463 $allAreBillingModeProcessors = TRUE;
464 }
465 else {
466 $allAreBillingModeProcessors = FALSE;
467 }
468
469 if (!$allAreBillingModeProcessors || !empty($this->_values['event']['is_pay_later']) || $bypassPayment
470 ) {
471
472 //freeze button to avoid multiple calls.
473 if (empty($this->_values['event']['is_monetary'])) {
474 $this->submitOnce = TRUE;
475 }
476
477 // CRM-11182 - Optional confirmation screen
478 // Change button label depending on whether the next action is confirm or register
479 if (
480 !$this->_values['event']['is_multiple_registrations']
481 && !$this->_values['event']['is_monetary']
482 && !$this->_values['event']['is_confirm_enabled']
483 ) {
484 $buttonLabel = ts('Register');
485 }
486 else {
487 $buttonLabel = ts('Continue');
488 }
489
490 $this->addButtons([
491 [
492 'type' => 'upload',
493 'name' => $buttonLabel,
494 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
495 'isDefault' => TRUE,
496 ],
497 ]);
498 }
499
500 $this->addFormRule(['CRM_Event_Form_Registration_Register', 'formRule'], $this);
501 $this->unsavedChangesWarn = TRUE;
502
503 // add pcp fields
504 if ($this->_pcpId) {
505 CRM_PCP_BAO_PCP::buildPcp($this->_pcpId, $this);
506 }
507 }
508
509 /**
510 * Build the radio/text form elements for the amount field
511 *
512 * @param CRM_Event_Form_Registration_Register $form
513 * Form object.
514 * @param bool $required
515 * True if you want to add formRule.
516 * @param int $discountId
517 * Discount id for the event.
518 *
519 * @throws \CRM_Core_Exception
520 */
521 public static function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
522 // build amount only when needed, skip incase of event full and waitlisting is enabled
523 // and few other conditions check preProcess()
524 if (property_exists($form, '_noFees') && $form->_noFees) {
525 return;
526 }
527
528 //if payment done, no need to build the fee block.
529 if (!empty($form->_paymentId)) {
530 //fix to display line item in update mode.
531 $form->assign('priceSet', isset($form->_priceSet) ? $form->_priceSet : NULL);
532 return;
533 }
534
535 $feeFields = CRM_Utils_Array::value('fee', $form->_values);
536
537 if (is_array($feeFields)) {
538 $form->_feeBlock = &$form->_values['fee'];
539 }
540
541 //check for discount.
542 $discountedFee = CRM_Utils_Array::value('discount', $form->_values);
543 if (is_array($discountedFee) && !empty($discountedFee)) {
544 if (!$discountId) {
545 $form->_discountId = $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
546 }
547 if ($discountId) {
548 $form->_feeBlock = &$form->_values['discount'][$discountId];
549 }
550 }
551 if (!is_array($form->_feeBlock)) {
552 $form->_feeBlock = [];
553 }
554
555 //its time to call the hook.
556 CRM_Utils_Hook::buildAmount('event', $form, $form->_feeBlock);
557
558 //reset required if participant is skipped.
559 $button = substr($form->controller->getButtonName(), -4);
560 if ($required && $button == 'skip') {
561 $required = FALSE;
562 }
563
564 $className = CRM_Utils_System::getClassName($form);
565
566 //build the priceset fields.
567 if (isset($form->_priceSetId) && $form->_priceSetId) {
568
569 //format price set fields across option full.
570 self::formatFieldsForOptionFull($form);
571
572 if (!empty($form->_priceSet['is_quick_config'])) {
573 $form->_quickConfig = $form->_priceSet['is_quick_config'];
574 }
575 $form->add('hidden', 'priceSetId', $form->_priceSetId);
576
577 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
578 $adminFieldVisible = FALSE;
579 if (CRM_Core_Permission::check('administer CiviCRM')) {
580 $adminFieldVisible = TRUE;
581 }
582
583 $hideAdminValues = TRUE;
584 if (CRM_Core_Permission::check('edit event participants')) {
585 $hideAdminValues = FALSE;
586 }
587
588 foreach ($form->_feeBlock as $field) {
589 // public AND admin visibility fields are included for back-office registration and back-office change selections
590 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
591 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
592 $className == 'CRM_Event_Form_Participant' ||
593 $className == 'CRM_Event_Form_ParticipantFeeSelection'
594 ) {
595 $fieldId = $field['id'];
596 $elementName = 'price_' . $fieldId;
597
598 $isRequire = CRM_Utils_Array::value('is_required', $field);
599 if ($button == 'skip') {
600 $isRequire = FALSE;
601 }
602
603 //user might modified w/ hook.
604 $options = CRM_Utils_Array::value('options', $field);
605 $formClasses = ['CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection'];
606
607 if (!is_array($options)) {
608 continue;
609 }
610 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
611 $publicVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('public');
612 $adminVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('admin');
613
614 foreach ($options as $key => $currentOption) {
615 $optionVisibility = CRM_Utils_Array::value('visibility_id', $currentOption, $publicVisibilityID);
616 if ($optionVisibility == $adminVisibilityID) {
617 unset($options[$key]);
618 }
619 }
620 }
621
622 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, []);
623
624 //soft suppress required rule when option is full.
625 if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
626 $isRequire = FALSE;
627 }
628 if (!empty($options)) {
629 //build the element.
630 CRM_Price_BAO_PriceField::addQuickFormElement($form,
631 $elementName,
632 $fieldId,
633 FALSE,
634 $isRequire,
635 NULL,
636 $options,
637 $optionFullIds
638 );
639 }
640 }
641 }
642 $form->assign('priceSet', $form->_priceSet);
643 }
644 else {
645 $eventFeeBlockValues = [];
646 foreach ($form->_feeBlock as $fee) {
647 if (is_array($fee)) {
648
649 //CRM-7632, CRM-6201
650 $totalAmountJs = NULL;
651 if ($className == 'CRM_Event_Form_Participant') {
652 $totalAmountJs = ['onClick' => "fillTotalAmount(" . $fee['value'] . ")"];
653 }
654
655 $eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
656 $elements[] = &$form->createElement('radio', NULL, '',
657 CRM_Utils_Money::format($fee['value']) . ' ' .
658 $fee['label'],
659 $fee['amount_id'],
660 $totalAmountJs
661 );
662 }
663 }
664 $form->assign('eventFeeBlockValues', json_encode($eventFeeBlockValues));
665
666 $form->_defaults['amount'] = CRM_Utils_Array::value('default_fee_id', $form->_values['event']);
667 $element = &$form->addGroup($elements, 'amount', ts('Event Fee(s)'), '<br />');
668 if (isset($form->_online) && $form->_online) {
669 $element->freeze();
670 }
671 if ($required) {
672 $form->addRule('amount', ts('Fee Level is a required field.'), 'required');
673 }
674 }
675 }
676
677 /**
678 * @param CRM_Event_Form_Registration $form
679 */
680 public static function formatFieldsForOptionFull(&$form) {
681 $priceSet = $form->get('priceSet');
682 $priceSetId = $form->get('priceSetId');
683 $defaultPricefieldIds = [];
684 if (!empty($form->_values['line_items'])) {
685 foreach ($form->_values['line_items'] as $lineItem) {
686 $defaultPricefieldIds[] = $lineItem['price_field_value_id'];
687 }
688 }
689 if (!$priceSetId ||
690 !is_array($priceSet) ||
691 empty($priceSet) || empty($priceSet['optionsMaxValueTotal'])
692 ) {
693 return;
694 }
695
696 $skipParticipants = $formattedPriceSetDefaults = [];
697 if (!empty($form->_allowConfirmation) && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
698 $participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
699 $pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
700 $form->_eventId
701 );
702 // modify options full to respect the selected fields
703 // options on confirmation.
704 $formattedPriceSetDefaults = self::formatPriceSetParams($form, $pricesetDefaults);
705
706 // to skip current registered participants fields option count on confirmation.
707 $skipParticipants[] = $form->_participantId;
708 if (!empty($form->_additionalParticipantIds)) {
709 $skipParticipants = array_merge($skipParticipants, $form->_additionalParticipantIds);
710 }
711 }
712
713 $className = CRM_Utils_System::getClassName($form);
714
715 //get the current price event price set options count.
716 $currentOptionsCount = self::getPriceSetOptionCount($form);
717 $recordedOptionsCount = CRM_Event_BAO_Participant::priceSetOptionsCount($form->_eventId, $skipParticipants);
718 $optionFullTotalAmount = 0;
719 $currentParticipantNo = (int) substr($form->_name, 12);
720 foreach ($form->_feeBlock as & $field) {
721 $optionFullIds = [];
722 $fieldId = $field['id'];
723 if (!is_array($field['options'])) {
724 continue;
725 }
726 foreach ($field['options'] as & $option) {
727 $optId = $option['id'];
728 $count = CRM_Utils_Array::value('count', $option, 0);
729 $maxValue = CRM_Utils_Array::value('max_value', $option, 0);
730 $dbTotalCount = CRM_Utils_Array::value($optId, $recordedOptionsCount, 0);
731 $currentTotalCount = CRM_Utils_Array::value($optId, $currentOptionsCount, 0);
732
733 $totalCount = $currentTotalCount + $dbTotalCount;
734 $isFull = FALSE;
735 if ($maxValue &&
736 (($totalCount >= $maxValue) &&
737 (empty($form->_lineItem[$currentParticipantNo][$optId]['price_field_id']) || $dbTotalCount >= $maxValue))
738 ) {
739 $isFull = TRUE;
740 $optionFullIds[$optId] = $optId;
741 if ($field['html_type'] != 'Select') {
742 if (in_array($optId, $defaultPricefieldIds)) {
743 $optionFullTotalAmount += CRM_Utils_Array::value('amount', $option);
744 }
745 }
746 else {
747 if (!empty($defaultPricefieldIds) && in_array($optId, $defaultPricefieldIds)) {
748 unset($optionFullIds[$optId]);
749 }
750 }
751 }
752 //here option is not full,
753 //but we don't want to allow participant to increase
754 //seats at the time of re-walking registration.
755 if ($count &&
756 !empty($form->_allowConfirmation) &&
757 !empty($formattedPriceSetDefaults)
758 ) {
759 if (empty($formattedPriceSetDefaults["price_{$field}"]) || empty($formattedPriceSetDefaults["price_{$fieldId}"][$optId])) {
760 $optionFullIds[$optId] = $optId;
761 $isFull = TRUE;
762 }
763 }
764 $option['is_full'] = $isFull;
765 $option['db_total_count'] = $dbTotalCount;
766 $option['total_option_count'] = $dbTotalCount + $currentTotalCount;
767 }
768
769 //ignore option full for offline registration.
770 if ($className == 'CRM_Event_Form_Participant') {
771 $optionFullIds = [];
772 }
773
774 //finally get option ids in.
775 $field['option_full_ids'] = $optionFullIds;
776 }
777 $form->assign('optionFullTotalAmount', $optionFullTotalAmount);
778 }
779
780 /**
781 * Global form rule.
782 *
783 * @param array $fields
784 * The input form values.
785 * @param array $files
786 * The uploaded files if any.
787 * @param \CRM_Event_Form_Registration_Register $form
788 *
789 * @return bool|array
790 * true if no errors, else array of errors
791 *
792 * @throws \CRM_Core_Exception
793 */
794 public static function formRule($fields, $files, $form) {
795 $errors = [];
796 //check that either an email or firstname+lastname is included in the form(CRM-9587)
797 self::checkProfileComplete($fields, $errors, $form->_eventId);
798 //To check if the user is already registered for the event(CRM-2426)
799 if (!$form->_skipDupeRegistrationCheck) {
800 self::checkRegistration($fields, $form);
801 }
802 //check for availability of registrations.
803 if (!$form->_allowConfirmation && empty($fields['bypass_payment']) &&
804 is_numeric($form->_availableRegistrations) &&
805 CRM_Utils_Array::value('additional_participants', $fields) >= $form->_availableRegistrations
806 ) {
807 $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", [1 => $form->_availableRegistrations]);
808 }
809
810 // during confirmation don't allow to increase additional participants, CRM-4320
811 if ($form->_allowConfirmation && !empty($fields['additional_participants']) &&
812 is_array($form->_additionalParticipantIds) &&
813 $fields['additional_participants'] > count($form->_additionalParticipantIds)
814 ) {
815 $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", [1 => count($form->_additionalParticipantIds)]);
816 }
817
818 //don't allow to register w/ waiting if enough spaces available.
819 if (!empty($fields['bypass_payment']) && $form->_allowConfirmation) {
820 if (!is_numeric($form->_availableRegistrations) ||
821 (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $form->_availableRegistrations)
822 ) {
823 $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
824 }
825 }
826
827 if (!empty($fields['additional_participants']) &&
828 !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])
829 ) {
830 $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
831 }
832
833 // priceset validations
834 if (!empty($fields['priceSetId']) &&
835 !$form->_requireApproval && !$form->_allowWaitlist
836 ) {
837 //format params.
838 $formatted = self::formatPriceSetParams($form, $fields);
839 $ppParams = [$formatted];
840 $priceSetErrors = self::validatePriceSet($form, $ppParams);
841 $primaryParticipantCount = self::getParticipantCount($form, $ppParams);
842
843 //get price set fields errors in.
844 $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, []));
845
846 $totalParticipants = $primaryParticipantCount;
847 if (!empty($fields['additional_participants'])) {
848 $totalParticipants += $fields['additional_participants'];
849 }
850
851 if (empty($fields['bypass_payment']) &&
852 !$form->_allowConfirmation &&
853 is_numeric($form->_availableRegistrations) &&
854 $form->_availableRegistrations < $totalParticipants
855 ) {
856 $errors['_qf_default'] = ts("Only %1 Registrations available.", [1 => $form->_availableRegistrations]);
857 }
858
859 $lineItem = [];
860 CRM_Price_BAO_PriceSet::processAmount($form->_values['fee'], $fields, $lineItem);
861
862 $minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
863 if ($fields['amount'] < 0) {
864 $errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
865 }
866 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
867 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', [
868 1 => CRM_Utils_Money::format($minAmt),
869 ]);
870 }
871 }
872 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
873 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
874 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
875 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
876 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
877 [1 => ucwords(str_replace('_', ' ', $greeting))]
878 );
879 }
880 }
881 }
882
883 // @todo - can we remove the 'is_monetary' concept?
884 if ($form->_values['event']['is_monetary']) {
885 if (empty($form->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
886 !isset($fields['payment_processor_id'])) {
887 $errors['payment_processor_id'] = ts('Please select a Payment Method');
888 }
889
890 if (self::isZeroAmount($fields, $form)) {
891 return empty($errors) ? TRUE : $errors;
892 }
893
894 // also return if zero fees for valid members
895 if (!empty($fields['bypass_payment']) ||
896 (!$form->_allowConfirmation && ($form->_requireApproval || $form->_allowWaitlist))
897 ) {
898 return empty($errors) ? TRUE : $errors;
899 }
900 CRM_Core_Payment_Form::validatePaymentInstrument(
901 $fields['payment_processor_id'],
902 $fields,
903 $errors,
904 (!$form->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
905 );
906 }
907
908 return empty($errors) ? TRUE : $errors;
909 }
910
911 /**
912 * Check if profiles are complete when event registration occurs(CRM-9587).
913 *
914 * @param array $fields
915 * @param array $errors
916 * @param int $eventId
917 */
918 public static function checkProfileComplete($fields, &$errors, $eventId) {
919 $email = '';
920 foreach ($fields as $fieldname => $fieldvalue) {
921 if (substr($fieldname, 0, 6) == 'email-' && $fieldvalue) {
922 $email = $fieldvalue;
923 }
924 }
925
926 if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
927 $defaults = $params = ['id' => $eventId];
928 CRM_Event_BAO_Event::retrieve($params, $defaults);
929 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
930 $errors['_qf_default'] = $message;
931 }
932 }
933
934 /**
935 * Process the form submission.
936 */
937 public function postProcess() {
938 // get the submitted form values.
939 $params = $this->controller->exportValues($this->_name);
940
941 //set as Primary participant
942 $params['is_primary'] = 1;
943
944 if ($this->_values['event']['is_pay_later']
945 && (!array_key_exists('hidden_processor', $params) || $params['payment_processor_id'] == 0)
946 ) {
947 $params['is_pay_later'] = 1;
948 }
949 else {
950 $params['is_pay_later'] = 0;
951 }
952
953 $this->set('is_pay_later', $params['is_pay_later']);
954
955 // assign pay later stuff
956 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
957 $this->assign('is_pay_later', $params['is_pay_later']);
958 if ($params['is_pay_later']) {
959 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
960 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
961 }
962
963 if (!$this->_allowConfirmation) {
964 // check if the participant is already registered
965 if (!$this->_skipDupeRegistrationCheck) {
966 $params['contact_id'] = self::getRegistrationContactID($params, $this, FALSE);
967 }
968 }
969
970 if (!empty($params['image_URL'])) {
971 CRM_Contact_BAO_Contact::processImageParams($params);
972 }
973
974 //carry campaign to partcipants.
975 if (array_key_exists('participant_campaign_id', $params)) {
976 $params['campaign_id'] = $params['participant_campaign_id'];
977 }
978 else {
979 $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
980 }
981
982 //hack to allow group to register w/ waiting
983 $primaryParticipantCount = self::getParticipantCount($this, $params);
984
985 $totalParticipants = $primaryParticipantCount;
986 if (!empty($params['additional_participants'])) {
987 $totalParticipants += $params['additional_participants'];
988 }
989 if (!$this->_allowConfirmation && !empty($params['bypass_payment']) &&
990 is_numeric($this->_availableRegistrations) &&
991 $totalParticipants > $this->_availableRegistrations
992 ) {
993 $this->_allowWaitlist = TRUE;
994 $this->set('allowWaitlist', TRUE);
995 }
996
997 //carry participant id if pre-registered.
998 if ($this->_allowConfirmation && $this->_participantId) {
999 $params['participant_id'] = $this->_participantId;
1000 }
1001
1002 $params['defaultRole'] = 1;
1003 if (array_key_exists('participant_role', $params)) {
1004 $params['participant_role_id'] = $params['participant_role'];
1005 }
1006
1007 if (array_key_exists('participant_role_id', $params)) {
1008 $params['defaultRole'] = 0;
1009 }
1010 if (empty($params['participant_role_id']) &&
1011 $this->_values['event']['default_role_id']
1012 ) {
1013 $params['participant_role_id'] = $this->_values['event']['default_role_id'];
1014 }
1015
1016 $config = CRM_Core_Config::singleton();
1017 $params['currencyID'] = $config->defaultCurrency;
1018
1019 if ($this->_values['event']['is_monetary']) {
1020 // we first reset the confirm page so it accepts new values
1021 $this->controller->resetPage('Confirm');
1022
1023 //added for discount
1024 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
1025 $params['amount_level'] = $this->getAmountLevel($params, $discountId);
1026 if (!empty($this->_values['discount'][$discountId])) {
1027 $params['discount_id'] = $discountId;
1028 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
1029 }
1030 elseif (empty($params['priceSetId'])) {
1031 if (!empty($params['amount'])) {
1032 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
1033 }
1034 else {
1035 $params['amount'] = '';
1036 }
1037 }
1038 else {
1039 $lineItem = [];
1040 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
1041 if ($params['tax_amount']) {
1042 $this->set('tax_amount', $params['tax_amount']);
1043 }
1044 $submittedLineItems = $this->get('lineItem');
1045 if (!empty($submittedLineItems) && is_array($submittedLineItems)) {
1046 $submittedLineItems[0] = $lineItem;
1047 }
1048 else {
1049 $submittedLineItems = [$lineItem];
1050 }
1051 $submittedLineItems = array_filter($submittedLineItems);
1052 $this->set('lineItem', $submittedLineItems);
1053 $this->set('lineItemParticipantsCount', [$primaryParticipantCount]);
1054 }
1055
1056 $this->set('amount', $params['amount']);
1057 $this->set('amount_level', $params['amount_level']);
1058
1059 // generate and set an invoiceID for this transaction
1060 $invoiceID = md5(uniqid(rand(), TRUE));
1061 $this->set('invoiceID', $invoiceID);
1062
1063 if ($this->_paymentProcessor) {
1064 $payment = $this->_paymentProcessor['object'];
1065 $payment->setBaseReturnUrl('civicrm/event/register');
1066 }
1067
1068 // ContributeMode is a deprecated concept. It is short-hand for a bunch of
1069 // assumptions we are working to remove.
1070 $this->set('contributeMode', 'direct');
1071
1072 // This code is duplicated multiple places and should be consolidated.
1073 $params = $this->prepareParamsForPaymentProcessor($params);
1074
1075 if ($this->_values['event']['is_monetary']) {
1076 $params['currencyID'] = $config->defaultCurrency;
1077 $params['invoiceID'] = $invoiceID;
1078 }
1079 $this->_params = $this->get('params');
1080 // Set the button so we know what
1081 $params['button'] = $this->controller->getButtonName();
1082 if (!empty($this->_params) && is_array($this->_params)) {
1083 $this->_params[0] = $params;
1084 }
1085 else {
1086 $this->_params = [];
1087 $this->_params[] = $params;
1088 }
1089 $this->set('params', $this->_params);
1090 if ($this->_paymentProcessor &&
1091 // Actually we don't really need to check if it supports pre-approval - we could just call
1092 // it regardless as the function we call re-acts tot the rests of the preApproval call.
1093 $this->_paymentProcessor['object']->supports('preApproval')
1094 && !$this->_allowWaitlist &&
1095 !$this->_requireApproval
1096 ) {
1097
1098 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1099 $this->set('contributeMode', 'express');
1100
1101 // Send Event Name & Id in Params
1102 $params['eventName'] = $this->_values['event']['title'];
1103 $params['eventId'] = $this->_values['event']['id'];
1104
1105 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register',
1106 "_qf_Register_display=1&qfKey={$this->controller->_key}",
1107 TRUE, NULL, FALSE
1108 );
1109 if (!empty($params['additional_participants'])) {
1110 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
1111 }
1112 else {
1113 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
1114 }
1115 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register',
1116 $urlArgs,
1117 TRUE, NULL, FALSE
1118 );
1119 $params['invoiceID'] = $invoiceID;
1120
1121 $params['component'] = 'event';
1122 $this->handlePreApproval($params);
1123 }
1124 elseif ($this->_paymentProcessor &&
1125 (int) $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
1126 ) {
1127 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1128 $this->set('contributeMode', 'notify');
1129 }
1130 }
1131 else {
1132 $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
1133
1134 $this->_params = [];
1135 $this->_params[] = $params;
1136 $this->set('params', $this->_params);
1137
1138 if (
1139 empty($params['additional_participants'])
1140 // CRM-11182 - Optional confirmation screen
1141 && !$this->_values['event']['is_confirm_enabled']
1142 ) {
1143 $this->processRegistration($this->_params);
1144 }
1145 }
1146
1147 // If registering > 1 participant, give status message
1148 if (!empty($params['additional_participants'])) {
1149 $statusMsg = ts('Registration information for participant 1 has been saved.');
1150 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1151 }
1152 }
1153
1154 /**
1155 * Method to check if the user is already registered for the event.
1156 * and if result found redirect to the event info page
1157 *
1158 * @param array $fields
1159 * The input form values(anonymous user).
1160 * @param CRM_Event_Form_Registration_Register $form
1161 * Event data.
1162 * @param bool $isAdditional
1163 * Treat isAdditional participants a bit differently.
1164 *
1165 * @return int
1166 */
1167 public static function checkRegistration($fields, $form, $isAdditional = FALSE) {
1168 // CRM-3907, skip check for preview registrations
1169 // CRM-4320 participant need to walk wizard
1170 if (
1171 ($form->_mode == 'test' || $form->_allowConfirmation)
1172 ) {
1173 return FALSE;
1174 }
1175
1176 $contactID = self::getRegistrationContactID($fields, $form, $isAdditional);
1177
1178 if ($contactID) {
1179 $participant = new CRM_Event_BAO_Participant();
1180 $participant->contact_id = $contactID;
1181 $participant->event_id = $form->_values['event']['id'];
1182 if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
1183 $participant->role_id = $fields['participant_role'];
1184 }
1185 else {
1186 $participant->role_id = $form->_values['event']['default_role_id'];
1187 }
1188 $participant->is_test = 0;
1189 $participant->find();
1190 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1191 while ($participant->fetch()) {
1192 if (array_key_exists($participant->status_id, $statusTypes)) {
1193 if (!$isAdditional && !$form->_values['event']['allow_same_participant_emails']) {
1194 $registerUrl = CRM_Utils_System::url('civicrm/event/register',
1195 "reset=1&id={$form->_values['event']['id']}&cid=0"
1196 );
1197 if ($form->_pcpId) {
1198 $registerUrl .= '&pcpId=' . $form->_pcpId;
1199 }
1200
1201 $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', [1 => $registerUrl]);
1202 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
1203 $url = CRM_Utils_System::url('civicrm/event/info',
1204 "reset=1&id={$form->_values['event']['id']}&noFullMsg=true"
1205 );
1206 if ($form->_action & CRM_Core_Action::PREVIEW) {
1207 $url .= '&action=preview';
1208 }
1209
1210 if ($form->_pcpId) {
1211 $url .= '&pcpId=' . $form->_pcpId;
1212 }
1213
1214 CRM_Utils_System::redirect($url);
1215 }
1216
1217 if ($isAdditional) {
1218 $status = ts("It looks like this participant is already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.");
1219 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
1220 return $participant->id;
1221 }
1222 }
1223 }
1224 }
1225 }
1226
1227 }