Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 838
0.00% covered (danger)
0.00%
0 / 25
CRAP
0.00% covered (danger)
0.00%
0 / 1
LoginSignupSpecialPage
0.00% covered (danger)
0.00%
0 / 838
0.00% covered (danger)
0.00%
0 / 25
54056
0.00% covered (danger)
0.00%
0 / 1
 isSignup
n/a
0 / 0
n/a
0 / 0
0
 successfulAction
n/a
0 / 0
n/a
0 / 0
0
 logAuthResult
n/a
0 / 0
n/a
0 / 0
0
 setRequest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getLoginHelper
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 loadRequestParameters
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
42
 load
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
182
 getPreservedParams
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 beforeExecute
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 107
0.00% covered (danger)
0.00%
0 / 1
1892
 getAuthenticationRequests
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 canBypassForm
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
72
 showSuccessPage
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 mainLoginForm
0.00% covered (danger)
0.00%
0 / 99
0.00% covered (danger)
0.00%
0 / 1
702
 getPageHtml
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
182
 getBenefitsContainerHtml
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 1
42
 getAuthForm
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
72
 onAuthChangeFormFields
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 showExtraInformation
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 getCreateAccountUsernamePolicyBulletsHtml
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 getFieldDefinitions
0.00% covered (danger)
0.00%
0 / 307
0.00% covered (danger)
0.00%
0 / 1
3080
 showCreateAccountLink
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 getTokenName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 makeLanguageSelector
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 makeLanguageSelectorLink
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 postProcessFormDescriptor
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
306
 getNoticeHtml
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Holds shared logic for login and account creation pages.
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 * @ingroup SpecialPage
8 */
9
10namespace MediaWiki\SpecialPage;
11
12use Exception;
13use LogicException;
14use MediaWiki\Auth\AuthenticationRequest;
15use MediaWiki\Auth\AuthenticationResponse;
16use MediaWiki\Auth\AuthManager;
17use MediaWiki\Auth\PasswordAuthenticationRequest;
18use MediaWiki\Auth\UsernameAuthenticationRequest;
19use MediaWiki\Context\DerivativeContext;
20use MediaWiki\Context\RequestContext;
21use MediaWiki\Exception\ErrorPageError;
22use MediaWiki\Exception\FatalError;
23use MediaWiki\Exception\PermissionsError;
24use MediaWiki\Exception\ReadOnlyError;
25use MediaWiki\Html\Html;
26use MediaWiki\HTMLForm\HTMLForm;
27use MediaWiki\Logger\LoggerFactory;
28use MediaWiki\MainConfigNames;
29use MediaWiki\MediaWikiServices;
30use MediaWiki\Message\Message;
31use MediaWiki\Parser\Sanitizer;
32use MediaWiki\Skin\Skin;
33use MediaWiki\Specials\Helpers\LoginHelper;
34use MediaWiki\Status\Status;
35use MediaWiki\Title\Title;
36use MediaWiki\User\User;
37use MediaWiki\User\UserIdentity;
38use StatusValue;
39use Wikimedia\ScopedCallback;
40
41/**
42 * Holds shared logic for login and account creation pages.
43 *
44 * @ingroup SpecialPage
45 * @ingroup Auth
46 */
47abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
48
49    /**
50     * The title of the page to return to after authentication finishes, or the empty string
51     * when there is no return target.
52     * Typically comes from the 'returnto' URL parameter. Validating and normalizing is the
53     * caller's responsibility.
54     * @var string
55     */
56    protected string $mReturnTo;
57    /**
58     * The query string part of the URL to return to after authentication finishes.
59     * Typically comes from the 'returntoquery' URL parameter.
60     * @var string
61     */
62    protected string $mReturnToQuery;
63    /**
64     * The fragment part of the URL to return to after authentication finishes.
65     * When not empty, should include the '#' character.
66     * Typically comes from the 'returntoanchor' URL parameter.
67     * @var string
68     */
69    protected string $mReturnToAnchor;
70    /**
71     * Value of the 'alwaysShowLogin' URL parameter. When true, the login form will be shown
72     * even if the user is already logged in. When false, the user might be redirected if we
73     * know (from the 'returnto' parameter) where to redirect them to (although there are
74     * other conditions which can also prevent that).
75     */
76    protected bool $mAlwaysShowLogin;
77
78    /** @var bool */
79    protected $mPosted;
80    /** @var string|null */
81    protected $mAction;
82    /** @var string */
83    protected $mToken;
84    /** @var bool */
85    protected $mStickHTTPS;
86    /** @var bool */
87    protected $mFromHTTP;
88    /** @var string */
89    protected $mEntryError = '';
90    /** @var string */
91    protected $mEntryErrorType = 'error';
92    /** @var LoginHelper */
93    protected $loginHelper = null;
94
95    /** @var bool */
96    protected $mLoaded = false;
97    /** @var bool */
98    protected $mLoadedRequest = false;
99    /** @var string|null */
100    protected $mSecureLoginUrl;
101    /** @var Message|true|null */
102    private $reasonValidatorResult = null;
103
104    /** @var string */
105    protected $securityLevel;
106
107    /** @var bool True if the user if creating an account for someone else. Flag used for internal
108     * communication, only set at the very end.
109     */
110    protected $proxyAccountCreation;
111    /** @var User FIXME another flag for passing data. */
112    protected $targetUser;
113
114    /** @var HTMLForm|null */
115    protected $authForm;
116
117    /**
118     * @return bool
119     */
120    abstract protected function isSignup();
121
122    /**
123     * @param bool $direct True if the action was successful just now; false if that happened
124     *    pre-redirection (so this handler was called already)
125     * @param StatusValue|null $extraMessages
126     * @return void
127     */
128    abstract protected function successfulAction( $direct = false, $extraMessages = null );
129
130    /**
131     * Logs to the authmanager-stats channel.
132     * @param bool $success
133     * @param UserIdentity $performer The performer
134     * @param string|null $status Error message key
135     */
136    abstract protected function logAuthResult( $success, UserIdentity $performer, $status = null );
137
138    /** @inheritDoc */
139    protected function setRequest( array $data, $wasPosted = null ) {
140        parent::setRequest( $data, $wasPosted );
141        $this->mLoadedRequest = false;
142    }
143
144    /**
145     * Get the login helper.
146     * @return LoginHelper
147     */
148    private function getLoginHelper(): LoginHelper {
149        if ( $this->loginHelper === null ) {
150            $this->loginHelper = new LoginHelper( $this->getContext() );
151        }
152        return $this->loginHelper;
153    }
154
155    /**
156     * Load basic request parameters for this Special page.
157     */
158    private function loadRequestParameters() {
159        if ( $this->mLoadedRequest ) {
160            return;
161        }
162        $this->mLoadedRequest = true;
163        $request = $this->getRequest();
164
165        $this->mPosted = $request->wasPosted();
166        $this->mAction = $request->getRawVal( 'action' );
167        $this->mFromHTTP = $request->getBool( 'fromhttp', false )
168            || $request->getBool( 'wpFromhttp', false );
169        $this->mStickHTTPS = $this->getConfig()->get( MainConfigNames::ForceHTTPS )
170            || ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
171            || $request->getBool( 'wpForceHttps', false );
172        $this->mReturnTo = $request->getVal( 'returnto', '' );
173        $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
174        $this->mReturnToAnchor = $request->getVal( 'returntoanchor', '' );
175        $this->mAlwaysShowLogin = $request->getBool( 'alwaysShowLogin' );
176    }
177
178    /**
179     * Load data from request.
180     * @internal
181     * @param string $subPage Subpage of Special:Userlogin
182     */
183    protected function load( $subPage ) {
184        $this->loadRequestParameters();
185        if ( $this->mLoaded ) {
186            return;
187        }
188        $this->mLoaded = true;
189        $request = $this->getRequest();
190
191        // set securityLevel early, loadAuth might rely on it
192        $securityLevel = $this->getRequest()->getText( 'force' );
193        if (
194            $securityLevel &&
195                MediaWikiServices::getInstance()->getAuthManager()->securitySensitiveOperationStatus(
196                    $securityLevel ) === AuthManager::SEC_REAUTH
197        ) {
198            $this->securityLevel = $securityLevel;
199        }
200
201        $this->loadAuth( $subPage );
202
203        $this->mToken = $request->getVal( $this->getTokenName() );
204
205        // Show an error or warning or a notice passed on from a previous page
206        $entryError = $this->msg( $request->getVal( 'error', '' ) );
207        $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
208        $entryNotice = $this->msg( $request->getVal( 'notice', '' ) );
209        // bc: provide login link as a parameter for messages where the translation
210        // was not updated
211        $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
212            $this->getPageTitle(),
213            $this->msg( 'loginreqlink' )->text(),
214            [],
215            $this->getPreservedParams( [ 'reset' => true ] )
216        );
217
218        // Only show valid error or warning messages.
219        $validErrorMessages = LoginHelper::getValidErrorMessages();
220        if ( $entryError->exists()
221            && in_array( $entryError->getKey(), $validErrorMessages, true )
222        ) {
223            $this->mEntryErrorType = 'error';
224            $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
225
226        } elseif ( $entryWarning->exists()
227            && in_array( $entryWarning->getKey(), $validErrorMessages, true )
228        ) {
229            $this->mEntryErrorType = 'warning';
230            $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
231        } elseif ( $entryNotice->exists()
232            && in_array( $entryNotice->getKey(), $validErrorMessages, true )
233        ) {
234            $this->mEntryErrorType = 'notice';
235            $this->mEntryError = $entryNotice->parse();
236        }
237
238        # 1. When switching accounts, it sucks to get automatically logged out
239        # 2. Do not return to PasswordReset after a successful password change
240        #    but goto Wiki start page (Main_Page) instead ( T35997 )
241        $returnToTitle = Title::newFromText( $this->mReturnTo );
242        if ( is_object( $returnToTitle )
243            && ( $returnToTitle->isSpecial( 'Userlogout' )
244                || $returnToTitle->isSpecial( 'PasswordReset' ) )
245        ) {
246            $this->mReturnTo = '';
247            $this->mReturnToQuery = '';
248        }
249    }
250
251    /** @inheritDoc */
252    protected function getPreservedParams( $options = [] ) {
253        $params = $options['params'] ?? [];
254
255        // Override returnto* with their property-based values, to account for the
256        // special-casing in load().
257        $this->loadRequestParameters();
258        $properties = [
259            'returnto' => 'mReturnTo',
260            'returntoquery' => 'mReturnToQuery',
261            'returntoanchor' => 'mReturnToAnchor',
262        ];
263        foreach ( $properties as $key => $prop ) {
264            $value = $this->$prop;
265            if ( $value !== '' ) {
266                $params[$key] = $value;
267            } else {
268                unset( $params[$key] );
269            }
270        }
271
272        if ( $this->mAlwaysShowLogin ) {
273            $params['alwaysShowLogin'] = '1';
274        }
275        if ( $this->getConfig()->get( MainConfigNames::SecureLogin ) && !$this->isSignup() ) {
276            $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
277        }
278
279        $options['params'] = $params;
280        return parent::getPreservedParams( $options );
281    }
282
283    /** @inheritDoc */
284    protected function beforeExecute( $subPage ) {
285        // finish initializing the class before processing the request - T135924
286        $this->loadRequestParameters();
287        return parent::beforeExecute( $subPage );
288    }
289
290    /**
291     * @param string|null $subPage
292     */
293    public function execute( $subPage ) {
294        if ( $this->mPosted ) {
295            $timer = MediaWikiServices::getInstance()->getStatsFactory()
296                ->getTiming( 'auth_specialpage_executeTiming_seconds' )
297                ->start();
298            $profilingScope = new ScopedCallback( function () use ( $timer ) {
299                $timer
300                    ->setLabel( 'action', $this->authAction )
301                    ->stop();
302            } );
303        }
304
305        $authManager = MediaWikiServices::getInstance()->getAuthManager();
306        $session = $this->getRequest()->getSession();
307
308        // Before persisting, set the login token to avoid double writes
309        $this->getToken();
310
311        // Session data is used for various things in the authentication process, so we must make
312        // sure a session cookie or some equivalent mechanism is set.
313        $session->persist();
314        // Explicitly disable cache to ensure cookie blocks may be set (T152462).
315        // (Technically redundant with sessions persisting from this page.)
316        $this->getOutput()->disableClientCache();
317
318        $this->load( $subPage );
319
320        // Do this early, so that it affects how error pages are rendered too
321        if ( $this->getLoginHelper()->isDisplayModePopup() ) {
322            // Replace the default skin with a "micro-skin" that omits most of the interface. (T362706)
323            // In the future, we might allow normal skins to serve this mode too, if they advise that
324            // they support it by setting a skin option, so that colors and fonts could stay consistent.
325            $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
326            $this->getContext()->setSkin( $skinFactory->makeSkin( 'authentication-popup' ) );
327        }
328
329        $this->setHeaders();
330        $this->checkPermissions();
331
332        // Make sure the system configuration allows log in / sign up
333        if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
334            if ( !$session->canSetUser() ) {
335                throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
336                    $session->getProvider()->describe( $this->getLanguage() )
337                ] );
338            }
339            throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
340        } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
341            throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
342        }
343
344        /*
345         * In the case where the user is already logged in, and was redirected to
346         * the login form from a page that requires login, do not show the login
347         * page. The use case scenario for this is when a user opens a large number
348         * of tabs, is redirected to the login page on all of them, and then logs
349         * in on one, expecting all the others to work properly.
350         *
351         * However, do show the form if it was visited intentionally (no 'returnto'
352         * is present). People who often switch between several accounts have grown
353         * accustomed to this behavior.
354         *
355         * For temporary users, the form is always shown, since the UI presents
356         * temporary users as not logged in and offers to discard their temporary
357         * account by logging in.
358         *
359         * Also make an exception when force=<level> is set in the URL, which means the user must
360         * reauthenticate for security reasons; for POST (although it shouldn't really happen);
361         * and allow an explicit URL parameter override.
362         */
363        if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
364            ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
365            !$this->mAlwaysShowLogin &&
366            !$this->getUser()->isTemp() && $this->getUser()->isRegistered()
367        ) {
368            $this->successfulAction();
369            return;
370        }
371
372        // If logging in and not on HTTPS, either redirect to it or offer a link.
373        if ( $this->getRequest()->getProtocol() !== 'https' ) {
374            $title = $this->getFullTitle();
375            $query = $this->getPreservedParams() + [
376                    'title' => null,
377                    ( $this->mEntryErrorType === 'error' ? 'error'
378                        : 'warning' ) => $this->mEntryError,
379                ] + $this->getRequest()->getQueryValues();
380            $url = $title->getFullURL( $query, false, PROTO_HTTPS );
381            if ( $this->getConfig()->get( MainConfigNames::SecureLogin ) && !$this->mFromHTTP ) {
382                // Avoid infinite redirect
383                $url = wfAppendQuery( $url, 'fromhttp=1' );
384                $this->getOutput()->redirect( $url );
385                // Since we only do this redir to change proto, always vary
386                $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
387
388                return;
389            } else {
390                // A wiki without HTTPS login support should set $wgServer to
391                // http://somehost, in which case the secure URL generated
392                // above won't actually start with https://
393                if ( str_starts_with( $url, 'https://' ) ) {
394                    $this->mSecureLoginUrl = $url;
395                }
396            }
397        }
398
399        if ( !$this->isActionAllowed( $this->authAction ) ) {
400            // FIXME how do we explain this to the user? can we handle session loss better?
401            // messages used: authpage-cannot-login, authpage-cannot-login-continue,
402            // authpage-cannot-create, authpage-cannot-create-continue
403            $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
404            return;
405        }
406
407        if ( $this->canBypassForm( $button_name ) ) {
408            $this->setRequest( [], true );
409            $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
410            if ( $button_name ) {
411                $this->getRequest()->setVal( $button_name, true );
412            }
413        }
414        $performer = $this->getUser();
415        $status = $this->trySubmit();
416
417        if ( !$status || !$status->isGood() ) {
418            $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
419            return;
420        }
421
422        /** @var AuthenticationResponse $response */
423        $response = $status->getValue();
424
425        $returnToUrl = $this->getPageTitle( 'return' )
426            ->getFullURL( $this->getPreservedParams( [ 'withToken' => true ] ), false, PROTO_HTTPS );
427        switch ( $response->status ) {
428            case AuthenticationResponse::PASS:
429                $this->logAuthResult( true, $performer );
430                $this->proxyAccountCreation = $this->isSignup() && $this->getUser()->isNamed();
431                $this->targetUser = User::newFromName( $response->username );
432
433                if (
434                    !$this->proxyAccountCreation
435                    && $response->loginRequest
436                    && $authManager->canAuthenticateNow()
437                ) {
438                    // successful registration; log the user in instantly
439                    $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
440                        $returnToUrl );
441                    if ( $response2->status !== AuthenticationResponse::PASS ) {
442                        LoggerFactory::getInstance( 'login' )
443                            ->error( 'Could not log in after account creation' );
444                        $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
445                        break;
446                    }
447                }
448
449                if ( !$this->proxyAccountCreation ) {
450                    $context = RequestContext::getMain();
451                    $localContext = $this->getContext();
452                    if ( $context !== $localContext ) {
453                        // remove AuthManagerSpecialPage context hack
454                        $this->setContext( $context );
455                    }
456                    // Ensure that the context user is the same as the session user.
457                    $this->getAuthManager()->setRequestContextUserFromSessionUser();
458                }
459
460                $this->successfulAction( true );
461                break;
462            case AuthenticationResponse::FAIL:
463                // fall through
464            case AuthenticationResponse::RESTART:
465                $this->authForm = null;
466                if ( $response->status === AuthenticationResponse::FAIL ) {
467                    $action = $this->getDefaultAction( $subPage );
468                    $messageType = 'error';
469                } else {
470                    $action = $this->getContinueAction( $this->authAction );
471                    $messageType = 'warning';
472                }
473                $this->logAuthResult( false, $performer, $response->message ? $response->message->getKey() : '-' );
474                $this->loadAuth( $subPage, $action, true );
475                $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
476                break;
477            case AuthenticationResponse::REDIRECT:
478                $this->authForm = null;
479                $this->getOutput()->redirect( $response->redirectTarget );
480                break;
481            case AuthenticationResponse::UI:
482                $this->authForm = null;
483                $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
484                    : AuthManager::ACTION_LOGIN_CONTINUE;
485                $this->authRequests = $response->neededRequests;
486                $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
487                break;
488            default:
489                throw new LogicException( 'invalid AuthenticationResponse' );
490        }
491    }
492
493    /** @inheritDoc */
494    protected function getAuthenticationRequests( $action, ?UserIdentity $user = null ) {
495        $options = [];
496        if ( $action === AuthManager::ACTION_LOGIN && $this->securityLevel !== null ) {
497            if ( $this->getUser()->isRegistered() ) {
498                $options['securityLevel'] = $this->securityLevel;
499            } else {
500                // TODO might be nice to show an error. For now just do nothing,
501                // the user will be redirected after login to the reauth form anyway.
502            }
503        }
504        return $this->getAuthManager()->getAuthenticationRequests( $action,
505            $user, $options );
506    }
507
508    /**
509     * Determine if the login form can be bypassed. This will be the case when no more than one
510     * button is present and no other user input fields that are not marked as 'skippable' are
511     * present. If the login form were not bypassed, the user would be presented with a
512     * superfluous page on which they must press the single button to proceed with login.
513     * Not only does this cause an additional mouse click and page load, it confuses users,
514     * especially since there are a help link and forgotten password link that are
515     * provided on the login page that do not apply to this situation.
516     *
517     * @param string|null &$button_name if the form has a single button, returns
518     *   the name of the button; otherwise, returns null
519     * @return bool
520     */
521    private function canBypassForm( &$button_name ) {
522        $button_name = null;
523        if ( $this->isContinued() ) {
524            return false;
525        }
526        $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
527        foreach ( $fields as $fieldname => $field ) {
528            if ( !isset( $field['type'] ) ) {
529                return false;
530            }
531            if ( !empty( $field['skippable'] ) ) {
532                continue;
533            }
534            if ( $field['type'] === 'button' ) {
535                if ( $button_name !== null ) {
536                    $button_name = null;
537                    return false;
538                } else {
539                    $button_name = $fieldname;
540                }
541            } elseif ( $field['type'] !== 'null' ) {
542                return false;
543            }
544        }
545        return true;
546    }
547
548    /**
549     * Show the success page.
550     *
551     * @param string $type Condition of return to; see `executeReturnTo`
552     * @param Message $title Page's title
553     * @param string $msgname
554     * @param string $injected_html
555     * @param StatusValue|null $extraMessages
556     */
557    protected function showSuccessPage(
558        $type, $title, $msgname, $injected_html, $extraMessages
559    ) {
560        $out = $this->getOutput();
561        $out->setPageTitleMsg( $title );
562        if ( $msgname ) {
563            $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
564        }
565        if ( $extraMessages ) {
566            $extraMessages = Status::wrap( $extraMessages );
567            $out->addWikiTextAsInterface(
568                $extraMessages->getWikiText( false, false, $this->getLanguage() )
569            );
570        }
571
572        $out->addHTML( $injected_html );
573
574        $helper = new LoginHelper( $this->getContext() );
575        $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery,
576            $this->mStickHTTPS, $this->mReturnToAnchor );
577    }
578
579    /**
580     * @param AuthenticationRequest[] $requests A list of AuthenticationRequest objects,
581     *   used to generate the form fields. An empty array means a fatal error
582     *   (authentication cannot continue).
583     * @param string|Message $msg
584     * @param string $msgtype
585     * @throws ErrorPageError
586     * @throws Exception
587     * @throws FatalError
588     * @throws PermissionsError
589     * @throws ReadOnlyError
590     * @internal
591     */
592    protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
593        $user = $this->getUser();
594        $out = $this->getOutput();
595
596        // FIXME how to handle empty $requests - restart, or no form, just an error message?
597        // no form would be better for no session type errors, restart is better when can* fails.
598        if ( !$requests ) {
599            $this->authAction = $this->getDefaultAction( $this->subPage );
600            $this->authForm = null;
601            $requests = $this->getAuthenticationRequests( $this->authAction, $user );
602        }
603
604        // Generic styles and scripts for both login and signup form
605        $out->addModuleStyles( [
606            'mediawiki.special.userlogin.common.styles',
607            'mediawiki.codex.messagebox.styles'
608        ] );
609        if ( $this->isSignup() ) {
610            // Additional styles and scripts for signup form
611            $out->addModules( 'mediawiki.special.createaccount' );
612            $out->addModuleStyles( [
613                'mediawiki.special.userlogin.signup.styles'
614            ] );
615            $userPolicyTitleUrl = false;
616            if ( !$this->msg( 'createacct-helpusername-url' )->inContentLanguage()->isDisabled() ) {
617                $titleFactory = MediaWikiServices::getInstance()->getTitleFactory();
618                $userPolicyTitle = $titleFactory->newFromText(
619                    $this->msg( 'createacct-helpusername-url' )->inContentLanguage()->text(),
620                );
621                if ( $userPolicyTitle && ( $userPolicyTitle->exists() || $userPolicyTitle->isExternal() ) ) {
622                    $userPolicyTitleUrl = $userPolicyTitle->getFullURL();
623                }
624            }
625            $out->addJsConfigVars( [
626                'wgCreateAccountUsernamePolicyUrl' => $userPolicyTitleUrl,
627                'wgCreateAccountUsernamePolicyBulletsHtml' => $this->getCreateAccountUsernamePolicyBulletsHtml()
628            ] );
629        } else {
630            // Additional styles for login form
631            $out->addModuleStyles( [
632                'mediawiki.special.userlogin.login.styles'
633            ] );
634        }
635        $out->disallowUserJs(); // just in case...
636
637        $form = $this->getAuthForm( $requests, $this->authAction );
638        $form->prepareForm();
639
640        $submitStatus = Status::newGood();
641        if ( $msg && $msgtype === 'warning' ) {
642            $submitStatus->warning( $msg );
643        } elseif ( $msg && $msgtype === 'error' ) {
644            $submitStatus->fatal( $msg );
645
646            // T409431 Pass information about the error to the frontend to
647            //         be logged by Javascript instrumentation handlers.
648            $this->getOutput()->addJsConfigVars(
649                'wgErrorPageMessageKey',
650                is_string( $msg ) ? $msg : $msg->getKey()
651            );
652        }
653
654        // warning header for non-standard workflows (e.g. security reauthentication)
655        if ( $this->getUser()->isNamed() && !$this->isContinued() ) {
656            if ( !$this->isSignup() && $this->securityLevel ) {
657                $securityLevelLower = strtolower( $this->securityLevel );
658                if ( $this->msg( "userlogin-reauth-banner-$securityLevelLower" )->exists() ) {
659                    $submitStatus->warning( "userlogin-reauth-banner-$securityLevelLower" );
660                } else {
661                    $submitStatus->warning( 'userlogin-reauth-banner-generic', $this->securityLevel );
662                }
663
664                // Build cancel link
665                $cancelLinkAttribs = [ 'class' => 'mw-authentication-popup-cancel' ];
666                if ( $this->getLoginHelper()->isDisplayModePopup() ) {
667                    $cancelLinkAttribs['class'] .= ' mw-authentication-popup-link';
668                    $this->getOutput()->addModules( 'mediawiki.authenticationPopup.cancel' );
669                }
670                $returnTitle = Title::newFromText( $this->mReturnTo );
671                if ( $returnTitle && !$returnTitle->isSpecialPage() ) {
672                    $cancelLink = $this->getLinkRenderer()->makeLink(
673                        $returnTitle->createFragmentTarget( $this->mReturnToAnchor ),
674                        $this->msg( 'userlogin-reauth-description-link' )->text(),
675                        $cancelLinkAttribs,
676                        wfCgiToArray( $this->mReturnToQuery )
677                    );
678                } else {
679                    $cancelLink = $this->getLinkRenderer()->makeLink(
680                        Title::newMainPage(),
681                        $this->msg( 'userlogin-reauth-description-link' )->text(),
682                        $cancelLinkAttribs
683                    );
684                }
685
686                $form->addHeaderHtml(
687                    $this->msg( 'userlogin-reauth-description' )
688                        ->rawParams( $cancelLink )
689                        ->parseAsBlock()
690                );
691            } else {
692                // User is accessing the login or signup page while already logged in.
693                // Add a big warning and a button to leave this page (T284927),
694                // but allow using the form if they really want to.
695                $form->addPreHtml(
696                    Html::warningBox( $this->msg(
697                        $this->isSignup() ? 'createacct-loggedin' : 'userlogin-loggedin',
698                        $this->getUser()->getName()
699                    )->parse() ) .
700                    '<div class="cdx-field"><div class="cdx-field__control">' .
701                    Html::element( 'a',
702                        [
703                            'class' => 'cdx-button cdx-button--fake-button cdx-button--fake-button--enabled ' .
704                                'cdx-button--action-progressive cdx-button--weight-primary mw-htmlform-submit ' .
705                                ( $this->getLoginHelper()->isDisplayModePopup() ? 'mw-authentication-popup-link' : '' ),
706                            'href' => ( Title::newFromText( $this->mReturnTo ) ?: Title::newMainPage() )
707                                ->createFragmentTarget( $this->mReturnToAnchor )->getLinkURL( $this->mReturnToQuery ),
708                        ],
709                        $this->msg(
710                            $this->isSignup() ? 'createacct-loggedin-continue-as' : 'userlogin-loggedin-continue-as',
711                            $this->getUser()->getName()
712                        )->text()
713                    ) .
714                    '</div></div>' .
715                    Html::element( 'h2', [], $this->msg(
716                        $this->isSignup() ? 'createacct-loggedin-heading' : 'userlogin-loggedin-heading'
717                    )->text() ) .
718                    $this->msg(
719                        $this->isSignup() ? 'createacct-loggedin-prompt' : 'userlogin-loggedin-prompt'
720                    )->parseAsBlock()
721                );
722            }
723        }
724
725        $formHtml = $form->getHTML( $submitStatus );
726
727        $out->addHTML( $this->getPageHtml( $formHtml ) );
728    }
729
730    /**
731     * Add page elements which are outside the form.
732     * FIXME this should probably be a template, but use a sensible language (handlebars?)
733     * @param string $formHtml
734     * @return string
735     */
736    protected function getPageHtml( $formHtml ) {
737        $loginPrompt = $this->isSignup() || $this->getLoginHelper()->isDisplayModePopup() || $this->isContinued()
738            ? ''
739            : Html::rawElement( 'div', [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
740        $languageLinks = $this->getConfig()->get( MainConfigNames::LoginLanguageSelector )
741            ? $this->makeLanguageSelector() : '';
742        $signupStartMsg = $this->msg( 'signupstart' );
743        $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
744            ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
745        if ( $languageLinks ) {
746            $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
747                Html::rawElement( 'p', [], $languageLinks )
748            );
749        }
750        if ( $this->getUser()->isTemp() ) {
751            $noticeHtml = $this->getNoticeHtml();
752        } else {
753            $noticeHtml = '';
754        }
755        $formBlock = Html::rawElement( 'div', [ 'id' => 'userloginForm' ], $formHtml );
756        $formAndBenefits = $formBlock;
757        if ( $this->isSignup() && $this->showExtraInformation() && !$this->getUser()->isNamed() ) {
758            $benefitsContainerHtml = null;
759            $info = [
760                'context' => $this->getContext(),
761                'form' => $this->authForm,
762            ];
763            $options = [
764                'beforeForm' => false,
765            ];
766            $this->getHookRunner()->onSpecialCreateAccountBenefits(
767                $benefitsContainerHtml, $info, $options
768            );
769            $benefitsContainerHtml ??= $this->getBenefitsContainerHtml();
770            $formAndBenefits = $options['beforeForm']
771                ? ( $benefitsContainerHtml . $formBlock )
772                : ( $formBlock . $benefitsContainerHtml );
773        }
774
775        return $loginPrompt
776            . $languageLinks
777            . $signupStart
778            . $noticeHtml
779            . Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
780                $formAndBenefits
781            );
782    }
783
784    /**
785     * The HTML to be shown in the "benefits to signing in / creating an account" section of the signup/login page.
786     *
787     * @unstable Experimental method added in 1.38. As noted in the comment from 2015 for getPageHtml,
788     *   this should use a template.
789     * @return string
790     */
791    protected function getBenefitsContainerHtml(): string {
792        $benefitsContainer = '';
793        $this->getOutput()->addModuleStyles( [ 'oojs-ui.styles.icons-user' ] );
794        if ( $this->isSignup() && $this->showExtraInformation() ) {
795            if ( !$this->getUser()->isTemp() ) {
796                // The following messages are used here:
797                // * createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-text1
798                // * createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-text2
799                // * createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-text3
800                $benefitCount = 3;
801                $benefitList = '';
802                for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
803                    $numberUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
804                    $numberHtml = Html::rawElement( 'strong', [], $numberUnescaped );
805                    $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->text();
806                    $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
807                        Html::rawElement( 'p', [],
808                            $this->msg( "createacct-benefit-text$benefitIdx" )->params(
809                                $numberUnescaped,
810                                $numberHtml
811                            )->parse()
812                        )
813                    );
814                }
815                $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
816                    Html::element( 'div', [ 'class' => 'mw-createacct-benefits-heading' ],
817                        $this->msg( 'createacct-benefit-heading' )->text()
818                    )
819                    . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ], $benefitList )
820                );
821            } else {
822                $benefitList = '';
823                $this->getOutput()->addModuleStyles(
824                    [
825                        'oojs-ui.styles.icons-moderation',
826                        'oojs-ui.styles.icons-interactions',
827                    ]
828                );
829                $benefits = [
830                    [
831                        'icon' => 'oo-ui-icon-unStar',
832                        'description' => $this->msg( "benefit-1-description" )->escaped()
833                    ],
834                    [
835                        'icon' => 'oo-ui-icon-userContributions',
836                        'description' => $this->msg( "benefit-2-description" )->escaped()
837                    ],
838                    [
839                        'icon' => 'oo-ui-icon-settings',
840                        'description' => $this->msg( "benefit-3-description" )->escaped()
841                    ]
842                ];
843                foreach ( $benefits as $benefit ) {
844                    $benefitContent = Html::rawElement( 'div', [ 'class' => 'mw-benefit-item' ],
845                        Html::rawElement( 'span', [ 'class' => $benefit[ 'icon' ] ] )
846                        . Html::rawElement( 'p', [], $benefit['description'] )
847                    );
848
849                    $benefitList .= Html::rawElement(
850                        'div', [ 'class' => 'mw-benefit-item-wrapper' ], $benefitContent );
851                }
852
853                $benefitsListWrapper = Html::rawElement(
854                    'div', [ 'class' => 'mw-benefit-list-wrapper' ], $benefitList );
855
856                $headingSubheadingWrapper = Html::rawElement( 'div', [ 'class' => 'mw-heading-subheading-wrapper' ],
857                    Html::element( 'h2', [],
858                        $this->msg( 'createacct-benefit-heading-temp-user' )->text()
859                    )
860                    . Html::element( 'p', [ 'class' => 'mw-benefit-subheading' ],
861                        $this->msg( 'createacct-benefit-subheading-temp-user' )->text()
862                    )
863                );
864
865                $benefitsContainer = Html::rawElement(
866                    'div', [ 'class' => 'mw-createacct-benefits-container' ],
867                    $headingSubheadingWrapper
868                    . $benefitsListWrapper
869                );
870            }
871        }
872        return $benefitsContainer;
873    }
874
875    /**
876     * Generates a form from the given request.
877     * @param AuthenticationRequest[] $requests
878     * @param string $action AuthManager action name
879     * @return HTMLForm
880     */
881    protected function getAuthForm( array $requests, $action ) {
882        // FIXME merge this with parent
883
884        if ( $this->authForm ) {
885            return $this->authForm;
886        }
887
888        $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
889
890        // get basic form description from the auth logic
891        $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
892        // this will call onAuthChangeFormFields()
893        $formDescriptor = $this->fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
894        $this->postProcessFormDescriptor( $formDescriptor, $requests );
895
896        $context = $this->getContext();
897        if ( $context->getRequest() !== $this->getRequest() ) {
898            // We have overridden the request, need to make sure the form uses that too.
899            $context = new DerivativeContext( $this->getContext() );
900            $context->setRequest( $this->getRequest() );
901        }
902        $form = HTMLForm::factory( 'codex', $formDescriptor, $context );
903
904        $form->addHiddenField( 'authAction', $this->authAction );
905        $form->addHiddenField( 'force', $this->securityLevel );
906        $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
907        $config = $this->getConfig();
908        if ( $config->get( MainConfigNames::SecureLogin ) &&
909        !$config->get( MainConfigNames::ForceHTTPS ) ) {
910            // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
911            if ( !$this->isSignup() ) {
912                $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
913                $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
914            }
915        }
916
917        $form->setAction( $this->getPageTitle()->getLocalURL( $this->getPreservedParams(
918            // We have manually set authAction above, so we don't need it in the action URL.
919            [ 'reset' => true ]
920        ) ) );
921        $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
922        if ( $this->isSignup() ) {
923            $form->setId( 'userlogin2' );
924        }
925
926        $form->suppressDefaultSubmit();
927
928        $this->authForm = $form;
929
930        return $form;
931    }
932
933    /** @inheritDoc */
934    public function onAuthChangeFormFields(
935        array $requests, array $fieldInfo, array &$formDescriptor, $action
936    ) {
937        $formDescriptor = self::mergeDefaultFormDescriptor( $fieldInfo, $formDescriptor,
938            $this->getFieldDefinitions( $fieldInfo, $requests ) );
939    }
940
941    /**
942     * Show extra information such as password recovery information, link from login to signup,
943     * CTA etc? Such information should only be shown on the "landing page", ie. when the user
944     * is at the first step of the authentication process.
945     * @return bool
946     */
947    protected function showExtraInformation() {
948        return $this->authAction !== $this->getContinueAction( $this->authAction )
949            && ( !$this->securityLevel || !$this->getUser()->isNamed() );
950    }
951
952    /**
953     * Parsed HTML for the username policy popover bullet list items.
954     *
955     * This is needed, because the community might override these messages with ones that inlcude local links.
956     * But if those links are rendered in javascript, then they would point to pages on the auth-domain,
957     * and that doesn't work.
958     *
959     * @return string[]
960     */
961    private function getCreateAccountUsernamePolicyBulletsHtml(): array {
962        return [
963            $this->msg( 'createacct-username-policy-popover-bullet1' )->parse(),
964            $this->msg( 'createacct-username-policy-popover-bullet2' )->parse(),
965            $this->msg( 'createacct-username-policy-popover-bullet3' )->parse(),
966        ];
967    }
968
969    /**
970     * Create a HTMLForm descriptor for the core login fields.
971     *
972     * @param array $fieldInfo
973     * @param array $requests
974     *
975     * @return array
976     */
977    protected function getFieldDefinitions( array $fieldInfo, array $requests ) {
978        $isLoggedIn = $this->getUser()->isRegistered();
979        $continuePart = $this->isContinued() ? 'continue-' : '';
980        $anotherPart = $isLoggedIn ? 'another-' : '';
981        // @phan-suppress-next-line PhanUndeclaredMethod
982        $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
983        $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
984        $secureLoginLink = '';
985        if ( $this->mSecureLoginUrl ) {
986            $secureLoginLink = Html::rawElement( 'a', [
987                'href' => $this->mSecureLoginUrl,
988                'class' => 'mw-login-flush-right mw-secure',
989            ], Html::element( 'span', [ 'class' => 'mw-secure--icon' ] ) .
990                $this->msg( 'userlogin-signwithsecure' )->parse() );
991        }
992
993        if ( $this->isSignup() ) {
994            $config = $this->getConfig();
995            $usernameHelpButton = Html::rawElement(
996                'button',
997                [
998                    'id' => 'mw-username-help',
999                    'type' => 'button',
1000                    'class' => 'cdx-button cdx-button--icon-only cdx-button--weight-quiet cdx-button--size-small',
1001                    'aria-label' => $this->msg( 'userlogin-yourname-desc-button-a11y-label' )->text(),
1002                ],
1003                Html::element( 'span', [ 'class' => 'cdx-button__icon' ] )
1004            );
1005            $hideIf = isset( $fieldInfo['mailpassword'] ) ? [ 'hide-if' => [ '===', 'mailpassword', '1' ] ] : [];
1006            $fieldDefinitions = [
1007                'username' => [
1008                    'label-raw' => $this->msg( 'userlogin-yourname' )->escaped(),
1009                    'id' => 'wpName2',
1010                    'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
1011                        : 'userlogin-yourname-ph',
1012                    'description-raw' => $this->msg( 'userlogin-yourname-desc' )->escaped() . $usernameHelpButton,
1013                    'cssclass' => 'mw-createacct-username',
1014                ],
1015                'mailpassword' => [
1016                    // create account without providing password, a temporary one will be mailed
1017                    'type' => 'check',
1018                    'label-message' => 'createaccountmail',
1019                    'name' => 'wpCreateaccountMail',
1020                    'id' => 'wpCreateaccountMail',
1021                ],
1022                'password' => [
1023                    'id' => 'wpPassword2',
1024                    'autocomplete' => 'new-password',
1025                    'placeholder-message' => 'createacct-yourpassword-ph',
1026                        'help-message' => '',
1027                        'end-icon-class' => 'mw-password-reveal-icon'
1028                ] + $hideIf,
1029                'domain' => [],
1030                'retype' => [
1031                    'type' => 'password',
1032                    'label-message' => 'createacct-yourpasswordagain',
1033                    'id' => 'wpRetype',
1034                    'cssclass' => 'loginPassword',
1035                    'size' => 20,
1036                    'autocomplete' => 'new-password',
1037                    'validation-callback' => function ( $value, $alldata ) {
1038                        if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
1039                            if ( !$value ) {
1040                                return $this->msg( 'htmlform-required' );
1041                            } elseif ( $value !== $alldata['password'] ) {
1042                                return $this->msg( 'badretype' );
1043                            }
1044                        }
1045                        return true;
1046                    },
1047                    'placeholder-message' => 'createacct-yourpasswordagain-ph',
1048                        'end-icon-class' => 'mw-password-reveal-icon'
1049                ] + $hideIf,
1050                'email' => [
1051                    'type' => 'email',
1052                    'label-message' => 'createacct-emailrequired',
1053                    'id' => 'wpEmail',
1054                    'cssclass' => 'loginText',
1055                    'size' => '20',
1056                    'maxlength' => 255,
1057                    'autocomplete' => 'email',
1058                    // FIXME will break non-standard providers
1059                    'required' => $config->get( MainConfigNames::EmailConfirmToEdit ),
1060                    'validation-callback' => function ( $value, $alldata ) {
1061                        // AuthManager will check most of these, but that will make the auth
1062                        // session fail and this won't, so nicer to do it this way
1063                        if ( !$value &&
1064                            $this->getConfig()->get( MainConfigNames::EmailConfirmToEdit )
1065                        ) {
1066                            // no point in allowing registration without email when email is
1067                            // required to edit
1068                            return $this->msg( 'noemailtitle' );
1069                        } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
1070                            // cannot send password via email when there is no email address
1071                            return $this->msg( 'noemailcreate' );
1072                        } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
1073                            return $this->msg( 'invalidemailaddress' );
1074                        } elseif ( is_string( $value ) && strlen( $value ) > 255 ) {
1075                            return $this->msg( 'changeemail-maxlength' );
1076                        }
1077                        return true;
1078                    },
1079                    // The following messages are used here:
1080                    // * createacct-email-ph
1081                    // * createacct-another-email-ph
1082                    'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1083                ],
1084                'realname' => [
1085                    'type' => 'text',
1086                    'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
1087                        : 'prefs-help-realname',
1088                    'label-message' => 'createacct-realname',
1089                    'cssclass' => 'loginText',
1090                    'size' => 20,
1091                    'placeholder-message' => 'createacct-realname',
1092                    'id' => 'wpRealName',
1093                    'autocomplete' => 'name',
1094                ],
1095                'reason' => [
1096                    // comment for the user creation log
1097                    'type' => 'text',
1098                    'label-message' => 'createacct-reason',
1099                    'cssclass' => 'loginText',
1100                    'id' => 'wpReason',
1101                    'size' => '20',
1102                    'validation-callback' => function ( $value, $alldata ) {
1103                        // if the user sets an email address as the user creation reason, confirm that
1104                        // that was their intent
1105                        if ( $value && Sanitizer::validateEmail( $value ) ) {
1106                            if ( $this->reasonValidatorResult !== null ) {
1107                                return $this->reasonValidatorResult;
1108                            }
1109                            $this->reasonValidatorResult = true;
1110                            $authManager = MediaWikiServices::getInstance()->getAuthManager();
1111                            if ( !$authManager->getAuthenticationSessionData( 'reason-retry', false ) ) {
1112                                $authManager->setAuthenticationSessionData( 'reason-retry', true );
1113                                $this->reasonValidatorResult = $this->msg( 'createacct-reason-confirm' );
1114                            }
1115                            return $this->reasonValidatorResult;
1116                        }
1117                        return true;
1118                    },
1119                    'placeholder-message' => 'createacct-reason-ph',
1120                ],
1121                'createaccount' => [
1122                    // submit button
1123                    'type' => 'submit',
1124                    // The following messages are used here:
1125                    // * createacct-submit
1126                    // * createacct-another-submit
1127                    // * createacct-continue-submit
1128                    // * createacct-another-continue-submit
1129                    'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1130                        'submit' )->text(),
1131                    'name' => 'wpCreateaccount',
1132                    'id' => 'wpCreateaccount',
1133                    'size' => 'large',
1134                    'weight' => 100,
1135                ],
1136            ];
1137
1138            if ( $this->loginHelper->isDisplayModePopup() ) {
1139                $fieldDefinitions['redirectnotice'] = [
1140                    'type' => 'info',
1141                    'default' => $this->msg( 'createacct-popup-redirect-notice' )->text(),
1142                    'cssclass' => 'mw-createacct-redirect-notice',
1143                    'weight' => -1,
1144                ];
1145            }
1146        } else {
1147            // When the user's password is too weak, they might be asked to provide a stronger one
1148            // as a followup step. That is a form with only two fields, 'password' and 'retype',
1149            // and they should behave more like account creation.
1150            $passwordRequest = AuthenticationRequest::getRequestByClass( $this->authRequests,
1151                PasswordAuthenticationRequest::class );
1152            $changePassword = $passwordRequest && $passwordRequest->action == AuthManager::ACTION_CHANGE;
1153            $fieldDefinitions = [
1154                'username' => (
1155                    [
1156                        'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1157                        'id' => 'wpName1',
1158                        'placeholder-message' => 'userlogin-yourname-ph',
1159                    ] + ( $changePassword ? [
1160                        // There is no username field on the AuthManager level when changing
1161                        // passwords. Fake one because password
1162                        'baseField' => 'password',
1163                        'nodata' => true,
1164                        'readonly' => true,
1165                        'cssclass' => 'mw-htmlform-hidden-field',
1166                    ] : [] )
1167                ),
1168                'password' => (
1169                    $changePassword ? [
1170                        'autocomplete' => 'new-password',
1171                        'placeholder-message' => 'createacct-yourpassword-ph',
1172                        'help-message' => '',
1173                    ] : [
1174                        'id' => 'wpPassword1',
1175                        'autocomplete' => 'current-password',
1176                        'placeholder-message' => 'userlogin-yourpassword-ph',
1177                    ]
1178                ),
1179                'retype' => [
1180                    'type' => 'password',
1181                    'autocomplete' => 'new-password',
1182                    'placeholder-message' => 'createacct-yourpasswordagain-ph',
1183                ],
1184                'domain' => [],
1185                'rememberMe' => [
1186                    // option for saving the user token to a cookie
1187                    'type' => 'check',
1188                    'cssclass' => 'mw-userlogin-rememberme',
1189                    'name' => 'wpRemember',
1190                    'label-message' => $this->msg( 'userlogin-remembermypassword' )
1191                        ->numParams( $expirationDays ),
1192                    'id' => 'wpRemember',
1193                ],
1194                'loginattempt' => [
1195                    // submit button
1196                    'type' => 'submit',
1197                    'default' => $this->msg( $this->securityLevel ?
1198                            'pt-login-reauth-button' :
1199                            // The following messages are used here:
1200                            // * pt-login-button
1201                            // * pt-login-continue-button
1202                            'pt-login-' . $continuePart . 'button'
1203                        )->text(),
1204                    'id' => 'wpLoginAttempt',
1205                    'size' => 'large',
1206                    'weight' => 100,
1207                ],
1208                'linkcontainer' => [
1209                    // help link
1210                    'type' => 'info',
1211                    'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1212                    // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1213                    'raw' => true,
1214                    'default' => Html::element( 'a', [
1215                        'href' => Skin::makeInternalOrExternalUrl( $this->msg( 'helplogin-url' )
1216                            ->inContentLanguage()
1217                            ->text() ),
1218                    ], $this->msg( 'userlogin-helplink2' )->text() ),
1219                    'weight' => 200,
1220                ],
1221                // button for ResetPasswordSecondaryAuthenticationProvider
1222                'skipReset' => [
1223                    'weight' => 110,
1224                    'flags' => [],
1225                ],
1226            ];
1227        }
1228
1229        // T369641: We want to ensure that this transformation to the username and/or
1230        // password fields are applied only when we have matching requests within the
1231        // authentication manager.
1232        $isUsernameOrPasswordRequest =
1233            AuthenticationRequest::getRequestByClass( $requests, UsernameAuthenticationRequest::class ) ||
1234            AuthenticationRequest::getRequestByClass( $requests, PasswordAuthenticationRequest::class );
1235
1236        if ( $isUsernameOrPasswordRequest ) {
1237            $fieldDefinitions['username'] += [
1238                'type' => 'text',
1239                'name' => 'wpName',
1240                'cssclass' => 'loginText mw-userlogin-username',
1241                'size' => 20,
1242                'autocomplete' => 'username',
1243                // 'required' => true,
1244            ];
1245            $fieldDefinitions['password'] += [
1246                'type' => 'password',
1247                // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1248                'name' => 'wpPassword',
1249                'cssclass' => 'loginPassword mw-userlogin-password',
1250                'size' => 20,
1251                // 'required' => true,
1252            ];
1253        }
1254
1255        if ( $this->getUser()->isNamed() && $this->securityLevel ) {
1256            // Keep the 'username' field key in the descriptor so the form processor
1257            // still binds POST['wpName'] -> $data['username'] for the AuthenticationRequest,
1258            // but render it as a hidden input. Add a separate info field for the visual.
1259            $fieldDefinitions['username']['type'] = 'hidden';
1260            $fieldDefinitions['username']['default'] = $this->getUser()->getName();
1261            unset( $fieldDefinitions['username']['placeholder-message'] );
1262            unset( $fieldDefinitions['username']['label-raw'] );
1263
1264            $fieldDefinitions['usernameDisplay'] = [
1265                'type' => 'info',
1266                'default' => $this->msg( 'userlogin-yourname-reauth', $this->getUser()->getName() )->parse(),
1267                'raw' => true,
1268                'weight' => -10,
1269            ];
1270        }
1271
1272        if ( $this->mEntryError ) {
1273            $defaultHtml = '';
1274            if ( $this->mEntryErrorType === 'error' ) {
1275                $defaultHtml = Html::errorBox( $this->mEntryError );
1276            } elseif ( $this->mEntryErrorType === 'warning' ) {
1277                $defaultHtml = Html::warningBox( $this->mEntryError );
1278            } elseif ( $this->mEntryErrorType === 'notice' ) {
1279                $defaultHtml = Html::noticeBox( $this->mEntryError );
1280            }
1281            $fieldDefinitions['entryError'] = [
1282                'type' => 'info',
1283                'default' => $defaultHtml,
1284                'raw' => true,
1285                'rawrow' => true,
1286                'weight' => -100,
1287            ];
1288        }
1289        if ( !$this->showExtraInformation() ) {
1290            unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1291        }
1292        if ( $this->isSignup() && $this->showExtraInformation() ) {
1293            // blank signup footer for site customization
1294            // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1295            $signupendMsg = $this->msg( 'signupend' );
1296            $signupendHttpsMsg = $this->msg( 'signupend-https' );
1297            if ( !$signupendMsg->isDisabled() ) {
1298                $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1299                $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1300                    ? $signupendHttpsMsg->parse() : $signupendMsg->parse();
1301                $fieldDefinitions['signupend'] = [
1302                    'type' => 'info',
1303                    'raw' => true,
1304                    'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1305                    'weight' => 225,
1306                ];
1307            }
1308        }
1309        if ( !$this->isSignup() && $this->showExtraInformation() ) {
1310            $passwordReset = MediaWikiServices::getInstance()->getPasswordReset();
1311            if ( $passwordReset->isEnabled()->isGood() ) {
1312                $fieldDefinitions['passwordReset'] = [
1313                    'type' => 'info',
1314                    'raw' => true,
1315                    'cssclass' => 'mw-form-related-link-container',
1316                    'default' => $this->getLinkRenderer()->makeLink(
1317                        SpecialPage::getTitleFor( 'PasswordReset' ),
1318                        $this->msg( 'userlogin-resetpassword-link' )->text(),
1319                        [ 'class' => 'mw-authentication-popup-link' ],
1320                        $this->getPreservedParams()
1321                    ),
1322                    'weight' => 230,
1323                ];
1324            }
1325
1326            // Don't show a "create account" link if the user can't.
1327            if ( $this->showCreateAccountLink() ) {
1328                // link to the other action
1329                $linkTitle = SpecialPage::getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
1330                $linkq = wfArrayToCgi( $this->getPreservedParams( [ 'reset' => true ] ) );
1331                $isLoggedIn = $this->getUser()->isRegistered()
1332                    && !$this->getUser()->isTemp();
1333                $popupMode = $this->getLoginHelper()->isDisplayModePopup();
1334
1335                $fieldDefinitions['createOrLogin'] = [
1336                    'type' => 'info',
1337                    'raw' => true,
1338                    'linkQuery' => $linkq,
1339                    'default' => function ( $params ) use ( $isLoggedIn, $linkTitle ) {
1340                        $buttonClasses = 'cdx-button cdx-button--action-progressive '
1341                            . 'cdx-button--fake-button cdx-button--fake-button--enabled';
1342
1343                        return Html::rawElement( 'div',
1344                            // The following element IDs are used here:
1345                            // mw-createaccount, mw-createaccount-cta
1346                            [ 'id' => 'mw-createaccount' . ( !$isLoggedIn ? '-cta' : '' ),
1347                                'class' => ( $isLoggedIn ? 'mw-form-related-link-container' : '' ) ],
1348                            ( $isLoggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1349                            . Html::element( 'a',
1350                                [
1351                                    // The following element IDs are used here:
1352                                    // mw-createaccount-join, mw-createaccount-join-loggedin
1353                                    'id' => 'mw-createaccount-join' . ( $isLoggedIn ? '-loggedin' : '' ),
1354                                    'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1355                                    'class' => [ 'mw-authentication-popup-link', $buttonClasses => !$isLoggedIn ],
1356                                    'target' => '_self',
1357                                    'tabindex' => 100,
1358                                ],
1359                                $this->msg(
1360                                    $isLoggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1361                                )->text()
1362                            )
1363                        );
1364                    },
1365                    'weight' => $popupMode ? -1 : 235,
1366                ];
1367            }
1368        }
1369
1370        return $fieldDefinitions;
1371    }
1372
1373    /**
1374     * Whether the login/create account form should display a link to the
1375     * other form (in addition to whatever the skin provides).
1376     * @return bool
1377     */
1378    private function showCreateAccountLink() {
1379        return $this->isSignup() ||
1380            $this->getContext()->getAuthority()->isAllowed( 'createaccount' );
1381    }
1382
1383    /**
1384     * @return string
1385     */
1386    protected function getTokenName() {
1387        return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1388    }
1389
1390    /**
1391     * Produce a bar of links which allow the user to select another language
1392     * during login/registration but retain "returnto"
1393     *
1394     * @return string
1395     */
1396    protected function makeLanguageSelector() {
1397        $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1398        if ( $msg->isBlank() ) {
1399            return '';
1400        }
1401        $langs = explode( "\n", $msg->text() );
1402        $links = [];
1403        foreach ( $langs as $lang ) {
1404            $lang = trim( $lang, '* ' );
1405            $parts = explode( '|', $lang );
1406            if ( count( $parts ) >= 2 ) {
1407                $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1408            }
1409        }
1410
1411        return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1412            $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1413    }
1414
1415    /**
1416     * Create a language selector link for a particular language
1417     * Links back to this page preserving type and returnto
1418     *
1419     * @param string $text Link text
1420     * @param string $lang Language code
1421     * @return string
1422     */
1423    protected function makeLanguageSelectorLink( $text, $lang ) {
1424        $services = MediaWikiServices::getInstance();
1425
1426        if ( $this->getLanguage()->getCode() == $lang
1427            || !$services->getLanguageNameUtils()->isValidCode( $lang )
1428        ) {
1429            // no link for currently used language
1430            // or invalid language code
1431            return htmlspecialchars( $text );
1432        }
1433
1434        $query = $this->getPreservedParams();
1435        $query['uselang'] = $lang;
1436
1437        $attr = [];
1438        $targetLanguage = $services->getLanguageFactory()->getLanguage( $lang );
1439        $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1440        $attr['class'] = 'mw-authentication-popup-link';
1441        $attr['title'] = false;
1442
1443        return $this->getLinkRenderer()->makeKnownLink(
1444            $this->getPageTitle(),
1445            $text,
1446            $attr,
1447            $query
1448        );
1449    }
1450
1451    /** @inheritDoc */
1452    protected function getGroupName() {
1453        return 'login';
1454    }
1455
1456    /**
1457     * @param array &$formDescriptor
1458     * @param array $requests
1459     */
1460    protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1461        // Pre-fill username (if not creating an account, T46775).
1462        if (
1463            isset( $formDescriptor['username'] ) &&
1464            !isset( $formDescriptor['username']['default'] ) &&
1465            !$this->isSignup()
1466        ) {
1467            $user = $this->getUser();
1468            if ( $user->isRegistered() && !$user->isTemp() ) {
1469                $formDescriptor['username']['default'] = $user->getName();
1470            } else {
1471                $formDescriptor['username']['default'] =
1472                    $this->getRequest()->getSession()->suggestLoginUsername();
1473            }
1474        }
1475
1476        // don't show a submit button if there is nothing to submit (i.e. the only form content
1477        // is other submit buttons, for redirect flows)
1478        if ( !$this->needsSubmitButton( $requests ) ) {
1479            unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1480        }
1481
1482        if ( $this->getUser()->isNamed() && !$this->isContinued() && !$this->securityLevel ) {
1483            // Remove 'primary' flag from the default form submission button if the user is already logged in
1484            if ( isset( $formDescriptor['createaccount'] ) ) {
1485                $formDescriptor['createaccount']['flags'] = [ 'progressive' ];
1486            }
1487            if ( isset( $formDescriptor['loginattempt'] ) ) {
1488                $formDescriptor['loginattempt']['flags'] = [ 'progressive' ];
1489            }
1490        }
1491
1492        if ( !$this->isSignup() ) {
1493            // FIXME HACK don't focus on non-empty field
1494            // maybe there should be an autofocus-if similar to hide-if?
1495            if (
1496                isset( $formDescriptor['username'] )
1497                && empty( $formDescriptor['username']['default'] )
1498                && !$this->getRequest()->getCheck( 'wpName' )
1499            ) {
1500                $formDescriptor['username']['autofocus'] = true;
1501            } elseif ( isset( $formDescriptor['password'] ) ) {
1502                $formDescriptor['password']['autofocus'] = true;
1503            }
1504        }
1505
1506        $this->addTabIndex( $formDescriptor );
1507    }
1508
1509    /**
1510     * Generates the HTML for a notice box to be displayed to a temporary user.
1511     *
1512     * @return string HTML representing the notice box
1513     */
1514    protected function getNoticeHtml() {
1515        $noticeContent = $this->msg( 'createacct-temp-warning', $this->getUser()->getName() )->parse();
1516        return Html::noticeBox(
1517            $noticeContent,
1518            'mw-createaccount-temp-warning',
1519            '',
1520            'mw-userLogin-icon--user-temporary'
1521        );
1522    }
1523
1524}
1525
1526// @codeCoverageIgnoreStart
1527/** @deprecated class alias since 1.41 */
1528class_alias( LoginSignupSpecialPage::class, 'LoginSignupSpecialPage' );
1529// @codeCoverageIgnoreEnd