3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
30 * @copyright CiviCRM LLC (c) 2004-2019
34 * This class generates form components for processing Event.
36 class CRM_Event_Form_Registration_Register
extends CRM_Event_Form_Registration
{
39 * The fields involved in this page.
46 * The status message that user view.
50 protected $_waitlistMsg;
51 protected $_requireApprovalMsg;
54 * Deprecated parameter that we hope to remove.
61 * Skip duplicate check.
63 * This can be set using hook_civicrm_buildForm() to override the registration dupe check.
68 public $_skipDupeRegistrationCheck = FALSE;
70 public $_paymentProcessorID;
73 * Show fee block or not.
87 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields).
89 * This is rendered via billingBlock.tpl.
93 public $_paymentFields = [];
96 * Is this submission incurring no costs.
98 * @param array $fields
99 * @param \CRM_Event_Form_Registration_Register $form
103 protected static function isZeroAmount($fields, $form): bool {
104 $isZeroAmount = FALSE;
105 if (!empty($fields['priceSetId'])) {
106 if (empty($fields['amount'])) {
107 $isZeroAmount = TRUE;
110 elseif (!empty($fields['amount']) &&
111 (isset($form->_values
['discount'][$fields['amount']])
112 && CRM_Utils_Array
::value('value', $form->_values
['discount'][$fields['amount']]) == 0
115 $isZeroAmount = TRUE;
117 elseif (!empty($fields['amount']) &&
118 (isset($form->_values
['fee'][$fields['amount']])
119 && CRM_Utils_Array
::value('value', $form->_values
['fee'][$fields['amount']]) == 0
122 $isZeroAmount = TRUE;
124 return $isZeroAmount;
128 * Get the contact id for the registration.
130 * @param array $fields
131 * @param CRM_Event_Form_Registration $form
132 * @param bool $isAdditional
136 public static function getRegistrationContactID($fields, $form, $isAdditional) {
138 if (!$isAdditional) {
139 $contactID = $form->getContactID();
141 if (!$contactID && is_array($fields) && $fields) {
142 $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'])]);
148 * Set variables up before form is built.
150 * @throws \CRM_Core_Exception
152 public function preProcess() {
153 parent
::preProcess();
156 //here we can't use parent $this->_allowWaitlist as user might
157 //walk back and we might set this value in this postProcess.
158 //(we set when spaces < group count and want to allow become part of waiting )
159 $eventFull = CRM_Event_BAO_Participant
::eventFull($this->_eventId
, FALSE, CRM_Utils_Array
::value('has_waitlist', $this->_values
['event']));
161 // Get payment processors if appropriate for this event
162 // We hide the payment fields if the event is full or requires approval,
163 // and the current user has not yet been approved CRM-12279
164 $this->_noFees
= (($eventFull ||
$this->_requireApproval
) && !$this->_allowConfirmation
);
165 $this->_paymentProcessors
= $this->_noFees ?
[] : $this->get('paymentProcessors');
166 $this->preProcessPaymentOptions();
168 $this->_allowWaitlist
= FALSE;
169 if ($eventFull && !$this->_allowConfirmation
&& !empty($this->_values
['event']['has_waitlist'])) {
170 $this->_allowWaitlist
= TRUE;
171 $this->_waitlistMsg
= CRM_Utils_Array
::value('waitlist_text', $this->_values
['event']);
172 if (!$this->_waitlistMsg
) {
173 $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.');
176 $this->set('allowWaitlist', $this->_allowWaitlist
);
178 //To check if the user is already registered for the event(CRM-2426)
179 if (!$this->_skipDupeRegistrationCheck
) {
180 self
::checkRegistration(NULL, $this);
183 $this->assign('availableRegistrations', $this->_availableRegistrations
);
185 // get the participant values from EventFees.php, CRM-4320
186 if ($this->_allowConfirmation
) {
187 CRM_Event_Form_EventFees
::preProcess($this);
192 * Set default values for the form.
196 * @throws \CRM_Core_Exception
197 * @throws \CiviCRM_API3_Exception
199 public function setDefaultValues() {
200 $this->_defaults
= [];
201 if (!$this->_allowConfirmation
&& $this->_requireApproval
) {
202 $this->_defaults
['bypass_payment'] = 1;
204 $contactID = $this->getContactID();
205 CRM_Core_Payment_Form
::setDefaultValues($this, $contactID);
207 CRM_Event_BAO_Participant
::formatFieldsAndSetProfileDefaults($contactID, $this);
209 // Set default payment processor as default payment_processor radio button value
210 if (!empty($this->_paymentProcessors
)) {
211 foreach ($this->_paymentProcessors
as $pid => $value) {
212 if (!empty($value['is_default'])) {
213 $this->_defaults
['payment_processor_id'] = $pid;
218 //if event is monetary and pay later is enabled and payment
219 //processor is not available then freeze the pay later checkbox with
221 if (!empty($this->_values
['event']['is_pay_later']) &&
222 !is_array($this->_paymentProcessor
)
224 $this->_defaults
['is_pay_later'] = 1;
227 //set custom field defaults
228 if (!empty($this->_fields
)) {
229 //load default campaign from page.
230 if (array_key_exists('participant_campaign_id', $this->_fields
)) {
231 $this->_defaults
['participant_campaign_id'] = CRM_Utils_Array
::value('campaign_id',
232 $this->_values
['event']
236 foreach ($this->_fields
as $name => $field) {
237 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
239 if (!isset($this->_defaults
[$name])) {
240 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID, $name, $this->_defaults
,
241 NULL, CRM_Profile_Form
::MODE_REGISTER
248 //fix for CRM-3088, default value for discount set.
250 if (!empty($this->_values
['discount'])) {
251 $discountId = CRM_Core_BAO_Discount
::findSet($this->_eventId
, 'civicrm_event');
253 if (isset($this->_values
['event']['default_discount_fee_id'])) {
254 $discountKey = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
255 $this->_values
['event']['default_discount_fee_id'],
259 $this->_defaults
['amount'] = key(array_slice($this->_values
['discount'][$discountId],
260 $discountKey - 1, $discountKey, TRUE
266 // add this event's default participant role to defaults array
267 // (for cases where participant_role field is included in form via profile)
268 if ($this->_values
['event']['default_role_id']) {
269 $this->_defaults
['participant_role']
270 = $this->_defaults
['participant_role_id'] = $this->_values
['event']['default_role_id'];
272 if ($this->_priceSetId
&& !empty($this->_feeBlock
)) {
273 foreach ($this->_feeBlock
as $key => $val) {
274 if (empty($val['options'])) {
277 $optionFullIds = CRM_Utils_Array
::value('option_full_ids', $val, []);
278 foreach ($val['options'] as $keys => $values) {
279 if ($values['is_default'] && empty($values['is_full'])) {
281 if ($val['html_type'] == 'CheckBox') {
282 $this->_defaults
["price_{$key}"][$keys] = 1;
285 $this->_defaults
["price_{$key}"] = $keys;
289 $unsetSubmittedOptions[$val['id']] = $optionFullIds;
291 //reset values for all options those are full.
292 CRM_Event_Form_Registration
::resetElementValue($unsetSubmittedOptions, $this);
295 //set default participant fields, CRM-4320.
296 $hasAdditionalParticipants = FALSE;
297 if ($this->_allowConfirmation
) {
298 $this->_contactId
= $contactID;
299 $this->_discountId
= $discountId;
300 $forcePayLater = CRM_Utils_Array
::value('is_pay_later', $this->_defaults
, FALSE);
301 $this->_defaults
= array_merge($this->_defaults
, CRM_Event_Form_EventFees
::setDefaultValues($this));
302 $this->_defaults
['is_pay_later'] = $forcePayLater;
304 if ($this->_additionalParticipantIds
) {
305 $hasAdditionalParticipants = TRUE;
306 $this->_defaults
['additional_participants'] = count($this->_additionalParticipantIds
);
309 $this->assign('hasAdditionalParticipants', $hasAdditionalParticipants);
311 // //hack to simplify credit card entry for testing
312 // $this->_defaults['credit_card_type'] = 'Visa';
313 // $this->_defaults['credit_card_number'] = '4807731747657838';
314 // $this->_defaults['cvv2'] = '000';
315 // $this->_defaults['credit_card_exp_date'] = array( 'Y' => '2010', 'M' => '05' );
317 // to process Custom data that are appended to URL
318 $getDefaults = CRM_Core_BAO_CustomGroup
::extractGetParams($this, "'Contact', 'Individual', 'Contribution', 'Participant'");
319 if (!empty($getDefaults)) {
320 $this->_defaults
= array_merge($this->_defaults
, $getDefaults);
323 return $this->_defaults
;
327 * Build the form object.
329 public function buildQuickForm() {
330 // build profiles first so that we can determine address fields etc
331 // and then show copy address checkbox
332 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre');
333 $this->buildCustom($this->_values
['custom_post_id'], 'customPost');
335 // CRM-18399: used by template to pass pre profile id as a url arg
336 $this->assign('custom_pre_id', $this->_values
['custom_pre_id']);
338 CRM_Core_Payment_ProcessorForm
::buildQuickForm($this);
340 $contactID = $this->getContactID();
342 $this->assign('contact_id', $contactID);
343 $this->assign('display_name', CRM_Contact_BAO_Contact
::displayName($contactID));
346 $this->add('hidden', 'scriptFee', NULL);
347 $this->add('hidden', 'scriptArray', NULL);
349 $bypassPayment = $allowGroupOnWaitlist = $isAdditionalParticipants = FALSE;
350 if ($this->_values
['event']['is_multiple_registrations']) {
351 // don't allow to add additional during confirmation if not preregistered.
352 if (!$this->_allowConfirmation ||
$this->_additionalParticipantIds
) {
353 // CRM-17745: Make maximum additional participants configurable
354 // Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
355 $additionalOptions = [];
356 $additionalOptions[''] = 1;
357 for ($i = 1; $i <= $this->_values
['event']['max_additional_participants']; $i++
) {
358 $additionalOptions[$i] = $i +
1;
360 $this->add('select', 'additional_participants',
361 ts('How many people are you registering?'),
364 ['onChange' => "allowParticipant()"]
366 $isAdditionalParticipants = TRUE;
370 if (!$this->_allowConfirmation
) {
371 $bypassPayment = TRUE;
374 //hack to allow group to register w/ waiting
375 if ((!empty($this->_values
['event']['is_multiple_registrations']) ||
378 !$this->_allowConfirmation
&&
379 is_numeric($this->_availableRegistrations
) && !empty($this->_values
['event']['has_waitlist'])
381 $bypassPayment = TRUE;
382 //case might be group become as a part of waitlist.
383 //If not waitlist then they require admin approve.
384 $allowGroupOnWaitlist = TRUE;
385 $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
]);
387 if ($this->_requireApproval
) {
388 $this->_requireApprovalMsg
= CRM_Utils_Array
::value('approval_req_text', $this->_values
['event'],
389 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.')
394 //case where only approval needed - no waitlist.
395 if ($this->_requireApproval
&&
396 !$this->_allowWaitlist
&& !$bypassPayment
398 $this->_requireApprovalMsg
= CRM_Utils_Array
::value('approval_req_text', $this->_values
['event'],
399 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.')
403 //lets display status to primary page only.
404 $this->assign('waitlistMsg', $this->_waitlistMsg
);
405 $this->assign('requireApprovalMsg', $this->_requireApprovalMsg
);
406 $this->assign('allowGroupOnWaitlist', $allowGroupOnWaitlist);
407 $this->assign('isAdditionalParticipants', $isAdditionalParticipants);
409 if ($this->_values
['event']['is_monetary']) {
410 self
::buildAmount($this);
414 //@todo this processor adding fn is another one duplicated on contribute - a shared
415 // common class would make this sort of thing extractable
416 $onlinePaymentProcessorEnabled = FALSE;
417 if (!empty($this->_paymentProcessors
)) {
418 foreach ($this->_paymentProcessors
as $key => $name) {
419 if ($name['billing_mode'] == 1) {
420 $onlinePaymentProcessorEnabled = TRUE;
422 $pps[$key] = $name['name'];
425 if ($this->getContactID() === 0 && !$this->_values
['event']['is_multiple_registrations']) {
426 //@todo we are blocking for multiple registrations because we haven't tested
427 $this->addCIDZeroOptions($onlinePaymentProcessorEnabled);
429 if (!empty($this->_values
['event']['is_pay_later']) &&
430 ($this->_allowConfirmation ||
(!$this->_requireApproval
&& !$this->_allowWaitlist
))
432 $pps[0] = $this->_values
['event']['pay_later_text'];
435 if ($this->_values
['event']['is_monetary']) {
436 if (count($pps) > 1) {
437 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
441 elseif (!empty($pps)) {
442 $ppKeys = array_keys($pps);
443 $currentPP = array_pop($ppKeys);
444 $this->addElement('hidden', 'payment_processor_id', $currentPP);
448 $this->addElement('hidden', 'bypass_payment', NULL, ['id' => 'bypass_payment']);
450 $this->assign('bypassPayment', $bypassPayment);
452 $userID = $this->getContactID();
455 $createCMSUser = FALSE;
457 if ($this->_values
['custom_pre_id']) {
458 $profileID = $this->_values
['custom_pre_id'];
459 $createCMSUser = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
462 if (!$createCMSUser &&
463 $this->_values
['custom_post_id']
465 if (!is_array($this->_values
['custom_post_id'])) {
466 $profileIDs = [$this->_values
['custom_post_id']];
469 $profileIDs = $this->_values
['custom_post_id'];
471 foreach ($profileIDs as $pid) {
472 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
474 $createCMSUser = TRUE;
480 if ($createCMSUser) {
481 CRM_Core_BAO_CMSUser
::buildForm($this, $profileID, TRUE);
485 //we have to load confirm contribution button in template
486 //when multiple payment processor as the user
487 //can toggle with payment processor selection
488 $billingModePaymentProcessors = 0;
489 if (!CRM_Utils_System
::isNull($this->_paymentProcessors
)) {
490 foreach ($this->_paymentProcessors
as $key => $values) {
491 if ($values['billing_mode'] == CRM_Core_Payment
::BILLING_MODE_BUTTON
) {
492 $billingModePaymentProcessors++
;
497 if ($billingModePaymentProcessors && count($this->_paymentProcessors
) == $billingModePaymentProcessors) {
498 $allAreBillingModeProcessors = TRUE;
501 $allAreBillingModeProcessors = FALSE;
504 if (!$allAreBillingModeProcessors ||
!empty($this->_values
['event']['is_pay_later']) ||
$bypassPayment
507 //freeze button to avoid multiple calls.
508 if (empty($this->_values
['event']['is_monetary'])) {
509 $this->submitOnce
= TRUE;
512 // CRM-11182 - Optional confirmation screen
513 // Change button label depending on whether the next action is confirm or register
515 !$this->_values
['event']['is_multiple_registrations']
516 && !$this->_values
['event']['is_monetary']
517 && !$this->_values
['event']['is_confirm_enabled']
519 $buttonLabel = ts('Register');
522 $buttonLabel = ts('Continue');
528 'name' => $buttonLabel,
529 'spacing' => ' ',
535 $this->addFormRule(['CRM_Event_Form_Registration_Register', 'formRule'], $this);
536 $this->unsavedChangesWarn
= TRUE;
540 CRM_PCP_BAO_PCP
::buildPcp($this->_pcpId
, $this);
545 * Build the radio/text form elements for the amount field
547 * @param CRM_Event_Form_Registration_Register $form
549 * @param bool $required
550 * True if you want to add formRule.
551 * @param int $discountId
552 * Discount id for the event.
554 * @throws \CRM_Core_Exception
556 public static function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
557 // build amount only when needed, skip incase of event full and waitlisting is enabled
558 // and few other conditions check preProcess()
559 if (property_exists($form, '_noFees') && $form->_noFees
) {
563 //if payment done, no need to build the fee block.
564 if (!empty($form->_paymentId
)) {
565 //fix to display line item in update mode.
566 $form->assign('priceSet', isset($form->_priceSet
) ?
$form->_priceSet
: NULL);
570 $feeFields = CRM_Utils_Array
::value('fee', $form->_values
);
572 if (is_array($feeFields)) {
573 $form->_feeBlock
= &$form->_values
['fee'];
576 //check for discount.
577 $discountedFee = CRM_Utils_Array
::value('discount', $form->_values
);
578 if (is_array($discountedFee) && !empty($discountedFee)) {
580 $form->_discountId
= $discountId = CRM_Core_BAO_Discount
::findSet($form->_eventId
, 'civicrm_event');
583 $form->_feeBlock
= &$form->_values
['discount'][$discountId];
586 if (!is_array($form->_feeBlock
)) {
587 $form->_feeBlock
= [];
590 //its time to call the hook.
591 CRM_Utils_Hook
::buildAmount('event', $form, $form->_feeBlock
);
593 //reset required if participant is skipped.
594 $button = substr($form->controller
->getButtonName(), -4);
595 if ($required && $button == 'skip') {
599 $className = CRM_Utils_System
::getClassName($form);
601 //build the priceset fields.
602 if (isset($form->_priceSetId
) && $form->_priceSetId
) {
604 //format price set fields across option full.
605 self
::formatFieldsForOptionFull($form);
607 if (!empty($form->_priceSet
['is_quick_config'])) {
608 $form->_quickConfig
= $form->_priceSet
['is_quick_config'];
610 $form->add('hidden', 'priceSetId', $form->_priceSetId
);
612 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
613 $adminFieldVisible = FALSE;
614 if (CRM_Core_Permission
::check('administer CiviCRM')) {
615 $adminFieldVisible = TRUE;
618 $hideAdminValues = TRUE;
619 if (CRM_Core_Permission
::check('edit event participants')) {
620 $hideAdminValues = FALSE;
623 foreach ($form->_feeBlock
as $field) {
624 // public AND admin visibility fields are included for back-office registration and back-office change selections
625 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
626 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
627 $className == 'CRM_Event_Form_Participant' ||
628 $className == 'CRM_Event_Form_ParticipantFeeSelection'
630 $fieldId = $field['id'];
631 $elementName = 'price_' . $fieldId;
633 $isRequire = CRM_Utils_Array
::value('is_required', $field);
634 if ($button == 'skip') {
638 //user might modified w/ hook.
639 $options = CRM_Utils_Array
::value('options', $field);
640 $formClasses = ['CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection'];
642 if (!is_array($options)) {
645 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
646 $publicVisibilityID = CRM_Price_BAO_PriceField
::getVisibilityOptionID('public');
647 $adminVisibilityID = CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin');
649 foreach ($options as $key => $currentOption) {
650 $optionVisibility = CRM_Utils_Array
::value('visibility_id', $currentOption, $publicVisibilityID);
651 if ($optionVisibility == $adminVisibilityID) {
652 unset($options[$key]);
657 $optionFullIds = CRM_Utils_Array
::value('option_full_ids', $field, []);
659 //soft suppress required rule when option is full.
660 if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
663 if (!empty($options)) {
665 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
677 $form->assign('priceSet', $form->_priceSet
);
680 $eventFeeBlockValues = [];
681 foreach ($form->_feeBlock
as $fee) {
682 if (is_array($fee)) {
685 $totalAmountJs = NULL;
686 if ($className == 'CRM_Event_Form_Participant') {
687 $totalAmountJs = ['onClick' => "fillTotalAmount(" . $fee['value'] . ")"];
690 $eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
691 $elements[] = &$form->createElement('radio', NULL, '',
692 CRM_Utils_Money
::format($fee['value']) . ' ' .
699 $form->assign('eventFeeBlockValues', json_encode($eventFeeBlockValues));
701 $form->_defaults
['amount'] = CRM_Utils_Array
::value('default_fee_id', $form->_values
['event']);
702 $element = &$form->addGroup($elements, 'amount', ts('Event Fee(s)'), '<br />');
703 if (isset($form->_online
) && $form->_online
) {
707 $form->addRule('amount', ts('Fee Level is a required field.'), 'required');
713 * @param CRM_Event_Form_Registration $form
715 public static function formatFieldsForOptionFull(&$form) {
716 $priceSet = $form->get('priceSet');
717 $priceSetId = $form->get('priceSetId');
718 $defaultPricefieldIds = [];
719 if (!empty($form->_values
['line_items'])) {
720 foreach ($form->_values
['line_items'] as $lineItem) {
721 $defaultPricefieldIds[] = $lineItem['price_field_value_id'];
725 !is_array($priceSet) ||
726 empty($priceSet) ||
empty($priceSet['optionsMaxValueTotal'])
731 $skipParticipants = $formattedPriceSetDefaults = [];
732 if (!empty($form->_allowConfirmation
) && (isset($form->_pId
) ||
isset($form->_additionalParticipantId
))) {
733 $participantId = isset($form->_pId
) ?
$form->_pId
: $form->_additionalParticipantId
;
734 $pricesetDefaults = CRM_Event_Form_EventFees
::setDefaultPriceSet($participantId,
737 // modify options full to respect the selected fields
738 // options on confirmation.
739 $formattedPriceSetDefaults = self
::formatPriceSetParams($form, $pricesetDefaults);
741 // to skip current registered participants fields option count on confirmation.
742 $skipParticipants[] = $form->_participantId
;
743 if (!empty($form->_additionalParticipantIds
)) {
744 $skipParticipants = array_merge($skipParticipants, $form->_additionalParticipantIds
);
748 $className = CRM_Utils_System
::getClassName($form);
750 //get the current price event price set options count.
751 $currentOptionsCount = self
::getPriceSetOptionCount($form);
752 $recordedOptionsCount = CRM_Event_BAO_Participant
::priceSetOptionsCount($form->_eventId
, $skipParticipants);
753 $optionFullTotalAmount = 0;
754 $currentParticipantNo = (int) substr($form->_name
, 12);
755 foreach ($form->_feeBlock
as & $field) {
757 $fieldId = $field['id'];
758 if (!is_array($field['options'])) {
761 foreach ($field['options'] as & $option) {
762 $optId = $option['id'];
763 $count = CRM_Utils_Array
::value('count', $option, 0);
764 $maxValue = CRM_Utils_Array
::value('max_value', $option, 0);
765 $dbTotalCount = CRM_Utils_Array
::value($optId, $recordedOptionsCount, 0);
766 $currentTotalCount = CRM_Utils_Array
::value($optId, $currentOptionsCount, 0);
768 $totalCount = $currentTotalCount +
$dbTotalCount;
771 (($totalCount >= $maxValue) &&
772 (empty($form->_lineItem
[$currentParticipantNo][$optId]['price_field_id']) ||
$dbTotalCount >= $maxValue))
775 $optionFullIds[$optId] = $optId;
776 if ($field['html_type'] != 'Select') {
777 if (in_array($optId, $defaultPricefieldIds)) {
778 $optionFullTotalAmount +
= CRM_Utils_Array
::value('amount', $option);
782 if (!empty($defaultPricefieldIds) && in_array($optId, $defaultPricefieldIds)) {
783 unset($optionFullIds[$optId]);
787 //here option is not full,
788 //but we don't want to allow participant to increase
789 //seats at the time of re-walking registration.
791 !empty($form->_allowConfirmation
) &&
792 !empty($formattedPriceSetDefaults)
794 if (empty($formattedPriceSetDefaults["price_{$field}"]) ||
empty($formattedPriceSetDefaults["price_{$fieldId}"][$optId])) {
795 $optionFullIds[$optId] = $optId;
799 $option['is_full'] = $isFull;
800 $option['db_total_count'] = $dbTotalCount;
801 $option['total_option_count'] = $dbTotalCount +
$currentTotalCount;
804 //ignore option full for offline registration.
805 if ($className == 'CRM_Event_Form_Participant') {
809 //finally get option ids in.
810 $field['option_full_ids'] = $optionFullIds;
812 $form->assign('optionFullTotalAmount', $optionFullTotalAmount);
818 * @param array $fields
819 * The input form values.
820 * @param array $files
821 * The uploaded files if any.
822 * @param \CRM_Event_Form_Registration_Register $form
825 * true if no errors, else array of errors
827 * @throws \CRM_Core_Exception
829 public static function formRule($fields, $files, $form) {
831 //check that either an email or firstname+lastname is included in the form(CRM-9587)
832 self
::checkProfileComplete($fields, $errors, $form->_eventId
);
833 //To check if the user is already registered for the event(CRM-2426)
834 if (!$form->_skipDupeRegistrationCheck
) {
835 self
::checkRegistration($fields, $form);
837 //check for availability of registrations.
838 if (!$form->_allowConfirmation
&& empty($fields['bypass_payment']) &&
839 is_numeric($form->_availableRegistrations
) &&
840 CRM_Utils_Array
::value('additional_participants', $fields) >= $form->_availableRegistrations
842 $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", [1 => $form->_availableRegistrations
]);
845 // during confirmation don't allow to increase additional participants, CRM-4320
846 if ($form->_allowConfirmation
&& !empty($fields['additional_participants']) &&
847 is_array($form->_additionalParticipantIds
) &&
848 $fields['additional_participants'] > count($form->_additionalParticipantIds
)
850 $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
)]);
853 //don't allow to register w/ waiting if enough spaces available.
854 if (!empty($fields['bypass_payment']) && $form->_allowConfirmation
) {
855 if (!is_numeric($form->_availableRegistrations
) ||
856 (empty($fields['priceSetId']) && CRM_Utils_Array
::value('additional_participants', $fields) < $form->_availableRegistrations
)
858 $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
862 if (!empty($fields['additional_participants']) &&
863 !CRM_Utils_Rule
::positiveInteger($fields['additional_participants'])
865 $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
868 // priceset validations
869 if (!empty($fields['priceSetId']) &&
870 !$form->_requireApproval
&& !$form->_allowWaitlist
873 $formatted = self
::formatPriceSetParams($form, $fields);
874 $ppParams = [$formatted];
875 $priceSetErrors = self
::validatePriceSet($form, $ppParams);
876 $primaryParticipantCount = self
::getParticipantCount($form, $ppParams);
878 //get price set fields errors in.
879 $errors = array_merge($errors, CRM_Utils_Array
::value(0, $priceSetErrors, []));
881 $totalParticipants = $primaryParticipantCount;
882 if (!empty($fields['additional_participants'])) {
883 $totalParticipants +
= $fields['additional_participants'];
886 if (empty($fields['bypass_payment']) &&
887 !$form->_allowConfirmation
&&
888 is_numeric($form->_availableRegistrations
) &&
889 $form->_availableRegistrations
< $totalParticipants
891 $errors['_qf_default'] = ts("Only %1 Registrations available.", [1 => $form->_availableRegistrations
]);
895 CRM_Price_BAO_PriceSet
::processAmount($form->_values
['fee'], $fields, $lineItem);
897 $minAmt = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
898 if ($fields['amount'] < 0) {
899 $errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
901 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
902 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', [
903 1 => CRM_Utils_Money
::format($minAmt),
908 // @todo - can we remove the 'is_monetary' concept?
909 if ($form->_values
['event']['is_monetary']) {
910 if (empty($form->_requireApproval
) && !empty($fields['amount']) && $fields['amount'] > 0 &&
911 !isset($fields['payment_processor_id'])) {
912 $errors['payment_processor_id'] = ts('Please select a Payment Method');
915 if (self
::isZeroAmount($fields, $form)) {
916 return empty($errors) ?
TRUE : $errors;
919 // also return if zero fees for valid members
920 if (!empty($fields['bypass_payment']) ||
921 (!$form->_allowConfirmation
&& ($form->_requireApproval ||
$form->_allowWaitlist
))
923 return empty($errors) ?
TRUE : $errors;
925 CRM_Core_Payment_Form
::validatePaymentInstrument(
926 $fields['payment_processor_id'],
929 (!$form->_isBillingAddressRequiredForPayLater ?
NULL : 'billing')
933 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
934 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
935 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
936 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
937 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
938 [1 => ucwords(str_replace('_', ' ', $greeting))]
943 return empty($errors) ?
TRUE : $errors;
947 * Check if profiles are complete when event registration occurs(CRM-9587).
949 * @param array $fields
950 * @param array $errors
951 * @param int $eventId
953 public static function checkProfileComplete($fields, &$errors, $eventId) {
955 foreach ($fields as $fieldname => $fieldvalue) {
956 if (substr($fieldname, 0, 6) == 'email-' && $fieldvalue) {
957 $email = $fieldvalue;
961 if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
962 $defaults = $params = ['id' => $eventId];
963 CRM_Event_BAO_Event
::retrieve($params, $defaults);
964 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
965 $errors['_qf_default'] = $message;
970 * Process the form submission.
972 public function postProcess() {
973 // get the submitted form values.
974 $params = $this->controller
->exportValues($this->_name
);
976 //set as Primary participant
977 $params['is_primary'] = 1;
979 if ($this->_values
['event']['is_pay_later']
980 && (!array_key_exists('hidden_processor', $params) ||
$params['payment_processor_id'] == 0)
982 $params['is_pay_later'] = 1;
985 $params['is_pay_later'] = 0;
988 $this->set('is_pay_later', $params['is_pay_later']);
990 // assign pay later stuff
991 $this->_params
['is_pay_later'] = CRM_Utils_Array
::value('is_pay_later', $params, FALSE);
992 $this->assign('is_pay_later', $params['is_pay_later']);
993 if ($params['is_pay_later']) {
994 $this->assign('pay_later_text', $this->_values
['event']['pay_later_text']);
995 $this->assign('pay_later_receipt', $this->_values
['event']['pay_later_receipt']);
998 if (!$this->_allowConfirmation
) {
999 // check if the participant is already registered
1000 if (!$this->_skipDupeRegistrationCheck
) {
1001 $params['contact_id'] = self
::getRegistrationContactID($params, $this, FALSE);
1005 if (!empty($params['image_URL'])) {
1006 CRM_Contact_BAO_Contact
::processImageParams($params);
1009 //carry campaign to partcipants.
1010 if (array_key_exists('participant_campaign_id', $params)) {
1011 $params['campaign_id'] = $params['participant_campaign_id'];
1014 $params['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
['event']);
1017 //hack to allow group to register w/ waiting
1018 $primaryParticipantCount = self
::getParticipantCount($this, $params);
1020 $totalParticipants = $primaryParticipantCount;
1021 if (!empty($params['additional_participants'])) {
1022 $totalParticipants +
= $params['additional_participants'];
1024 if (!$this->_allowConfirmation
&& !empty($params['bypass_payment']) &&
1025 is_numeric($this->_availableRegistrations
) &&
1026 $totalParticipants > $this->_availableRegistrations
1028 $this->_allowWaitlist
= TRUE;
1029 $this->set('allowWaitlist', TRUE);
1032 //carry participant id if pre-registered.
1033 if ($this->_allowConfirmation
&& $this->_participantId
) {
1034 $params['participant_id'] = $this->_participantId
;
1037 $params['defaultRole'] = 1;
1038 if (array_key_exists('participant_role', $params)) {
1039 $params['participant_role_id'] = $params['participant_role'];
1042 if (array_key_exists('participant_role_id', $params)) {
1043 $params['defaultRole'] = 0;
1045 if (empty($params['participant_role_id']) &&
1046 $this->_values
['event']['default_role_id']
1048 $params['participant_role_id'] = $this->_values
['event']['default_role_id'];
1051 $config = CRM_Core_Config
::singleton();
1052 $params['currencyID'] = $config->defaultCurrency
;
1054 if ($this->_values
['event']['is_monetary']) {
1055 // we first reset the confirm page so it accepts new values
1056 $this->controller
->resetPage('Confirm');
1058 //added for discount
1059 $discountId = CRM_Core_BAO_Discount
::findSet($this->_eventId
, 'civicrm_event');
1060 $params['amount_level'] = $this->getAmountLevel($params, $discountId);
1061 if (!empty($this->_values
['discount'][$discountId])) {
1062 $params['discount_id'] = $discountId;
1063 $params['amount'] = $this->_values
['discount'][$discountId][$params['amount']]['value'];
1065 elseif (empty($params['priceSetId'])) {
1066 if (!empty($params['amount'])) {
1067 $params['amount'] = $this->_values
['fee'][$params['amount']]['value'];
1070 $params['amount'] = '';
1075 CRM_Price_BAO_PriceSet
::processAmount($this->_values
['fee'], $params, $lineItem);
1076 if ($params['tax_amount']) {
1077 $this->set('tax_amount', $params['tax_amount']);
1079 $submittedLineItems = $this->get('lineItem');
1080 if (!empty($submittedLineItems) && is_array($submittedLineItems)) {
1081 $submittedLineItems[0] = $lineItem;
1084 $submittedLineItems = [$lineItem];
1086 $submittedLineItems = array_filter($submittedLineItems);
1087 $this->set('lineItem', $submittedLineItems);
1088 $this->set('lineItemParticipantsCount', [$primaryParticipantCount]);
1091 $this->set('amount', $params['amount']);
1092 $this->set('amount_level', $params['amount_level']);
1094 // generate and set an invoiceID for this transaction
1095 $invoiceID = md5(uniqid(rand(), TRUE));
1096 $this->set('invoiceID', $invoiceID);
1098 if ($this->_paymentProcessor
) {
1099 $payment = $this->_paymentProcessor
['object'];
1100 $payment->setBaseReturnUrl('civicrm/event/register');
1103 // ContributeMode is a deprecated concept. It is short-hand for a bunch of
1104 // assumptions we are working to remove.
1105 $this->set('contributeMode', 'direct');
1107 // This code is duplicated multiple places and should be consolidated.
1108 $params = $this->prepareParamsForPaymentProcessor($params);
1110 if ($this->_values
['event']['is_monetary']) {
1111 $params['currencyID'] = $config->defaultCurrency
;
1112 $params['invoiceID'] = $invoiceID;
1114 $this->_params
= $this->get('params');
1115 // Set the button so we know what
1116 $params['button'] = $this->controller
->getButtonName();
1117 if (!empty($this->_params
) && is_array($this->_params
)) {
1118 $this->_params
[0] = $params;
1121 $this->_params
= [];
1122 $this->_params
[] = $params;
1124 $this->set('params', $this->_params
);
1125 if ($this->_paymentProcessor
&&
1126 // Actually we don't really need to check if it supports pre-approval - we could just call
1127 // it regardless as the function we call re-acts tot the rests of the preApproval call.
1128 $this->_paymentProcessor
['object']->supports('preApproval')
1129 && !$this->_allowWaitlist
&&
1130 !$this->_requireApproval
1133 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1134 $this->set('contributeMode', 'express');
1136 // Send Event Name & Id in Params
1137 $params['eventName'] = $this->_values
['event']['title'];
1138 $params['eventId'] = $this->_values
['event']['id'];
1140 $params['cancelURL'] = CRM_Utils_System
::url('civicrm/event/register',
1141 "_qf_Register_display=1&qfKey={$this->controller->_key}",
1144 if (!empty($params['additional_participants'])) {
1145 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
1148 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
1150 $params['returnURL'] = CRM_Utils_System
::url('civicrm/event/register',
1154 $params['invoiceID'] = $invoiceID;
1156 $params['component'] = 'event';
1157 $this->handlePreApproval($params);
1159 elseif ($this->_paymentProcessor
&&
1160 (int) $this->_paymentProcessor
['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_NOTIFY
1162 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1163 $this->set('contributeMode', 'notify');
1167 $params['description'] = ts('Online Event Registration') . ' ' . $this->_values
['event']['title'];
1169 $this->_params
= [];
1170 $this->_params
[] = $params;
1171 $this->set('params', $this->_params
);
1174 empty($params['additional_participants'])
1175 // CRM-11182 - Optional confirmation screen
1176 && !$this->_values
['event']['is_confirm_enabled']
1178 $this->processRegistration($this->_params
);
1182 // If registering > 1 participant, give status message
1183 if (!empty($params['additional_participants'])) {
1184 $statusMsg = ts('Registration information for participant 1 has been saved.');
1185 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1190 * Method to check if the user is already registered for the event.
1191 * and if result found redirect to the event info page
1193 * @param array $fields
1194 * The input form values(anonymous user).
1195 * @param CRM_Event_Form_Registration_Register $form
1197 * @param bool $isAdditional
1198 * Treat isAdditional participants a bit differently.
1202 public static function checkRegistration($fields, $form, $isAdditional = FALSE) {
1203 // CRM-3907, skip check for preview registrations
1204 // CRM-4320 participant need to walk wizard
1206 ($form->_mode
== 'test' ||
$form->_allowConfirmation
)
1211 $contactID = self
::getRegistrationContactID($fields, $form, $isAdditional);
1214 $participant = new CRM_Event_BAO_Participant();
1215 $participant->contact_id
= $contactID;
1216 $participant->event_id
= $form->_values
['event']['id'];
1217 if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
1218 $participant->role_id
= $fields['participant_role'];
1221 $participant->role_id
= $form->_values
['event']['default_role_id'];
1223 $participant->is_test
= 0;
1224 $participant->find();
1225 $statusTypes = CRM_Event_PseudoConstant
::participantStatus(NULL, 'is_counted = 1');
1226 while ($participant->fetch()) {
1227 if (array_key_exists($participant->status_id
, $statusTypes)) {
1228 if (!$isAdditional && !$form->_values
['event']['allow_same_participant_emails']) {
1229 $registerUrl = CRM_Utils_System
::url('civicrm/event/register',
1230 "reset=1&id={$form->_values['event']['id']}&cid=0"
1232 if ($form->_pcpId
) {
1233 $registerUrl .= '&pcpId=' . $form->_pcpId
;
1236 $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]);
1237 CRM_Core_Session
::singleton()->setStatus($status, ts('Oops.'), 'alert');
1238 $url = CRM_Utils_System
::url('civicrm/event/info',
1239 "reset=1&id={$form->_values['event']['id']}&noFullMsg=true"
1241 if ($form->_action
& CRM_Core_Action
::PREVIEW
) {
1242 $url .= '&action=preview';
1245 if ($form->_pcpId
) {
1246 $url .= '&pcpId=' . $form->_pcpId
;
1249 CRM_Utils_System
::redirect($url);
1252 if ($isAdditional) {
1253 $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.");
1254 CRM_Core_Session
::singleton()->setStatus($status, ts('Oops.'), 'alert');
1255 return $participant->id
;