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