Merge "Move PECL memcached class to /libs"
[lhc/web/wiklou.git] / includes / specialpage / LoginSignupSpecialPage.php
1 <?php
2 /**
3 * Holds shared logic for login and account creation pages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\Auth\AuthenticationRequest;
25 use MediaWiki\Auth\AuthenticationResponse;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\Throttler;
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\Session\SessionManager;
30
31 /**
32 * Holds shared logic for login and account creation pages.
33 *
34 * @ingroup SpecialPage
35 */
36 abstract class LoginSignupSpecialPage extends AuthManagerSpecialPage {
37 protected $mReturnTo;
38 protected $mPosted;
39 protected $mAction;
40 protected $mLanguage;
41 protected $mReturnToQuery;
42 protected $mToken;
43 protected $mStickHTTPS;
44 protected $mFromHTTP;
45 protected $mEntryError = '';
46 protected $mEntryErrorType = 'error';
47
48 protected $mLoaded = false;
49 protected $mLoadedRequest = false;
50 protected $mSecureLoginUrl;
51
52 /** @var string */
53 protected $securityLevel;
54
55 /** @var bool True if the user if creating an account for someone else. Flag used for internal
56 * communication, only set at the very end. */
57 protected $proxyAccountCreation;
58 /** @var User FIXME another flag for passing data. */
59 protected $targetUser;
60
61 /** @var HTMLForm */
62 protected $authForm;
63
64 /** @var FakeAuthTemplate */
65 protected $fakeTemplate;
66
67 abstract protected function isSignup();
68
69 /**
70 * @param bool $direct True if the action was successful just now; false if that happened
71 * pre-redirection (so this handler was called already)
72 * @param StatusValue|null $extraMessages
73 * @return void
74 */
75 abstract protected function successfulAction( $direct = false, $extraMessages = null );
76
77 /**
78 * Logs to the authmanager-stats channel.
79 * @param bool $success
80 * @param string|null $status Error message key
81 */
82 abstract protected function logAuthResult( $success, $status = null );
83
84 public function __construct( $name ) {
85 global $wgUseMediaWikiUIEverywhere;
86 parent::__construct( $name );
87
88 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
89 $wgUseMediaWikiUIEverywhere = true;
90 }
91
92 protected function setRequest( array $data, $wasPosted = null ) {
93 parent::setRequest( $data, $wasPosted );
94 $this->mLoadedRequest = false;
95 }
96
97 /**
98 * Load basic request parameters for this Special page.
99 * @param $subPage
100 */
101 private function loadRequestParameters( $subPage ) {
102 if ( $this->mLoadedRequest ) {
103 return;
104 }
105 $this->mLoadedRequest = true;
106 $request = $this->getRequest();
107
108 $this->mPosted = $request->wasPosted();
109 $this->mIsReturn = $subPage === 'return';
110 $this->mAction = $request->getVal( 'action' );
111 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
112 || $request->getBool( 'wpFromhttp', false );
113 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
114 || $request->getBool( 'wpForceHttps', false );
115 $this->mLanguage = $request->getText( 'uselang' );
116 $this->mReturnTo = $request->getVal( 'returnto', '' );
117 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
118 }
119
120 /**
121 * Load data from request.
122 * @private
123 * @param string $subPage Subpage of Special:Userlogin
124 */
125 protected function load( $subPage ) {
126 global $wgSecureLogin;
127
128 $this->loadRequestParameters( $subPage );
129 if ( $this->mLoaded ) {
130 return;
131 }
132 $this->mLoaded = true;
133 $request = $this->getRequest();
134
135 $securityLevel = $this->getRequest()->getText( 'force' );
136 if (
137 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
138 $securityLevel ) === AuthManager::SEC_REAUTH
139 ) {
140 $this->securityLevel = $securityLevel;
141 }
142
143 $this->loadAuth( $subPage );
144
145 $this->mToken = $request->getVal( $this->getTokenName() );
146
147 // Show an error or warning passed on from a previous page
148 $entryError = $this->msg( $request->getVal( 'error', '' ) );
149 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
150 // bc: provide login link as a parameter for messages where the translation
151 // was not updated
152 $loginreqlink = Linker::linkKnown(
153 $this->getPageTitle(),
154 $this->msg( 'loginreqlink' )->escaped(),
155 [],
156 [
157 'returnto' => $this->mReturnTo,
158 'returntoquery' => $this->mReturnToQuery,
159 'uselang' => $this->mLanguage,
160 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
161 ]
162 );
163
164 // Only show valid error or warning messages.
165 if ( $entryError->exists()
166 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
167 ) {
168 $this->mEntryErrorType = 'error';
169 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
170
171 } elseif ( $entryWarning->exists()
172 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
173 ) {
174 $this->mEntryErrorType = 'warning';
175 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
176 }
177
178 # 1. When switching accounts, it sucks to get automatically logged out
179 # 2. Do not return to PasswordReset after a successful password change
180 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
181 $returnToTitle = Title::newFromText( $this->mReturnTo );
182 if ( is_object( $returnToTitle )
183 && ( $returnToTitle->isSpecial( 'Userlogout' )
184 || $returnToTitle->isSpecial( 'PasswordReset' ) )
185 ) {
186 $this->mReturnTo = '';
187 $this->mReturnToQuery = '';
188 }
189 }
190
191 protected function getPreservedParams( $withToken = false ) {
192 global $wgSecureLogin;
193
194 $params = parent::getPreservedParams( $withToken );
195 $params += [
196 'returnto' => $this->mReturnTo ?: null,
197 'returntoquery' => $this->mReturnToQuery ?: null,
198 ];
199 if ( $wgSecureLogin && !$this->isSignup() ) {
200 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
201 }
202 return $params;
203 }
204
205 protected function beforeExecute( $subPage ) {
206 // finish initializing the class before processing the request - T135924
207 $this->loadRequestParameters( $subPage );
208 return parent::beforeExecute( $subPage );
209 }
210
211 /**
212 * @param string|null $subPage
213 */
214 public function execute( $subPage ) {
215 $authManager = AuthManager::singleton();
216 $session = SessionManager::getGlobalSession();
217
218 // Session data is used for various things in the authentication process, so we must make
219 // sure a session cookie or some equivalent mechanism is set.
220 $session->persist();
221
222 $this->load( $subPage );
223 $this->setHeaders();
224 $this->checkPermissions();
225
226 // Make sure the system configuration allows log in / sign up
227 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
228 if ( !$session->canSetUser() ) {
229 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
230 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
231 ] );
232 }
233 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
234 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
235 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
236 }
237
238 /*
239 * In the case where the user is already logged in, and was redirected to
240 * the login form from a page that requires login, do not show the login
241 * page. The use case scenario for this is when a user opens a large number
242 * of tabs, is redirected to the login page on all of them, and then logs
243 * in on one, expecting all the others to work properly.
244 *
245 * However, do show the form if it was visited intentionally (no 'returnto'
246 * is present). People who often switch between several accounts have grown
247 * accustomed to this behavior.
248 *
249 * Also make an exception when force=<level> is set in the URL, which means the user must
250 * reauthenticate for security reasons.
251 */
252 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
253 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
254 $this->getUser()->isLoggedIn()
255 ) {
256 $this->successfulAction();
257 }
258
259 // If logging in and not on HTTPS, either redirect to it or offer a link.
260 global $wgSecureLogin;
261 if ( $this->getRequest()->getProtocol() !== 'https' ) {
262 $title = $this->getFullTitle();
263 $query = $this->getPreservedParams( false ) + [
264 'title' => null,
265 ( $this->mEntryErrorType === 'error' ? 'error'
266 : 'warning' ) => $this->mEntryError,
267 ] + $this->getRequest()->getQueryValues();
268 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
269 if ( $wgSecureLogin && !$this->mFromHTTP &&
270 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
271 ) {
272 // Avoid infinite redirect
273 $url = wfAppendQuery( $url, 'fromhttp=1' );
274 $this->getOutput()->redirect( $url );
275 // Since we only do this redir to change proto, always vary
276 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
277
278 return;
279 } else {
280 // A wiki without HTTPS login support should set $wgServer to
281 // http://somehost, in which case the secure URL generated
282 // above won't actually start with https://
283 if ( substr( $url, 0, 8 ) === 'https://' ) {
284 $this->mSecureLoginUrl = $url;
285 }
286 }
287 }
288
289 if ( !$this->isActionAllowed( $this->authAction ) ) {
290 // FIXME how do we explain this to the user? can we handle session loss better?
291 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
292 // authpage-cannot-create, authpage-cannot-create-continue
293 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
294 return;
295 }
296
297 $status = $this->trySubmit();
298
299 if ( !$status || !$status->isGood() ) {
300 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
301 return;
302 }
303
304 /** @var AuthenticationResponse $response */
305 $response = $status->getValue();
306
307 $returnToUrl = $this->getPageTitle( 'return' )
308 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
309 switch ( $response->status ) {
310 case AuthenticationResponse::PASS:
311 $this->logAuthResult( true );
312 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
313 $this->targetUser = User::newFromName( $response->username );
314
315 if (
316 !$this->proxyAccountCreation
317 && $response->loginRequest
318 && $authManager->canAuthenticateNow()
319 ) {
320 // successful registration; log the user in instantly
321 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
322 $returnToUrl );
323 if ( $response2->status !== AuthenticationResponse::PASS ) {
324 LoggerFactory::getInstance( 'login' )
325 ->error( 'Could not log in after account creation' );
326 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
327 break;
328 }
329 }
330
331 if ( !$this->proxyAccountCreation ) {
332 // Ensure that the context user is the same as the session user.
333 $this->setSessionUserForCurrentRequest();
334 }
335
336 $this->successfulAction( true );
337 break;
338 case AuthenticationResponse::FAIL:
339 // fall through
340 case AuthenticationResponse::RESTART:
341 unset( $this->authForm );
342 if ( $response->status === AuthenticationResponse::FAIL ) {
343 $action = $this->getDefaultAction( $subPage );
344 $messageType = 'error';
345 } else {
346 $action = $this->getContinueAction( $this->authAction );
347 $messageType = 'warning';
348 }
349 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
350 $this->loadAuth( $subPage, $action, true );
351 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
352 break;
353 case AuthenticationResponse::REDIRECT:
354 unset( $this->authForm );
355 $this->getOutput()->redirect( $response->redirectTarget );
356 break;
357 case AuthenticationResponse::UI:
358 unset( $this->authForm );
359 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
360 : AuthManager::ACTION_LOGIN_CONTINUE;
361 $this->authRequests = $response->neededRequests;
362 $this->mainLoginForm( $response->neededRequests, $response->message, 'warning' );
363 break;
364 default:
365 throw new LogicException( 'invalid AuthenticationResponse' );
366 }
367 }
368
369 /**
370 * Show the success page.
371 *
372 * @param string $type Condition of return to; see `executeReturnTo`
373 * @param string|Message $title Page's title
374 * @param string $msgname
375 * @param string $injected_html
376 * @param StatusValue|null $extraMessages
377 */
378 protected function showSuccessPage(
379 $type, $title, $msgname, $injected_html, $extraMessages
380 ) {
381 $out = $this->getOutput();
382 $out->setPageTitle( $title );
383 if ( $msgname ) {
384 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
385 }
386 if ( $extraMessages ) {
387 $extraMessages = Status::wrap( $extraMessages );
388 $out->addWikiText( $extraMessages->getWikiText() );
389 }
390
391 $out->addHTML( $injected_html );
392
393 $helper = new LoginHelper( $this->getContext() );
394 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
395 }
396
397 /**
398 * Add a "return to" link or redirect to it.
399 * Extensions can use this to reuse the "return to" logic after
400 * inject steps (such as redirection) into the login process.
401 *
402 * @param string $type One of the following:
403 * - error: display a return to link ignoring $wgRedirectOnLogin
404 * - signup: display a return to link using $wgRedirectOnLogin if needed
405 * - success: display a return to link using $wgRedirectOnLogin if needed
406 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
407 * @param string $returnTo
408 * @param array|string $returnToQuery
409 * @param bool $stickHTTPS Keep redirect link on HTTPS
410 * @since 1.22
411 */
412 public function showReturnToPage(
413 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
414 ) {
415 $helper = new LoginHelper( $this->getContext() );
416 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
417 }
418
419 /**
420 * Replace some globals to make sure the fact that the user has just been logged in is
421 * reflected in the current request.
422 * @param User $user
423 */
424 protected function setSessionUserForCurrentRequest() {
425 global $wgUser, $wgLang;
426
427 $context = RequestContext::getMain();
428 $localContext = $this->getContext();
429 if ( $context !== $localContext ) {
430 // remove AuthManagerSpecialPage context hack
431 $this->setContext( $context );
432 }
433
434 $user = $context->getRequest()->getSession()->getUser();
435
436 $wgUser = $user;
437 $context->setUser( $user );
438
439 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
440 $userLang = Language::factory( $code );
441 $wgLang = $userLang;
442 $context->setLanguage( $userLang );
443 }
444
445 /**
446 * @param AuthenticationRequest[] $requests A list of AuthorizationRequest objects,
447 * used to generate the form fields. An empty array means a fatal error
448 * (authentication cannot continue).
449 * @param string|Message $msg
450 * @param string $msgtype
451 * @throws ErrorPageError
452 * @throws Exception
453 * @throws FatalError
454 * @throws MWException
455 * @throws PermissionsError
456 * @throws ReadOnlyError
457 * @private
458 */
459 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
460 $titleObj = $this->getPageTitle();
461 $user = $this->getUser();
462 $out = $this->getOutput();
463
464 // FIXME how to handle empty $requests - restart, or no form, just an error message?
465 // no form would be better for no session type errors, restart is better when can* fails.
466 if ( !$requests ) {
467 $this->authAction = $this->getDefaultAction( $this->subPage );
468 $this->authForm = null;
469 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
470 }
471
472 // Generic styles and scripts for both login and signup form
473 $out->addModuleStyles( [
474 'mediawiki.ui',
475 'mediawiki.ui.button',
476 'mediawiki.ui.checkbox',
477 'mediawiki.ui.input',
478 'mediawiki.special.userlogin.common.styles'
479 ] );
480 if ( $this->isSignup() ) {
481 // XXX hack pending RL or JS parse() support for complex content messages T27349
482 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
483 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
484
485 // Additional styles and scripts for signup form
486 $out->addModules( [
487 'mediawiki.special.userlogin.signup.js'
488 ] );
489 $out->addModuleStyles( [
490 'mediawiki.special.userlogin.signup.styles'
491 ] );
492 } else {
493 // Additional styles for login form
494 $out->addModuleStyles( [
495 'mediawiki.special.userlogin.login.styles'
496 ] );
497 }
498 $out->disallowUserJs(); // just in case...
499
500 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
501 $form->prepareForm();
502 $formHtml = $form->getHTML( $msg ? Status::newFatal( $msg ) : false );
503
504 $out->addHTML( $this->getPageHtml( $formHtml ) );
505 }
506
507 /**
508 * Add page elements which are outside the form.
509 * FIXME this should probably be a template, but use a sane language (handlebars?)
510 * @param string $formHtml
511 * @return string
512 */
513 protected function getPageHtml( $formHtml ) {
514 global $wgLoginLanguageSelector;
515
516 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
517 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
518 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
519 $signupStartMsg = $this->msg( 'signupstart' );
520 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
521 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
522 if ( $languageLinks ) {
523 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
524 Html::rawElement( 'p', [], $languageLinks )
525 );
526 }
527
528 $benefitsContainer = '';
529 if ( $this->isSignup() && $this->showExtraInformation() ) {
530 // messages used:
531 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
532 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
533 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
534 $benefitCount = 3;
535 $benefitList = '';
536 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
537 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
538 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
539 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
540 Html::rawElement( 'h3', [],
541 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
542 )
543 . Html::rawElement( 'p', [],
544 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
545 )
546 );
547 }
548 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
549 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
550 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
551 $benefitList
552 )
553 );
554 }
555
556 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
557 $loginPrompt
558 . $languageLinks
559 . $signupStart
560 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
561 $formHtml
562 )
563 . $benefitsContainer
564 );
565
566 return $html;
567 }
568
569 /**
570 * Generates a form from the given request.
571 * @param AuthenticationRequest[] $requests
572 * @param string $action AuthManager action name
573 * @param string|Message $msg
574 * @param string $msgType
575 * @return HTMLForm
576 */
577 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
578 global $wgSecureLogin, $wgLoginLanguageSelector;
579 // FIXME merge this with parent
580
581 if ( isset( $this->authForm ) ) {
582 return $this->authForm;
583 }
584
585 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
586
587 // get basic form description from the auth logic
588 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
589 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
590 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
591 // this will call onAuthChangeFormFields()
592 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
593 $this->postProcessFormDescriptor( $formDescriptor, $requests );
594
595 $context = $this->getContext();
596 if ( $context->getRequest() !== $this->getRequest() ) {
597 // We have overridden the request, need to make sure the form uses that too.
598 $context = new DerivativeContext( $this->getContext() );
599 $context->setRequest( $this->getRequest() );
600 }
601 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
602
603 $form->addHiddenField( 'authAction', $this->authAction );
604 if ( $wgLoginLanguageSelector ) {
605 $form->addHiddenField( 'uselang', $this->mLanguage );
606 }
607 $form->addHiddenField( 'force', $this->securityLevel );
608 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
609 if ( $wgSecureLogin ) {
610 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
611 if ( !$this->isSignup() ) {
612 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
613 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
614 }
615 }
616
617 // set properties of the form itself
618 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
619 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
620 if ( $this->isSignup() ) {
621 $form->setId( 'userlogin2' );
622 }
623
624 // warning header for non-standard workflows (e.g. security reauthentication)
625 if ( !$this->isSignup() && $this->getUser()->isLoggedIn() ) {
626 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
627 $form->addHeaderText( Html::rawElement( 'div', [ 'class' => 'warningbox' ],
628 $this->msg( $reauthMessage )->params( $this->getUser()->getName() )->parse() ) );
629 }
630
631 $form->suppressDefaultSubmit();
632
633 $this->authForm = $form;
634
635 return $form;
636 }
637
638 /**
639 * Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
640 * @param string|Message $msg
641 * @param string $msgType
642 * @return FakeAuthTemplate
643 */
644 protected function getFakeTemplate( $msg, $msgType ) {
645 global $wgAuth, $wgEnableEmail, $wgHiddenPrefs, $wgEmailConfirmToEdit, $wgEnableUserEmail,
646 $wgSecureLogin, $wgLoginLanguageSelector, $wgPasswordResetRoutes;
647
648 // make a best effort to get the value of fields which used to be fixed in the old login
649 // template but now might or might not exist depending on what providers are used
650 $request = $this->getRequest();
651 $data = (object) [
652 'mUsername' => $request->getText( 'wpName' ),
653 'mPassword' => $request->getText( 'wpPassword' ),
654 'mRetype' => $request->getText( 'wpRetype' ),
655 'mEmail' => $request->getText( 'wpEmail' ),
656 'mRealName' => $request->getText( 'wpRealName' ),
657 'mDomain' => $request->getText( 'wpDomain' ),
658 'mReason' => $request->getText( 'wpReason' ),
659 'mRemember' => $request->getCheck( 'wpRemember' ),
660 ];
661
662 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
663 // There is no code reuse to make this easier to remove .
664 // If an extension tries to change any of these values, they are out of luck - we only
665 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
666
667 $titleObj = $this->getPageTitle();
668 $user = $this->getUser();
669 $template = new FakeAuthTemplate();
670
671 // Pre-fill username (if not creating an account, bug 44775).
672 if ( $data->mUsername == '' && $this->isSignup() ) {
673 if ( $user->isLoggedIn() ) {
674 $data->mUsername = $user->getName();
675 } else {
676 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
677 }
678 }
679
680 if ( $this->isSignup() ) {
681 // Must match number of benefits defined in messages
682 $template->set( 'benefitCount', 3 );
683
684 $q = 'action=submitlogin&type=signup';
685 $linkq = 'type=login';
686 } else {
687 $q = 'action=submitlogin&type=login';
688 $linkq = 'type=signup';
689 }
690
691 if ( $this->mReturnTo !== '' ) {
692 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
693 if ( $this->mReturnToQuery !== '' ) {
694 $returnto .= '&returntoquery=' .
695 wfUrlencode( $this->mReturnToQuery );
696 }
697 $q .= $returnto;
698 $linkq .= $returnto;
699 }
700
701 # Don't show a "create account" link if the user can't.
702 if ( $this->showCreateAccountLink() ) {
703 # Pass any language selection on to the mode switch link
704 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
705 $linkq .= '&uselang=' . $this->mLanguage;
706 }
707 // Supply URL, login template creates the button.
708 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
709 } else {
710 $template->set( 'link', '' );
711 }
712
713 $resetLink = $this->isSignup()
714 ? null
715 : is_array( $wgPasswordResetRoutes )
716 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
717
718 $template->set( 'header', '' );
719 $template->set( 'formheader', '' );
720 $template->set( 'skin', $this->getSkin() );
721
722 $template->set( 'name', $data->mUsername );
723 $template->set( 'password', $data->mPassword );
724 $template->set( 'retype', $data->mRetype );
725 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
726 $template->set( 'email', $data->mEmail );
727 $template->set( 'realname', $data->mRealName );
728 $template->set( 'domain', $data->mDomain );
729 $template->set( 'reason', $data->mReason );
730 $template->set( 'remember', $data->mRemember );
731
732 $template->set( 'action', $titleObj->getLocalURL( $q ) );
733 $template->set( 'message', $msg );
734 $template->set( 'messagetype', $msgType );
735 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
736 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
737 $template->set( 'useemail', $wgEnableEmail );
738 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
739 $template->set( 'emailothers', $wgEnableUserEmail );
740 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
741 $template->set( 'resetlink', $resetLink );
742 $template->set( 'canremember', $request->getSession()->getProvider()
743 ->getRememberUserDuration() !== null );
744 $template->set( 'usereason', $user->isLoggedIn() );
745 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
746 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
747 $template->set( 'loggedin', $user->isLoggedIn() );
748 $template->set( 'loggedinuser', $user->getName() );
749 $template->set( 'token', $this->getToken()->toString() );
750
751 $action = $this->isSignup() ? 'signup' : 'login';
752 $wgAuth->modifyUITemplate( $template, $action );
753
754 $oldTemplate = $template;
755 $hookName = $this->isSignup() ? 'UserCreateForm' : 'UserLoginForm';
756 Hooks::run( $hookName, [ &$template ] );
757 if ( $oldTemplate !== $template ) {
758 wfDeprecated( "reference in $hookName hook", '1.27' );
759 }
760
761 return $template;
762
763 }
764
765 public function onAuthChangeFormFields(
766 array $requests, array $fieldInfo, array &$formDescriptor, $action
767 ) {
768 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
769 $specialFields = array_merge( [ 'extraInput' ],
770 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
771
772 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
773 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
774 $requestField = isset( $formDescriptor[$fieldName] ) ?
775 $formDescriptor[$fieldName] : [];
776
777 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
778 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
779 // and is not an info field or a submit button
780 if (
781 !isset( $fieldInfo[$fieldName] )
782 && (
783 !isset( $coreField['baseField'] )
784 || !isset( $fieldInfo[$coreField['baseField']] )
785 )
786 && !in_array( $fieldName, $specialFields, true )
787 && (
788 !isset( $coreField['type'] )
789 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
790 )
791 ) {
792 $coreFieldDescriptors[$fieldName] = null;
793 continue;
794 }
795
796 // core message labels should always take priority
797 if (
798 isset( $coreField['label'] )
799 || isset( $coreField['label-message'] )
800 || isset( $coreField['label-raw'] )
801 ) {
802 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
803 }
804
805 $coreFieldDescriptors[$fieldName] += $requestField;
806 }
807
808 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
809 return true;
810 }
811
812 /**
813 * Show extra information such as password recovery information, link from login to signup,
814 * CTA etc? Such information should only be shown on the "landing page", ie. when the user
815 * is at the first step of the authentication process.
816 * @return bool
817 */
818 protected function showExtraInformation() {
819 return $this->authAction !== $this->getContinueAction( $this->authAction )
820 && !$this->securityLevel;
821 }
822
823 /**
824 * Create a HTMLForm descriptor for the core login fields.
825 * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions)
826 * @return array
827 */
828 protected function getFieldDefinitions( $template ) {
829 global $wgEmailConfirmToEdit, $wgLoginLanguageSelector;
830
831 $isLoggedIn = $this->getUser()->isLoggedIn();
832 $continuePart = $this->isContinued() ? 'continue-' : '';
833 $anotherPart = $isLoggedIn ? 'another-' : '';
834 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
835 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
836 $secureLoginLink = '';
837 if ( $this->mSecureLoginUrl ) {
838 $secureLoginLink = Html::element( 'a', [
839 'href' => $this->mSecureLoginUrl,
840 'class' => 'mw-ui-flush-right mw-secure',
841 ], $this->msg( 'userlogin-signwithsecure' )->text() );
842 }
843 $usernameHelpLink = '';
844 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
845 $usernameHelpLink = Html::rawElement( 'span', [
846 'class' => 'mw-ui-flush-right',
847 ], $this->msg( 'createacct-helpusername' )->parse() );
848 }
849
850 if ( $this->isSignup() ) {
851 $fieldDefinitions = [
852 'statusarea' => [
853 // used by the mediawiki.special.userlogin.signup.js module for error display
854 // FIXME merge this with HTMLForm's normal status (error) area
855 'type' => 'info',
856 'raw' => true,
857 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
858 'weight' => -105,
859 ],
860 'username' => [
861 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
862 'id' => 'wpName2',
863 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
864 : 'userlogin-yourname-ph',
865 ],
866 'mailpassword' => [
867 // create account without providing password, a temporary one will be mailed
868 'type' => 'check',
869 'label-message' => 'createaccountmail',
870 'name' => 'wpCreateaccountMail',
871 'id' => 'wpCreateaccountMail',
872 ],
873 'password' => [
874 'id' => 'wpPassword2',
875 'placeholder-message' => 'createacct-yourpassword-ph',
876 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
877 ],
878 'domain' => [],
879 'retype' => [
880 'baseField' => 'password',
881 'type' => 'password',
882 'label-message' => 'createacct-yourpasswordagain',
883 'id' => 'wpRetype',
884 'cssclass' => 'loginPassword',
885 'size' => 20,
886 'validation-callback' => function ( $value, $alldata ) {
887 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
888 if ( !$value ) {
889 return $this->msg( 'htmlform-required' );
890 } elseif ( $value !== $alldata['password'] ) {
891 return $this->msg( 'badretype' );
892 }
893 }
894 return true;
895 },
896 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
897 'placeholder-message' => 'createacct-yourpasswordagain-ph',
898 ],
899 'email' => [
900 'type' => 'email',
901 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
902 : 'createacct-emailoptional',
903 'id' => 'wpEmail',
904 'cssclass' => 'loginText',
905 'size' => '20',
906 // FIXME will break non-standard providers
907 'required' => $wgEmailConfirmToEdit,
908 'validation-callback' => function ( $value, $alldata ) {
909 global $wgEmailConfirmToEdit;
910
911 // AuthManager will check most of these, but that will make the auth
912 // session fail and this won't, so nicer to do it this way
913 if ( !$value && $wgEmailConfirmToEdit ) {
914 // no point in allowing registration without email when email is
915 // required to edit
916 return $this->msg( 'noemailtitle' );
917 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
918 // cannot send password via email when there is no email address
919 return $this->msg( 'noemailcreate' );
920 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
921 return $this->msg( 'invalidemailaddress' );
922 }
923 return true;
924 },
925 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
926 ],
927 'realname' => [
928 'type' => 'text',
929 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
930 : 'prefs-help-realname',
931 'label-message' => 'createacct-realname',
932 'cssclass' => 'loginText',
933 'size' => 20,
934 'id' => 'wpRealName',
935 ],
936 'reason' => [
937 // comment for the user creation log
938 'type' => 'text',
939 'label-message' => 'createacct-reason',
940 'cssclass' => 'loginText',
941 'id' => 'wpReason',
942 'size' => '20',
943 'placeholder-message' => 'createacct-reason-ph',
944 ],
945 'extrainput' => [], // placeholder for fields coming from the template
946 'createaccount' => [
947 // submit button
948 'type' => 'submit',
949 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
950 'submit' )->text(),
951 'name' => 'wpCreateaccount',
952 'id' => 'wpCreateaccount',
953 'weight' => 100,
954 ],
955 ];
956 } else {
957 $fieldDefinitions = [
958 'username' => [
959 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
960 'id' => 'wpName1',
961 'placeholder-message' => 'userlogin-yourname-ph',
962 ],
963 'password' => [
964 'id' => 'wpPassword1',
965 'placeholder-message' => 'userlogin-yourpassword-ph',
966 ],
967 'domain' => [],
968 'extrainput' => [],
969 'rememberMe' => [
970 // option for saving the user token to a cookie
971 'type' => 'check',
972 'name' => 'wpRemember',
973 'label-message' => $this->msg( 'userlogin-remembermypassword' )
974 ->numParams( $expirationDays ),
975 'id' => 'wpRemember',
976 ],
977 'loginattempt' => [
978 // submit button
979 'type' => 'submit',
980 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
981 'id' => 'wpLoginAttempt',
982 'weight' => 100,
983 ],
984 'linkcontainer' => [
985 // help link
986 'type' => 'info',
987 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
988 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
989 'raw' => true,
990 'default' => Html::element( 'a', [
991 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
992 ->inContentLanguage()
993 ->text() ),
994 ], $this->msg( 'userlogin-helplink2' )->text() ),
995 'weight' => 200,
996 ],
997 // button for ResetPasswordSecondaryAuthenticationProvider
998 'skipReset' => [
999 'weight' => 110,
1000 'flags' => [],
1001 ],
1002 ];
1003 }
1004
1005 $fieldDefinitions['username'] += [
1006 'type' => 'text',
1007 'name' => 'wpName',
1008 'cssclass' => 'loginText',
1009 'size' => 20,
1010 // 'required' => true,
1011 ];
1012 $fieldDefinitions['password'] += [
1013 'type' => 'password',
1014 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1015 'name' => 'wpPassword',
1016 'cssclass' => 'loginPassword',
1017 'size' => 20,
1018 // 'required' => true,
1019 ];
1020
1021 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1022 // B/C for old extensions that haven't been converted to AuthManager (or have been
1023 // but somebody is using the old version) and still use templates via the
1024 // UserCreateForm/UserLoginForm hook.
1025 // 'header' used by ConfirmEdit, CondfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1026 // 'formheader' used by MobileFrontend
1027 $fieldDefinitions['header'] = [
1028 'type' => 'info',
1029 'raw' => true,
1030 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1031 'weight' => - 110,
1032 ];
1033 }
1034 if ( $this->mEntryError ) {
1035 $fieldDefinitions['entryError'] = [
1036 'type' => 'info',
1037 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1038 $this->mEntryError ),
1039 'raw' => true,
1040 'rawrow' => true,
1041 'weight' => -100,
1042 ];
1043 }
1044 if ( !$this->showExtraInformation() ) {
1045 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1046 }
1047 if ( $this->isSignup() && $this->showExtraInformation() ) {
1048 // blank signup footer for site customization
1049 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1050 $signupendMsg = $this->msg( 'signupend' );
1051 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1052 if ( !$signupendMsg->isDisabled() ) {
1053 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1054 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1055 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1056 $fieldDefinitions['signupend'] = [
1057 'type' => 'info',
1058 'raw' => true,
1059 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1060 'weight' => 225,
1061 ];
1062 }
1063 }
1064 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1065 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1066 if ( $passwordReset->isAllowed( $this->getUser() ) ) {
1067 $fieldDefinitions['passwordReset'] = [
1068 'type' => 'info',
1069 'raw' => true,
1070 'cssclass' => 'mw-form-related-link-container',
1071 'default' => Linker::link(
1072 SpecialPage::getTitleFor( 'PasswordReset' ),
1073 $this->msg( 'userlogin-resetpassword-link' )->escaped()
1074 ),
1075 'weight' => 230,
1076 ];
1077 }
1078
1079 // Don't show a "create account" link if the user can't.
1080 if ( $this->showCreateAccountLink() ) {
1081 // link to the other action
1082 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' :'CreateAccount' );
1083 $linkq = $this->getReturnToQueryStringFragment();
1084 // Pass any language selection on to the mode switch link
1085 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1086 $linkq .= '&uselang=' . $this->mLanguage;
1087 }
1088 $loggedIn = $this->getUser()->isLoggedIn();
1089
1090 $fieldDefinitions['createOrLogin'] = [
1091 'type' => 'info',
1092 'raw' => true,
1093 'linkQuery' => $linkq,
1094 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1095 return Html::rawElement( 'div',
1096 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1097 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1098 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1099 . Html::element( 'a',
1100 [
1101 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1102 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1103 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1104 'tabindex' => 100,
1105 ],
1106 $this->msg(
1107 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1108 )->escaped()
1109 )
1110 );
1111 },
1112 'weight' => 235,
1113 ];
1114 }
1115 }
1116
1117 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1118 $fieldDefinitions = array_filter( $fieldDefinitions );
1119
1120 return $fieldDefinitions;
1121 }
1122
1123 /**
1124 * Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks
1125 * @param $fieldDefinitions array
1126 * @param FakeAuthTemplate $template
1127 * @return array
1128 */
1129 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1130 if ( $template->get( 'usedomain', false ) ) {
1131 // TODO probably should be translated to the new domain notation in AuthManager
1132 $fieldDefinitions['domain'] = [
1133 'type' => 'select',
1134 'label-message' => 'yourdomainname',
1135 'options' => array_combine( $template->get( 'domainnames', [] ),
1136 $template->get( 'domainnames', [] ) ),
1137 'default' => $template->get( 'domain', '' ),
1138 'name' => 'wpDomain',
1139 // FIXME id => 'mw-user-domain-section' on the parent div
1140 ];
1141 }
1142
1143 // poor man's associative array_splice
1144 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1145 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1146 + $template->getExtraInputDefinitions()
1147 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1148
1149 return $fieldDefinitions;
1150 }
1151
1152 /**
1153 * Check if a session cookie is present.
1154 *
1155 * This will not pick up a cookie set during _this_ request, but is meant
1156 * to ensure that the client is returning the cookie which was set on a
1157 * previous pass through the system.
1158 *
1159 * @return bool
1160 */
1161 protected function hasSessionCookie() {
1162 global $wgDisableCookieCheck, $wgInitialSessionId;
1163
1164 return $wgDisableCookieCheck || (
1165 $wgInitialSessionId &&
1166 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1167 );
1168 }
1169
1170 /**
1171 * Returns a string that can be appended to the URL (without encoding) to preserve the
1172 * return target. Does not include leading '?'/'&'.
1173 */
1174 protected function getReturnToQueryStringFragment() {
1175 $returnto = '';
1176 if ( $this->mReturnTo !== '' ) {
1177 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1178 if ( $this->mReturnToQuery !== '' ) {
1179 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1180 }
1181 }
1182 return $returnto;
1183 }
1184
1185 /**
1186 * Whether the login/create account form should display a link to the
1187 * other form (in addition to whatever the skin provides).
1188 * @return bool
1189 */
1190 private function showCreateAccountLink() {
1191 if ( $this->isSignup() ) {
1192 return true;
1193 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1194 return true;
1195 } else {
1196 return false;
1197 }
1198 }
1199
1200 protected function getTokenName() {
1201 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1202 }
1203
1204 /**
1205 * Produce a bar of links which allow the user to select another language
1206 * during login/registration but retain "returnto"
1207 *
1208 * @return string
1209 */
1210 protected function makeLanguageSelector() {
1211 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1212 if ( $msg->isBlank() ) {
1213 return '';
1214 }
1215 $langs = explode( "\n", $msg->text() );
1216 $links = [];
1217 foreach ( $langs as $lang ) {
1218 $lang = trim( $lang, '* ' );
1219 $parts = explode( '|', $lang );
1220 if ( count( $parts ) >= 2 ) {
1221 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1222 }
1223 }
1224
1225 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1226 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1227 }
1228
1229 /**
1230 * Create a language selector link for a particular language
1231 * Links back to this page preserving type and returnto
1232 *
1233 * @param string $text Link text
1234 * @param string $lang Language code
1235 * @return string
1236 */
1237 protected function makeLanguageSelectorLink( $text, $lang ) {
1238 if ( $this->getLanguage()->getCode() == $lang ) {
1239 // no link for currently used language
1240 return htmlspecialchars( $text );
1241 }
1242 $query = [ 'uselang' => $lang ];
1243 if ( $this->mReturnTo !== '' ) {
1244 $query['returnto'] = $this->mReturnTo;
1245 $query['returntoquery'] = $this->mReturnToQuery;
1246 }
1247
1248 $attr = [];
1249 $targetLanguage = Language::factory( $lang );
1250 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1251
1252 return Linker::linkKnown(
1253 $this->getPageTitle(),
1254 htmlspecialchars( $text ),
1255 $attr,
1256 $query
1257 );
1258 }
1259
1260 protected function getGroupName() {
1261 return 'login';
1262 }
1263
1264 /**
1265 * @param array $formDescriptor
1266 */
1267 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1268 // Pre-fill username (if not creating an account, T46775).
1269 if (
1270 isset( $formDescriptor['username'] ) &&
1271 !isset( $formDescriptor['username']['default'] ) &&
1272 !$this->isSignup()
1273 ) {
1274 $user = $this->getUser();
1275 if ( $user->isLoggedIn() ) {
1276 $formDescriptor['username']['default'] = $user->getName();
1277 } else {
1278 $formDescriptor['username']['default'] =
1279 $this->getRequest()->getSession()->suggestLoginUsername();
1280 }
1281 }
1282
1283 // don't show a submit button if there is nothing to submit (i.e. the only form content
1284 // is other submit buttons, for redirect flows)
1285 if ( !$this->needsSubmitButton( $requests ) ) {
1286 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1287 }
1288
1289 if ( !$this->isSignup() ) {
1290 // FIXME HACK don't focus on non-empty field
1291 // maybe there should be an autofocus-if similar to hide-if?
1292 if (
1293 isset( $formDescriptor['username'] )
1294 && empty( $formDescriptor['username']['default'] )
1295 && !$this->getRequest()->getCheck( 'wpName' )
1296 ) {
1297 $formDescriptor['username']['autofocus'] = true;
1298 } elseif ( isset( $formDescriptor['password'] ) ) {
1299 $formDescriptor['password']['autofocus'] = true;
1300 }
1301 }
1302
1303 $this->addTabIndex( $formDescriptor );
1304 }
1305 }
1306
1307 /**
1308 * B/C class to try handling login/signup template modifications even though login/signup does not
1309 * actually happen through a template anymore. Just collects extra field definitions and allows
1310 * some other class to do decide what to do with threm..
1311 * TODO find the right place for adding extra fields and kill this
1312 */
1313 class FakeAuthTemplate extends BaseTemplate {
1314 public function execute() {
1315 throw new LogicException( 'not used' );
1316 }
1317
1318 /**
1319 * Extensions (AntiSpoof and TitleBlacklist) call this in response to
1320 * UserCreateForm hook to add checkboxes to the create account form.
1321 */
1322 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1323 // use the same indexes as UserCreateForm just in case someone adds an item manually
1324 $this->data['extrainput'][] = [
1325 'name' => $name,
1326 'value' => $value,
1327 'type' => $type,
1328 'msg' => $msg,
1329 'helptext' => $helptext,
1330 ];
1331 }
1332
1333 /**
1334 * Turns addInputItem-style field definitions into HTMLForm field definitions.
1335 * @return array
1336 */
1337 public function getExtraInputDefinitions() {
1338 $definitions = [];
1339
1340 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1341 $definition = [
1342 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1343 'name' => $field['name'],
1344 'value' => $field['value'],
1345 'id' => $field['name'],
1346 ];
1347 if ( $field['msg'] ) {
1348 $definition['label-message'] = $this->getMsg( $field['msg'] );
1349 }
1350 if ( $field['helptext'] ) {
1351 $definition['help'] = $this->msgWiki( $field['helptext'] );
1352 }
1353
1354 // the array key doesn't matter much when name is defined explicitly but
1355 // let's try and follow HTMLForm conventions
1356 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1357 $definitions[$name] = $definition;
1358 }
1359
1360 if ( $this->haveData( 'extrafields' ) ) {
1361 $definitions['extrafields'] = [
1362 'type' => 'info',
1363 'raw' => true,
1364 'default' => $this->get( 'extrafields' ),
1365 ];
1366 }
1367
1368 return $definitions;
1369 }
1370 }
1371
1372 /**
1373 * LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,
1374 * but some extensions called its public methods directly, so the class is retained as a
1375 * B/C wrapper. Anything that used it before should use AuthManager instead.
1376 */
1377 class LoginForm extends SpecialPage {
1378 const SUCCESS = 0;
1379 const NO_NAME = 1;
1380 const ILLEGAL = 2;
1381 const WRONG_PLUGIN_PASS = 3;
1382 const NOT_EXISTS = 4;
1383 const WRONG_PASS = 5;
1384 const EMPTY_PASS = 6;
1385 const RESET_PASS = 7;
1386 const ABORTED = 8;
1387 const CREATE_BLOCKED = 9;
1388 const THROTTLED = 10;
1389 const USER_BLOCKED = 11;
1390 const NEED_TOKEN = 12;
1391 const WRONG_TOKEN = 13;
1392 const USER_MIGRATED = 14;
1393
1394 public static $statusCodes = [
1395 self::SUCCESS => 'success',
1396 self::NO_NAME => 'no_name',
1397 self::ILLEGAL => 'illegal',
1398 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1399 self::NOT_EXISTS => 'not_exists',
1400 self::WRONG_PASS => 'wrong_pass',
1401 self::EMPTY_PASS => 'empty_pass',
1402 self::RESET_PASS => 'reset_pass',
1403 self::ABORTED => 'aborted',
1404 self::CREATE_BLOCKED => 'create_blocked',
1405 self::THROTTLED => 'throttled',
1406 self::USER_BLOCKED => 'user_blocked',
1407 self::NEED_TOKEN => 'need_token',
1408 self::WRONG_TOKEN => 'wrong_token',
1409 self::USER_MIGRATED => 'user_migrated',
1410 ];
1411
1412 /**
1413 * @param WebRequest $request
1414 */
1415 public function __construct( $request = null ) {
1416 wfDeprecated( 'LoginForm', '1.27' );
1417 parent::__construct();
1418 }
1419
1420 /**
1421 * @deprecated since 1.27 - call LoginHelper::getValidErrorMessages instead.
1422 */
1423 public static function getValidErrorMessages() {
1424 return LoginHelper::getValidErrorMessages();
1425 }
1426
1427 /**
1428 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1429 */
1430 public static function incrementLoginThrottle( $username ) {
1431 wfDeprecated( __METHOD__, "1.27" );
1432 global $wgRequest;
1433 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1434 $throttler = new Throttler();
1435 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1436 }
1437
1438 /**
1439 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1440 */
1441 public static function incLoginThrottle( $username ) {
1442 wfDeprecated( __METHOD__, "1.27" );
1443 $res = self::incrementLoginThrottle( $username );
1444 return is_array( $res ) ? true : 0;
1445 }
1446
1447 /**
1448 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1449 */
1450 public static function clearLoginThrottle( $username ) {
1451 wfDeprecated( __METHOD__, "1.27" );
1452 global $wgRequest;
1453 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1454 $throttler = new Throttler();
1455 return $throttler->clear( $username, $wgRequest->getIP() );
1456 }
1457
1458 /**
1459 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1460 */
1461 public static function getLoginToken() {
1462 wfDeprecated( __METHOD__, '1.27' );
1463 global $wgRequest;
1464 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1465 }
1466
1467 /**
1468 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1469 */
1470 public static function setLoginToken() {
1471 wfDeprecated( __METHOD__, '1.27' );
1472 }
1473
1474 /**
1475 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1476 */
1477 public static function clearLoginToken() {
1478 wfDeprecated( __METHOD__, '1.27' );
1479 global $wgRequest;
1480 $wgRequest->getSession()->resetToken( 'login' );
1481 }
1482
1483 /**
1484 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1485 */
1486 public static function getCreateaccountToken() {
1487 wfDeprecated( __METHOD__, '1.27' );
1488 global $wgRequest;
1489 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1490 }
1491
1492 /**
1493 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1494 */
1495 public static function setCreateaccountToken() {
1496 wfDeprecated( __METHOD__, '1.27' );
1497 }
1498
1499 /**
1500 * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
1501 */
1502 public static function clearCreateaccountToken() {
1503 wfDeprecated( __METHOD__, '1.27' );
1504 global $wgRequest;
1505 $wgRequest->getSession()->resetToken( 'createaccount' );
1506 }
1507 }