$atts Block attributes (`loginPageId`, * `inviteOnlyMessage`) or shortcode * attributes (`login_page_id`, * `invite_only_message`). */ public function render( array $atts ): string { // A just-completed invite signup is redirected back here already logged // in (see maybeHandleSubmit); its success flag distinguishes that from a // visitor who simply happens to be signed in already. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag; the submit that set it was nonce-checked. $registered = sanitize_key( Val::string( wp_unslash( $_GET['us_registered'] ?? '' ) ) ); if ( is_user_logged_in() ) { if ( self::RESULT_INVITE === $registered ) { // An invited student is done the moment they land here logged in, // so this is where their "continue" link belongs. The sign-in-page // fallback is deliberately not used: pointing someone who is // already signed in at the login screen helps nobody. $continue = $this->continueUrl( $this->successPageId( $atts ) ); $link = null === $continue ? '' : '

' . esc_html__( 'Continue to your account', 'unsupervised-schedular' ) . '

'; return '

' . esc_html__( 'Your account has been created and you are now logged in.', 'unsupervised-schedular' ) . '

' . $link . '
'; } return '

' . esc_html__( 'You already have an account and are logged in.', 'unsupervised-schedular' ) . '

'; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- token identifies the invite; the form submit is nonce-checked in maybeHandleSubmit. $token = sanitize_text_field( Val::string( wp_unslash( $_REQUEST['us_invite'] ?? '' ) ) ); // Only the token's hash is stored, so hash the submitted token for lookup. $invite = '' !== $token ? $this->invites->findByToken( Invite::hashToken( $token ) ) : null; $open = $this->settings->openRegistrationEnabled(); // Only a redeemable invite fixes the form's email to the invited address. // A stale token (expired / accepted / revoked) with open registration on // must fall back to the normal editable email field, not show — and then // fail to submit — the stale invite's address. $inviteValid = null !== $invite && $invite->isAcceptable( current_time( 'mysql' ) ); // The submission itself is processed in maybeHandleSubmit on // template_redirect (before any output), so the invite auto-login cookie // is actually sent. Its success signal returns here as ?us_registered; // only a validation error is carried on the instance to show inline. $successType = in_array( $registered, [ self::RESULT_CONFIRM, self::RESULT_CONFIRM_GROUP ], true ) ? $registered : ''; $error = $this->submitError; // Result of an email-confirmation link (set by EmailConfirmationHandler's redirect). // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag, not a state change. $confirmResult = sanitize_key( Val::string( wp_unslash( $_GET['us_confirmed'] ?? '' ) ) ); // Where the post-confirmation prompt sends students to sign in. $loginUrl = $this->loginUrl( $this->successPageId( $atts ) ); $policyForms = $this->signupPolicies(); $accountQuestions = $this->questions->findByScope( Question::SCOPE_ACCOUNT, activeOnly: true ); $canRegister = $open || $inviteValid; $inviteOnlyMessage = $this->inviteOnlyMessage( $atts ); // The signup form carries the same policy-acceptance markup as the booking // gate, so it needs the plugin stylesheet that formats it. wp_enqueue_style( 'us-scheduler' ); // The two-step script only matters when there is a second step to reveal. if ( $canRegister && '' === $successType && [] !== $accountQuestions ) { wp_enqueue_script( 'us-scheduler-register' ); } ob_start(); include USC_PLUGIN_DIR . 'templates/frontend/register-page.php'; return (string) ob_get_clean(); } /** * Process a submitted registration on `template_redirect`, before any page * output. Running here (rather than inside {@see render()}, which fires * during `the_content` after headers are sent) is what lets the invite * branch's `wp_set_auth_cookie()` actually persist — otherwise the student * appears logged in for a single render and is logged out on the next view. * * On success the request is redirected (post/redirect/get) with a * `?us_registered` flag so a refresh cannot resubmit; a validation error is * stashed for {@see render()} to show inline with the form. */ public function maybeHandleSubmit(): void { if ( ! isset( $_POST['us_register'] ) || is_user_logged_in() ) { return; } if ( ! check_admin_referer( 'us_student_register' ) ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified by check_admin_referer above. $token = sanitize_text_field( Val::string( wp_unslash( $_REQUEST['us_invite'] ?? '' ) ) ); $invite = '' !== $token ? $this->invites->findByToken( Invite::hashToken( $token ) ) : null; $open = $this->settings->openRegistrationEnabled(); $result = $this->handleSubmit( $invite, $open ); if ( in_array( $result, [ self::RESULT_INVITE, self::RESULT_CONFIRM, self::RESULT_CONFIRM_GROUP ], true ) ) { $this->redirect( add_query_arg( 'us_registered', $result, $this->currentUrl() ) ); return; } $this->submitError = $result; } /** * The current page's clean permalink, used as the post/redirect/get target * so the invite token and any stale flags are dropped from the URL. */ private function currentUrl(): string { $url = get_permalink(); return is_string( $url ) ? $url : home_url( '/' ); } /** * Issues the post-submit redirect and stops the request. Split out so tests * can observe the target without the process exiting. */ protected function redirect( string $url ): void { wp_safe_redirect( $url ); exit; } /** * The message shown when registration is closed and no valid invite is * present. Studios can override the default via the block * (`inviteOnlyMessage`) or shortcode (`invite_only_message`) attribute. * * @param array $atts */ private function inviteOnlyMessage( array $atts ): string { $custom = trim( Val::string( $atts['inviteOnlyMessage'] ?? $atts['invite_only_message'] ?? '' ) ); if ( '' !== $custom ) { return $custom; } return esc_html__( 'Registration is by invitation only. Please use the link from your invitation email, or contact the studio.', 'unsupervised-schedular' ); } /** * Redirect to the configured registration page when an invite token lands * elsewhere (e.g. a link generated before the page was selected). Hooked on * `template_redirect`. */ public function maybeRedirectToRegistrationPage(): void { if ( is_admin() ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only token used only to build the redirect target. $token = sanitize_text_field( Val::string( wp_unslash( $_GET['us_invite'] ?? '' ) ) ); if ( '' === $token ) { return; } $pageId = Val::int( get_option( RegistrationController::OPTION_PAGE, 0 ) ); if ( $pageId <= 0 || is_page( $pageId ) ) { return; } wp_safe_redirect( add_query_arg( 'us_invite', rawurlencode( $token ), (string) get_permalink( $pageId ) ) ); exit; } /** * Process the submitted registration. Returns a success signal * ({@see RESULT_INVITE} or {@see RESULT_CONFIRM}) or an error message string * on failure. * * The invite branch is tried first, so an invited student always completes * signup regardless of whether open registration is enabled. */ private function handleSubmit( ?Invite $invite, bool $open ): string { $inviteValid = null !== $invite && $invite->isAcceptable( current_time( 'mysql' ) ); if ( ! $inviteValid && ! $open ) { return esc_html__( 'This invitation is invalid, expired, or has already been used.', 'unsupervised-schedular' ); } // The submit nonce is verified by the caller (render) before this runs. // phpcs:disable WordPress.Security.NonceVerification.Missing // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be sanitized. $password = Val::string( wp_unslash( $_POST['password'] ?? '' ) ); $displayName = sanitize_text_field( Val::string( wp_unslash( $_POST['display_name'] ?? '' ) ) ); if ( strlen( $password ) < 8 ) { return esc_html__( 'Please choose a password of at least 8 characters.', 'unsupervised-schedular' ); } // The email is fixed by a personal invite; group-link signups and // self-signups supply their own. if ( $inviteValid && ! $invite->isGroup() ) { $email = $invite->email; } else { $email = sanitize_email( Val::string( wp_unslash( $_POST['email'] ?? '' ) ) ); if ( ! is_email( $email ) ) { return esc_html__( 'Please enter a valid email address.', 'unsupervised-schedular' ); } } $policyForms = $this->signupPolicies(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element is coerced to a positive int in the array_map callback; slashes cannot survive integer coercion. $accepted = array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), (array) ( $_POST['accept'] ?? [] ) ); // phpcs:enable WordPress.Security.NonceVerification.Missing foreach ( $policyForms as $form ) { if ( ! in_array( (int) $form['version']->id, $accepted, true ) ) { return esc_html__( 'You must accept all required policies to register.', 'unsupervised-schedular' ); } } // Account-signup questions (step two) — validate before creating the user so // a missing required answer never leaves a half-registered account behind. $accountQuestions = $this->questions->findByScope( Question::SCOPE_ACCOUNT, activeOnly: true ); $answers = $this->submittedAnswers(); foreach ( $accountQuestions as $question ) { if ( $question->isRequired && '' === trim( (string) ( $answers[ (int) $question->id ] ?? '' ) ) ) { return esc_html__( 'Please answer all required registration questions.', 'unsupervised-schedular' ); } } if ( email_exists( $email ) ) { return esc_html__( 'An account already exists for this email.', 'unsupervised-schedular' ); } $userId = wp_insert_user( [ 'user_login' => $email, 'user_email' => $email, 'user_pass' => $password, 'display_name' => '' !== $displayName ? $displayName : $email, 'role' => $inviteValid ? $invite->role : RoleManager::STUDENT, ] ); if ( is_wp_error( $userId ) ) { return esc_html__( 'Could not create the account. Please contact the studio.', 'unsupervised-schedular' ); } $this->recordAcceptances( $policyForms, (int) $userId ); $this->recordAnswers( $accountQuestions, $answers, (int) $userId ); if ( $inviteValid && ! $invite->isGroup() ) { $this->invites->markAccepted( (int) $invite->id, (int) $userId ); // A personal invite may carry a group-class grant (invited by email); // point any grants for this address at the new account so the class // becomes enrollable for them. $this->access->linkStudentByEmail( $email, (int) $userId ); wp_set_current_user( (int) $userId ); wp_set_auth_cookie( (int) $userId ); return self::RESULT_INVITE; } // Group-link signups and self-signups both stay pending until they // confirm their email; the group link is multi-use so it is never marked // accepted. A group signup auto-approves on confirmation — no admin // review — while a self-signup then waits for studio approval. $autoApprove = $inviteValid && $invite->isGroup(); $rawToken = RegistrationStatus::markPending( (int) $userId, $autoApprove ); $user = get_user_by( 'id', (int) $userId ); if ( $user instanceof \WP_User ) { $this->mailer->sendConfirmation( $user, $this->confirmUrl( $rawToken ) ); } return $autoApprove ? self::RESULT_CONFIRM_GROUP : self::RESULT_CONFIRM; } /** * The page id chosen for the post-registration destination, from either the * block (`loginPageId`) or shortcode (`login_page_id`) attribute. * * @param array $atts */ private function successPageId( array $atts ): int { return Val::int( $atts['loginPageId'] ?? $atts['login_page_id'] ?? 0 ); } /** * URL the post-confirmation sign-in link points to: the chosen login page * when one is configured (and still exists), otherwise the WordPress login * screen. */ private function loginUrl( int $loginPageId ): string { return $this->continueUrl( $loginPageId ) ?? wp_login_url(); } /** * The chosen post-registration page's URL, or null when none is configured * (or it has since been deleted). Unlike {@see loginUrl()} this has no * WordPress-login-screen fallback, so callers that need a page the student * was actually sent to — the invited-student link and the block's * auto-redirect — can tell "not configured" from "configured". */ public function continueUrl( int $pageId ): ?string { if ( $pageId <= 0 ) { return null; } $url = get_permalink( $pageId ); return is_string( $url ) ? $url : null; } /** * Whether this request is a *finished* registration — the states the * block's auto-redirect may act on: * * - an invited student who just signed up and is now logged in, and * - a self-signup returning from the emailed confirmation link, whether * their account is ready (`ready`) or awaiting studio approval (`1`). * * Deliberately excluded: the intermediate "check your email" step (the * student would never see the instruction) and every failure — a validation * error or an expired confirmation link (`expired`) — so the message always * gets shown. The `us_confirmed` values are set by * {@see EmailConfirmationHandler::maybeConfirm()}. */ public function isRegistrationComplete(): bool { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag; the submit that set it was nonce-checked. $registered = sanitize_key( Val::string( wp_unslash( $_GET['us_registered'] ?? '' ) ) ); if ( self::RESULT_INVITE === $registered ) { return is_user_logged_in(); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag set by EmailConfirmationHandler's redirect. $confirmed = sanitize_key( Val::string( wp_unslash( $_GET['us_confirmed'] ?? '' ) ) ); return in_array( $confirmed, [ '1', 'ready' ], true ); } /** * Build the email-confirmation URL for a raw token: the configured * registration page (falling back to the home page) with `?us_confirm=`. */ private function confirmUrl( string $rawToken ): string { $pageId = Val::int( get_option( RegistrationController::OPTION_PAGE, 0 ) ); $base = $pageId > 0 ? (string) get_permalink( $pageId ) : home_url( '/' ); return add_query_arg( 'us_confirm', rawurlencode( $rawToken ), $base ); } /** * The account-question answers submitted with the form, keyed by question id. * * @return array */ private function submittedAnswers(): array { // The submit nonce is verified by the caller (render) before this runs. // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- each value is unslashed and sanitized in the loop below. $raw = $_POST['us_answers'] ?? []; if ( ! is_array( $raw ) ) { return []; } $out = []; foreach ( $raw as $questionId => $value ) { $out[ absint( Val::int( $questionId ) ) ] = sanitize_textarea_field( Val::string( wp_unslash( $value ) ) ); } return $out; } /** * Persist the submitted answers for each active account-signup question. * * @param list $questions * @param array $answers question_id => submitted value */ private function recordAnswers( array $questions, array $answers, int $userId ): void { foreach ( $questions as $question ) { $value = trim( (string) ( $answers[ (int) $question->id ] ?? '' ) ); if ( '' === $value ) { continue; } $this->answers->insert( new Answer( questionId: (int) $question->id, registrationType: Answer::REG_ACCOUNT, registrationId: $userId, studentId: $userId, answerValue: $value, ) ); } } /** * Record account-time acceptances for each signup policy version. * * @param list $policyForms */ private function recordAcceptances( array $policyForms, int $userId ): void { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- IP is stored verbatim for audit. $ip = sanitize_text_field( Val::string( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) ) ); foreach ( $policyForms as $form ) { $this->acceptances->insert( new PolicyAcceptance( policyVersionId: (int) $form['version']->id, studentId: $userId, registrationType: PolicyAcceptance::REG_ACCOUNT, registrationId: $userId, ipAddress: '' !== $ip ? $ip : null, ) ); } } /** * Signup-scoped policies that have a current published version. * * @return list */ private function signupPolicies(): array { $out = []; foreach ( $this->policies->findForScope( Policy::SCOPE_SIGNUP ) as $policy ) { if ( null === $policy->currentVersionId ) { continue; } $version = $this->versions->findById( $policy->currentVersionId ); if ( null === $version || ! $version->isPublished() ) { continue; } $out[] = [ 'policy' => $policy, 'version' => $version, ]; } return $out; } }