MediaWiki REL1_30
LoginSignupSpecialPage.php
Go to the documentation of this file.
1<?php
31use Wikimedia\ScopedCallback;
32
39 protected $mReturnTo;
40 protected $mPosted;
41 protected $mAction;
42 protected $mLanguage;
43 protected $mReturnToQuery;
44 protected $mToken;
45 protected $mStickHTTPS;
46 protected $mFromHTTP;
47 protected $mEntryError = '';
48 protected $mEntryErrorType = 'error';
49
50 protected $mLoaded = false;
51 protected $mLoadedRequest = false;
53
55 protected $securityLevel;
56
61 protected $targetUser;
62
64 protected $authForm;
65
67 protected $fakeTemplate;
68
69 abstract protected function isSignup();
70
77 abstract protected function successfulAction( $direct = false, $extraMessages = null );
78
84 abstract protected function logAuthResult( $success, $status = null );
85
86 public function __construct( $name ) {
88 parent::__construct( $name );
89
90 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
92 }
93
94 protected function setRequest( array $data, $wasPosted = null ) {
95 parent::setRequest( $data, $wasPosted );
96 $this->mLoadedRequest = false;
97 }
98
103 private function loadRequestParameters( $subPage ) {
104 if ( $this->mLoadedRequest ) {
105 return;
106 }
107 $this->mLoadedRequest = true;
108 $request = $this->getRequest();
109
110 $this->mPosted = $request->wasPosted();
111 $this->mIsReturn = $subPage === 'return';
112 $this->mAction = $request->getVal( 'action' );
113 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
114 || $request->getBool( 'wpFromhttp', false );
115 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
116 || $request->getBool( 'wpForceHttps', false );
117 $this->mLanguage = $request->getText( 'uselang' );
118 $this->mReturnTo = $request->getVal( 'returnto', '' );
119 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
120 }
121
127 protected function load( $subPage ) {
128 global $wgSecureLogin;
129
131 if ( $this->mLoaded ) {
132 return;
133 }
134 $this->mLoaded = true;
135 $request = $this->getRequest();
136
137 $securityLevel = $this->getRequest()->getText( 'force' );
138 if (
139 $securityLevel && AuthManager::singleton()->securitySensitiveOperationStatus(
140 $securityLevel ) === AuthManager::SEC_REAUTH
141 ) {
142 $this->securityLevel = $securityLevel;
143 }
144
145 $this->loadAuth( $subPage );
146
147 $this->mToken = $request->getVal( $this->getTokenName() );
148
149 // Show an error or warning passed on from a previous page
150 $entryError = $this->msg( $request->getVal( 'error', '' ) );
151 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
152 // bc: provide login link as a parameter for messages where the translation
153 // was not updated
154 $loginreqlink = $this->getLinkRenderer()->makeKnownLink(
155 $this->getPageTitle(),
156 $this->msg( 'loginreqlink' )->text(),
157 [],
158 [
159 'returnto' => $this->mReturnTo,
160 'returntoquery' => $this->mReturnToQuery,
161 'uselang' => $this->mLanguage ?: null,
162 'fromhttp' => $wgSecureLogin && $this->mFromHTTP ? '1' : null,
163 ]
164 );
165
166 // Only show valid error or warning messages.
167 if ( $entryError->exists()
168 && in_array( $entryError->getKey(), LoginHelper::getValidErrorMessages(), true )
169 ) {
170 $this->mEntryErrorType = 'error';
171 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
172
173 } elseif ( $entryWarning->exists()
174 && in_array( $entryWarning->getKey(), LoginHelper::getValidErrorMessages(), true )
175 ) {
176 $this->mEntryErrorType = 'warning';
177 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
178 }
179
180 # 1. When switching accounts, it sucks to get automatically logged out
181 # 2. Do not return to PasswordReset after a successful password change
182 # but goto Wiki start page (Main_Page) instead ( T35997 )
183 $returnToTitle = Title::newFromText( $this->mReturnTo );
184 if ( is_object( $returnToTitle )
185 && ( $returnToTitle->isSpecial( 'Userlogout' )
186 || $returnToTitle->isSpecial( 'PasswordReset' ) )
187 ) {
188 $this->mReturnTo = '';
189 $this->mReturnToQuery = '';
190 }
191 }
192
193 protected function getPreservedParams( $withToken = false ) {
194 global $wgSecureLogin;
195
196 $params = parent::getPreservedParams( $withToken );
197 $params += [
198 'returnto' => $this->mReturnTo ?: null,
199 'returntoquery' => $this->mReturnToQuery ?: null,
200 ];
201 if ( $wgSecureLogin && !$this->isSignup() ) {
202 $params['fromhttp'] = $this->mFromHTTP ? '1' : null;
203 }
204 return $params;
205 }
206
207 protected function beforeExecute( $subPage ) {
208 // finish initializing the class before processing the request - T135924
210 return parent::beforeExecute( $subPage );
211 }
212
216 public function execute( $subPage ) {
217 if ( $this->mPosted ) {
218 $time = microtime( true );
219 $profilingScope = new ScopedCallback( function () use ( $time ) {
220 $time = microtime( true ) - $time;
221 $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
222 $statsd->timing( "timing.login.ui.{$this->authAction}", $time * 1000 );
223 } );
224 }
225
226 $authManager = AuthManager::singleton();
227 $session = SessionManager::getGlobalSession();
228
229 // Session data is used for various things in the authentication process, so we must make
230 // sure a session cookie or some equivalent mechanism is set.
231 $session->persist();
232
233 $this->load( $subPage );
234 $this->setHeaders();
235 $this->checkPermissions();
236
237 // Make sure the system configuration allows log in / sign up
238 if ( !$this->isSignup() && !$authManager->canAuthenticateNow() ) {
239 if ( !$session->canSetUser() ) {
240 throw new ErrorPageError( 'cannotloginnow-title', 'cannotloginnow-text', [
241 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
242 ] );
243 }
244 throw new ErrorPageError( 'cannotlogin-title', 'cannotlogin-text' );
245 } elseif ( $this->isSignup() && !$authManager->canCreateAccounts() ) {
246 throw new ErrorPageError( 'cannotcreateaccount-title', 'cannotcreateaccount-text' );
247 }
248
249 /*
250 * In the case where the user is already logged in, and was redirected to
251 * the login form from a page that requires login, do not show the login
252 * page. The use case scenario for this is when a user opens a large number
253 * of tabs, is redirected to the login page on all of them, and then logs
254 * in on one, expecting all the others to work properly.
255 *
256 * However, do show the form if it was visited intentionally (no 'returnto'
257 * is present). People who often switch between several accounts have grown
258 * accustomed to this behavior.
259 *
260 * Also make an exception when force=<level> is set in the URL, which means the user must
261 * reauthenticate for security reasons.
262 */
263 if ( !$this->isSignup() && !$this->mPosted && !$this->securityLevel &&
264 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' ) &&
265 $this->getUser()->isLoggedIn()
266 ) {
267 $this->successfulAction();
268 }
269
270 // If logging in and not on HTTPS, either redirect to it or offer a link.
271 global $wgSecureLogin;
272 if ( $this->getRequest()->getProtocol() !== 'https' ) {
273 $title = $this->getFullTitle();
274 $query = $this->getPreservedParams( false ) + [
275 'title' => null,
276 ( $this->mEntryErrorType === 'error' ? 'error'
277 : 'warning' ) => $this->mEntryError,
278 ] + $this->getRequest()->getQueryValues();
279 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
280 if ( $wgSecureLogin && !$this->mFromHTTP &&
281 wfCanIPUseHTTPS( $this->getRequest()->getIP() )
282 ) {
283 // Avoid infinite redirect
284 $url = wfAppendQuery( $url, 'fromhttp=1' );
285 $this->getOutput()->redirect( $url );
286 // Since we only do this redir to change proto, always vary
287 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
288
289 return;
290 } else {
291 // A wiki without HTTPS login support should set $wgServer to
292 // http://somehost, in which case the secure URL generated
293 // above won't actually start with https://
294 if ( substr( $url, 0, 8 ) === 'https://' ) {
295 $this->mSecureLoginUrl = $url;
296 }
297 }
298 }
299
300 if ( !$this->isActionAllowed( $this->authAction ) ) {
301 // FIXME how do we explain this to the user? can we handle session loss better?
302 // messages used: authpage-cannot-login, authpage-cannot-login-continue,
303 // authpage-cannot-create, authpage-cannot-create-continue
304 $this->mainLoginForm( [], 'authpage-cannot-' . $this->authAction );
305 return;
306 }
307
308 if ( $this->canBypassForm( $button_name ) ) {
309 $this->setRequest( [], true );
310 $this->getRequest()->setVal( $this->getTokenName(), $this->getToken() );
311 if ( $button_name ) {
312 $this->getRequest()->setVal( $button_name, true );
313 }
314 }
315
316 $status = $this->trySubmit();
317
318 if ( !$status || !$status->isGood() ) {
319 $this->mainLoginForm( $this->authRequests, $status ? $status->getMessage() : '', 'error' );
320 return;
321 }
322
324 $response = $status->getValue();
325
326 $returnToUrl = $this->getPageTitle( 'return' )
327 ->getFullURL( $this->getPreservedParams( true ), false, PROTO_HTTPS );
328 switch ( $response->status ) {
329 case AuthenticationResponse::PASS:
330 $this->logAuthResult( true );
331 $this->proxyAccountCreation = $this->isSignup() && !$this->getUser()->isAnon();
332 $this->targetUser = User::newFromName( $response->username );
333
334 if (
335 !$this->proxyAccountCreation
336 && $response->loginRequest
337 && $authManager->canAuthenticateNow()
338 ) {
339 // successful registration; log the user in instantly
340 $response2 = $authManager->beginAuthentication( [ $response->loginRequest ],
341 $returnToUrl );
342 if ( $response2->status !== AuthenticationResponse::PASS ) {
343 LoggerFactory::getInstance( 'login' )
344 ->error( 'Could not log in after account creation' );
345 $this->successfulAction( true, Status::newFatal( 'createacct-loginerror' ) );
346 break;
347 }
348 }
349
350 if ( !$this->proxyAccountCreation ) {
351 // Ensure that the context user is the same as the session user.
353 }
354
355 $this->successfulAction( true );
356 break;
357 case AuthenticationResponse::FAIL:
358 // fall through
359 case AuthenticationResponse::RESTART:
360 unset( $this->authForm );
361 if ( $response->status === AuthenticationResponse::FAIL ) {
362 $action = $this->getDefaultAction( $subPage );
363 $messageType = 'error';
364 } else {
365 $action = $this->getContinueAction( $this->authAction );
366 $messageType = 'warning';
367 }
368 $this->logAuthResult( false, $response->message ? $response->message->getKey() : '-' );
369 $this->loadAuth( $subPage, $action, true );
370 $this->mainLoginForm( $this->authRequests, $response->message, $messageType );
371 break;
372 case AuthenticationResponse::REDIRECT:
373 unset( $this->authForm );
374 $this->getOutput()->redirect( $response->redirectTarget );
375 break;
376 case AuthenticationResponse::UI:
377 unset( $this->authForm );
378 $this->authAction = $this->isSignup() ? AuthManager::ACTION_CREATE_CONTINUE
379 : AuthManager::ACTION_LOGIN_CONTINUE;
380 $this->authRequests = $response->neededRequests;
381 $this->mainLoginForm( $response->neededRequests, $response->message, $response->messageType );
382 break;
383 default:
384 throw new LogicException( 'invalid AuthenticationResponse' );
385 }
386 }
387
401 private function canBypassForm( &$button_name ) {
402 $button_name = null;
403 if ( $this->isContinued() ) {
404 return false;
405 }
406 $fields = AuthenticationRequest::mergeFieldInfo( $this->authRequests );
407 foreach ( $fields as $fieldname => $field ) {
408 if ( !isset( $field['type'] ) ) {
409 return false;
410 }
411 if ( !empty( $field['skippable'] ) ) {
412 continue;
413 }
414 if ( $field['type'] === 'button' ) {
415 if ( $button_name !== null ) {
416 $button_name = null;
417 return false;
418 } else {
419 $button_name = $fieldname;
420 }
421 } elseif ( $field['type'] !== 'null' ) {
422 return false;
423 }
424 }
425 return true;
426 }
427
437 protected function showSuccessPage(
438 $type, $title, $msgname, $injected_html, $extraMessages
439 ) {
440 $out = $this->getOutput();
441 $out->setPageTitle( $title );
442 if ( $msgname ) {
443 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
444 }
445 if ( $extraMessages ) {
446 $extraMessages = Status::wrap( $extraMessages );
447 $out->addWikiText( $extraMessages->getWikiText() );
448 }
449
450 $out->addHTML( $injected_html );
451
452 $helper = new LoginHelper( $this->getContext() );
453 $helper->showReturnToPage( $type, $this->mReturnTo, $this->mReturnToQuery, $this->mStickHTTPS );
454 }
455
471 public function showReturnToPage(
472 $type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false
473 ) {
474 $helper = new LoginHelper( $this->getContext() );
475 $helper->showReturnToPage( $type, $returnTo, $returnToQuery, $stickHTTPS );
476 }
477
483 protected function setSessionUserForCurrentRequest() {
484 global $wgUser, $wgLang;
485
487 $localContext = $this->getContext();
488 if ( $context !== $localContext ) {
489 // remove AuthManagerSpecialPage context hack
490 $this->setContext( $context );
491 }
492
493 $user = $context->getRequest()->getSession()->getUser();
494
495 $wgUser = $user;
496 $context->setUser( $user );
497
498 $code = $this->getRequest()->getVal( 'uselang', $user->getOption( 'language' ) );
499 $userLang = Language::factory( $code );
500 $wgLang = $userLang;
501 $context->setLanguage( $userLang );
502 }
503
518 protected function mainLoginForm( array $requests, $msg = '', $msgtype = 'error' ) {
519 $titleObj = $this->getPageTitle();
520 $user = $this->getUser();
521 $out = $this->getOutput();
522
523 // FIXME how to handle empty $requests - restart, or no form, just an error message?
524 // no form would be better for no session type errors, restart is better when can* fails.
525 if ( !$requests ) {
526 $this->authAction = $this->getDefaultAction( $this->subPage );
527 $this->authForm = null;
528 $requests = AuthManager::singleton()->getAuthenticationRequests( $this->authAction, $user );
529 }
530
531 // Generic styles and scripts for both login and signup form
532 $out->addModuleStyles( [
533 'mediawiki.ui',
534 'mediawiki.ui.button',
535 'mediawiki.ui.checkbox',
536 'mediawiki.ui.input',
537 'mediawiki.special.userlogin.common.styles'
538 ] );
539 if ( $this->isSignup() ) {
540 // XXX hack pending RL or JS parse() support for complex content messages T27349
541 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
542 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
543
544 // Additional styles and scripts for signup form
545 $out->addModules( [
546 'mediawiki.special.userlogin.signup.js'
547 ] );
548 $out->addModuleStyles( [
549 'mediawiki.special.userlogin.signup.styles'
550 ] );
551 } else {
552 // Additional styles for login form
553 $out->addModuleStyles( [
554 'mediawiki.special.userlogin.login.styles'
555 ] );
556 }
557 $out->disallowUserJs(); // just in case...
558
559 $form = $this->getAuthForm( $requests, $this->authAction, $msg, $msgtype );
560 $form->prepareForm();
561
562 $submitStatus = Status::newGood();
563 if ( $msg && $msgtype === 'warning' ) {
564 $submitStatus->warning( $msg );
565 } elseif ( $msg && $msgtype === 'error' ) {
566 $submitStatus->fatal( $msg );
567 }
568
569 // warning header for non-standard workflows (e.g. security reauthentication)
570 if (
571 !$this->isSignup() &&
572 $this->getUser()->isLoggedIn() &&
573 $this->authAction !== AuthManager::ACTION_LOGIN_CONTINUE
574 ) {
575 $reauthMessage = $this->securityLevel ? 'userlogin-reauth' : 'userlogin-loggedin';
576 $submitStatus->warning( $reauthMessage, $this->getUser()->getName() );
577 }
578
579 $formHtml = $form->getHTML( $submitStatus );
580
581 $out->addHTML( $this->getPageHtml( $formHtml ) );
582 }
583
590 protected function getPageHtml( $formHtml ) {
592
593 $loginPrompt = $this->isSignup() ? '' : Html::rawElement( 'div',
594 [ 'id' => 'userloginprompt' ], $this->msg( 'loginprompt' )->parseAsBlock() );
595 $languageLinks = $wgLoginLanguageSelector ? $this->makeLanguageSelector() : '';
596 $signupStartMsg = $this->msg( 'signupstart' );
597 $signupStart = ( $this->isSignup() && !$signupStartMsg->isDisabled() )
598 ? Html::rawElement( 'div', [ 'id' => 'signupstart' ], $signupStartMsg->parseAsBlock() ) : '';
599 if ( $languageLinks ) {
600 $languageLinks = Html::rawElement( 'div', [ 'id' => 'languagelinks' ],
601 Html::rawElement( 'p', [], $languageLinks )
602 );
603 }
604
605 $benefitsContainer = '';
606 if ( $this->isSignup() && $this->showExtraInformation() ) {
607 // messages used:
608 // createacct-benefit-icon1 createacct-benefit-head1 createacct-benefit-body1
609 // createacct-benefit-icon2 createacct-benefit-head2 createacct-benefit-body2
610 // createacct-benefit-icon3 createacct-benefit-head3 createacct-benefit-body3
611 $benefitCount = 3;
612 $benefitList = '';
613 for ( $benefitIdx = 1; $benefitIdx <= $benefitCount; $benefitIdx++ ) {
614 $headUnescaped = $this->msg( "createacct-benefit-head$benefitIdx" )->text();
615 $iconClass = $this->msg( "createacct-benefit-icon$benefitIdx" )->escaped();
616 $benefitList .= Html::rawElement( 'div', [ 'class' => "mw-number-text $iconClass" ],
617 Html::rawElement( 'h3', [],
618 $this->msg( "createacct-benefit-head$benefitIdx" )->escaped()
619 )
620 . Html::rawElement( 'p', [],
621 $this->msg( "createacct-benefit-body$benefitIdx" )->params( $headUnescaped )->escaped()
622 )
623 );
624 }
625 $benefitsContainer = Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-container' ],
626 Html::rawElement( 'h2', [], $this->msg( 'createacct-benefit-heading' )->escaped() )
627 . Html::rawElement( 'div', [ 'class' => 'mw-createacct-benefits-list' ],
628 $benefitList
629 )
630 );
631 }
632
633 $html = Html::rawElement( 'div', [ 'class' => 'mw-ui-container' ],
634 $loginPrompt
635 . $languageLinks
636 . $signupStart
637 . Html::rawElement( 'div', [ 'id' => 'userloginForm' ],
638 $formHtml
639 )
640 . $benefitsContainer
641 );
642
643 return $html;
644 }
645
654 protected function getAuthForm( array $requests, $action, $msg = '', $msgType = 'error' ) {
655 global $wgSecureLogin;
656 // FIXME merge this with parent
657
658 if ( isset( $this->authForm ) ) {
659 return $this->authForm;
660 }
661
662 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
663
664 // get basic form description from the auth logic
665 $fieldInfo = AuthenticationRequest::mergeFieldInfo( $requests );
666 $fakeTemplate = $this->getFakeTemplate( $msg, $msgType );
667 $this->fakeTemplate = $fakeTemplate; // FIXME there should be a saner way to pass this to the hook
668 // this will call onAuthChangeFormFields()
669 $formDescriptor = static::fieldInfoToFormDescriptor( $requests, $fieldInfo, $this->authAction );
670 $this->postProcessFormDescriptor( $formDescriptor, $requests );
671
672 $context = $this->getContext();
673 if ( $context->getRequest() !== $this->getRequest() ) {
674 // We have overridden the request, need to make sure the form uses that too.
675 $context = new DerivativeContext( $this->getContext() );
676 $context->setRequest( $this->getRequest() );
677 }
678 $form = HTMLForm::factory( 'vform', $formDescriptor, $context );
679
680 $form->addHiddenField( 'authAction', $this->authAction );
681 if ( $this->mLanguage ) {
682 $form->addHiddenField( 'uselang', $this->mLanguage );
683 }
684 $form->addHiddenField( 'force', $this->securityLevel );
685 $form->addHiddenField( $this->getTokenName(), $this->getToken()->toString() );
686 if ( $wgSecureLogin ) {
687 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
688 if ( !$this->isSignup() ) {
689 $form->addHiddenField( 'wpForceHttps', (int)$this->mStickHTTPS );
690 $form->addHiddenField( 'wpFromhttp', $usingHTTPS );
691 }
692 }
693
694 // set properties of the form itself
695 $form->setAction( $this->getPageTitle()->getLocalURL( $this->getReturnToQueryStringFragment() ) );
696 $form->setName( 'userlogin' . ( $this->isSignup() ? '2' : '' ) );
697 if ( $this->isSignup() ) {
698 $form->setId( 'userlogin2' );
699 }
700
701 $form->suppressDefaultSubmit();
702
703 $this->authForm = $form;
704
705 return $form;
706 }
707
714 protected function getFakeTemplate( $msg, $msgType ) {
717
718 // make a best effort to get the value of fields which used to be fixed in the old login
719 // template but now might or might not exist depending on what providers are used
720 $request = $this->getRequest();
721 $data = (object)[
722 'mUsername' => $request->getText( 'wpName' ),
723 'mPassword' => $request->getText( 'wpPassword' ),
724 'mRetype' => $request->getText( 'wpRetype' ),
725 'mEmail' => $request->getText( 'wpEmail' ),
726 'mRealName' => $request->getText( 'wpRealName' ),
727 'mDomain' => $request->getText( 'wpDomain' ),
728 'mReason' => $request->getText( 'wpReason' ),
729 'mRemember' => $request->getCheck( 'wpRemember' ),
730 ];
731
732 // Preserves a bunch of logic from the old code that was rewritten in getAuthForm().
733 // There is no code reuse to make this easier to remove .
734 // If an extension tries to change any of these values, they are out of luck - we only
735 // actually use the domain/usedomain/domainnames, extraInput and extrafields keys.
736
737 $titleObj = $this->getPageTitle();
738 $user = $this->getUser();
740
741 // Pre-fill username (if not creating an account, T46775).
742 if ( $data->mUsername == '' && $this->isSignup() ) {
743 if ( $user->isLoggedIn() ) {
744 $data->mUsername = $user->getName();
745 } else {
746 $data->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
747 }
748 }
749
750 if ( $this->isSignup() ) {
751 // Must match number of benefits defined in messages
752 $template->set( 'benefitCount', 3 );
753
754 $q = 'action=submitlogin&type=signup';
755 $linkq = 'type=login';
756 } else {
757 $q = 'action=submitlogin&type=login';
758 $linkq = 'type=signup';
759 }
760
761 if ( $this->mReturnTo !== '' ) {
762 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
763 if ( $this->mReturnToQuery !== '' ) {
764 $returnto .= '&returntoquery=' .
765 wfUrlencode( $this->mReturnToQuery );
766 }
767 $q .= $returnto;
768 $linkq .= $returnto;
769 }
770
771 # Don't show a "create account" link if the user can't.
772 if ( $this->showCreateAccountLink() ) {
773 # Pass any language selection on to the mode switch link
774 if ( $this->mLanguage ) {
775 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
776 }
777 // Supply URL, login template creates the button.
778 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
779 } else {
780 $template->set( 'link', '' );
781 }
782
783 $resetLink = $this->isSignup()
784 ? null
785 : is_array( $wgPasswordResetRoutes )
786 && in_array( true, array_values( $wgPasswordResetRoutes ), true );
787
788 $template->set( 'header', '' );
789 $template->set( 'formheader', '' );
790 $template->set( 'skin', $this->getSkin() );
791
792 $template->set( 'name', $data->mUsername );
793 $template->set( 'password', $data->mPassword );
794 $template->set( 'retype', $data->mRetype );
795 $template->set( 'createemailset', false ); // no easy way to get that from AuthManager
796 $template->set( 'email', $data->mEmail );
797 $template->set( 'realname', $data->mRealName );
798 $template->set( 'domain', $data->mDomain );
799 $template->set( 'reason', $data->mReason );
800 $template->set( 'remember', $data->mRemember );
801
802 $template->set( 'action', $titleObj->getLocalURL( $q ) );
803 $template->set( 'message', $msg );
804 $template->set( 'messagetype', $msgType );
805 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
806 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs, true ) );
807 $template->set( 'useemail', $wgEnableEmail );
808 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
809 $template->set( 'emailothers', $wgEnableUserEmail );
810 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
811 $template->set( 'resetlink', $resetLink );
812 $template->set( 'canremember', $request->getSession()->getProvider()
813 ->getRememberUserDuration() !== null );
814 $template->set( 'usereason', $user->isLoggedIn() );
815 $template->set( 'cansecurelogin', ( $wgSecureLogin ) );
816 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
817 $template->set( 'loggedin', $user->isLoggedIn() );
818 $template->set( 'loggedinuser', $user->getName() );
819 $template->set( 'token', $this->getToken()->toString() );
820
821 $action = $this->isSignup() ? 'signup' : 'login';
822 $wgAuth->modifyUITemplate( $template, $action );
823
824 $oldTemplate = $template;
825
826 // Both Hooks::run are explicit here to make findHooks.php happy
827 if ( $this->isSignup() ) {
828 Hooks::run( 'UserCreateForm', [ &$template ] );
829 if ( $oldTemplate !== $template ) {
830 wfDeprecated( "reference in UserCreateForm hook", '1.27' );
831 }
832 } else {
833 Hooks::run( 'UserLoginForm', [ &$template ] );
834 if ( $oldTemplate !== $template ) {
835 wfDeprecated( "reference in UserLoginForm hook", '1.27' );
836 }
837 }
838
839 return $template;
840 }
841
842 public function onAuthChangeFormFields(
843 array $requests, array $fieldInfo, array &$formDescriptor, $action
844 ) {
845 $coreFieldDescriptors = $this->getFieldDefinitions( $this->fakeTemplate );
846 $specialFields = array_merge( [ 'extraInput' ],
847 array_keys( $this->fakeTemplate->getExtraInputDefinitions() ) );
848
849 // keep the ordering from getCoreFieldDescriptors() where there is no explicit weight
850 foreach ( $coreFieldDescriptors as $fieldName => $coreField ) {
851 $requestField = isset( $formDescriptor[$fieldName] ) ?
852 $formDescriptor[$fieldName] : [];
853
854 // remove everything that is not in the fieldinfo, is not marked as a supplemental field
855 // to something in the fieldinfo, is not B/C for the pre-AuthManager templates,
856 // and is not an info field or a submit button
857 if (
858 !isset( $fieldInfo[$fieldName] )
859 && (
860 !isset( $coreField['baseField'] )
861 || !isset( $fieldInfo[$coreField['baseField']] )
862 )
863 && !in_array( $fieldName, $specialFields, true )
864 && (
865 !isset( $coreField['type'] )
866 || !in_array( $coreField['type'], [ 'submit', 'info' ], true )
867 )
868 ) {
869 $coreFieldDescriptors[$fieldName] = null;
870 continue;
871 }
872
873 // core message labels should always take priority
874 if (
875 isset( $coreField['label'] )
876 || isset( $coreField['label-message'] )
877 || isset( $coreField['label-raw'] )
878 ) {
879 unset( $requestField['label'], $requestField['label-message'], $coreField['label-raw'] );
880 }
881
882 $coreFieldDescriptors[$fieldName] += $requestField;
883 }
884
885 $formDescriptor = array_filter( $coreFieldDescriptors + $formDescriptor );
886 return true;
887 }
888
895 protected function showExtraInformation() {
896 return $this->authAction !== $this->getContinueAction( $this->authAction )
898 }
899
905 protected function getFieldDefinitions( $template ) {
907
908 $isLoggedIn = $this->getUser()->isLoggedIn();
909 $continuePart = $this->isContinued() ? 'continue-' : '';
910 $anotherPart = $isLoggedIn ? 'another-' : '';
911 $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration();
912 $expirationDays = ceil( $expiration / ( 3600 * 24 ) );
913 $secureLoginLink = '';
914 if ( $this->mSecureLoginUrl ) {
915 $secureLoginLink = Html::element( 'a', [
916 'href' => $this->mSecureLoginUrl,
917 'class' => 'mw-ui-flush-right mw-secure',
918 ], $this->msg( 'userlogin-signwithsecure' )->text() );
919 }
920 $usernameHelpLink = '';
921 if ( !$this->msg( 'createacct-helpusername' )->isDisabled() ) {
922 $usernameHelpLink = Html::rawElement( 'span', [
923 'class' => 'mw-ui-flush-right',
924 ], $this->msg( 'createacct-helpusername' )->parse() );
925 }
926
927 if ( $this->isSignup() ) {
928 $fieldDefinitions = [
929 'statusarea' => [
930 // used by the mediawiki.special.userlogin.signup.js module for error display
931 // FIXME merge this with HTMLForm's normal status (error) area
932 'type' => 'info',
933 'raw' => true,
934 'default' => Html::element( 'div', [ 'id' => 'mw-createacct-status-area' ] ),
935 'weight' => -105,
936 ],
937 'username' => [
938 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $usernameHelpLink,
939 'id' => 'wpName2',
940 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph'
941 : 'userlogin-yourname-ph',
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 'placeholder-message' => 'createacct-yourpassword-ph',
953 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
954 ],
955 'domain' => [],
956 'retype' => [
957 'baseField' => 'password',
958 'type' => 'password',
959 'label-message' => 'createacct-yourpasswordagain',
960 'id' => 'wpRetype',
961 'cssclass' => 'loginPassword',
962 'size' => 20,
963 'validation-callback' => function ( $value, $alldata ) {
964 if ( empty( $alldata['mailpassword'] ) && !empty( $alldata['password'] ) ) {
965 if ( !$value ) {
966 return $this->msg( 'htmlform-required' );
967 } elseif ( $value !== $alldata['password'] ) {
968 return $this->msg( 'badretype' );
969 }
970 }
971 return true;
972 },
973 'hide-if' => [ '===', 'wpCreateaccountMail', '1' ],
974 'placeholder-message' => 'createacct-yourpasswordagain-ph',
975 ],
976 'email' => [
977 'type' => 'email',
978 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired'
979 : 'createacct-emailoptional',
980 'id' => 'wpEmail',
981 'cssclass' => 'loginText',
982 'size' => '20',
983 // FIXME will break non-standard providers
984 'required' => $wgEmailConfirmToEdit,
985 'validation-callback' => function ( $value, $alldata ) {
987
988 // AuthManager will check most of these, but that will make the auth
989 // session fail and this won't, so nicer to do it this way
990 if ( !$value && $wgEmailConfirmToEdit ) {
991 // no point in allowing registration without email when email is
992 // required to edit
993 return $this->msg( 'noemailtitle' );
994 } elseif ( !$value && !empty( $alldata['mailpassword'] ) ) {
995 // cannot send password via email when there is no email address
996 return $this->msg( 'noemailcreate' );
997 } elseif ( $value && !Sanitizer::validateEmail( $value ) ) {
998 return $this->msg( 'invalidemailaddress' );
999 }
1000 return true;
1001 },
1002 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph',
1003 ],
1004 'realname' => [
1005 'type' => 'text',
1006 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip'
1007 : 'prefs-help-realname',
1008 'label-message' => 'createacct-realname',
1009 'cssclass' => 'loginText',
1010 'size' => 20,
1011 'id' => 'wpRealName',
1012 ],
1013 'reason' => [
1014 // comment for the user creation log
1015 'type' => 'text',
1016 'label-message' => 'createacct-reason',
1017 'cssclass' => 'loginText',
1018 'id' => 'wpReason',
1019 'size' => '20',
1020 'placeholder-message' => 'createacct-reason-ph',
1021 ],
1022 'extrainput' => [], // placeholder for fields coming from the template
1023 'createaccount' => [
1024 // submit button
1025 'type' => 'submit',
1026 'default' => $this->msg( 'createacct-' . $anotherPart . $continuePart .
1027 'submit' )->text(),
1028 'name' => 'wpCreateaccount',
1029 'id' => 'wpCreateaccount',
1030 'weight' => 100,
1031 ],
1032 ];
1033 } else {
1034 $fieldDefinitions = [
1035 'username' => [
1036 'label-raw' => $this->msg( 'userlogin-yourname' )->escaped() . $secureLoginLink,
1037 'id' => 'wpName1',
1038 'placeholder-message' => 'userlogin-yourname-ph',
1039 ],
1040 'password' => [
1041 'id' => 'wpPassword1',
1042 'placeholder-message' => 'userlogin-yourpassword-ph',
1043 ],
1044 'domain' => [],
1045 'extrainput' => [],
1046 'rememberMe' => [
1047 // option for saving the user token to a cookie
1048 'type' => 'check',
1049 'name' => 'wpRemember',
1050 'label-message' => $this->msg( 'userlogin-remembermypassword' )
1051 ->numParams( $expirationDays ),
1052 'id' => 'wpRemember',
1053 ],
1054 'loginattempt' => [
1055 // submit button
1056 'type' => 'submit',
1057 'default' => $this->msg( 'pt-login-' . $continuePart . 'button' )->text(),
1058 'id' => 'wpLoginAttempt',
1059 'weight' => 100,
1060 ],
1061 'linkcontainer' => [
1062 // help link
1063 'type' => 'info',
1064 'cssclass' => 'mw-form-related-link-container mw-userlogin-help',
1065 // 'id' => 'mw-userlogin-help', // FIXME HTMLInfoField ignores this
1066 'raw' => true,
1067 'default' => Html::element( 'a', [
1068 'href' => Skin::makeInternalOrExternalUrl( wfMessage( 'helplogin-url' )
1069 ->inContentLanguage()
1070 ->text() ),
1071 ], $this->msg( 'userlogin-helplink2' )->text() ),
1072 'weight' => 200,
1073 ],
1074 // button for ResetPasswordSecondaryAuthenticationProvider
1075 'skipReset' => [
1076 'weight' => 110,
1077 'flags' => [],
1078 ],
1079 ];
1080 }
1081
1082 $fieldDefinitions['username'] += [
1083 'type' => 'text',
1084 'name' => 'wpName',
1085 'cssclass' => 'loginText',
1086 'size' => 20,
1087 // 'required' => true,
1088 ];
1089 $fieldDefinitions['password'] += [
1090 'type' => 'password',
1091 // 'label-message' => 'userlogin-yourpassword', // would override the changepassword label
1092 'name' => 'wpPassword',
1093 'cssclass' => 'loginPassword',
1094 'size' => 20,
1095 // 'required' => true,
1096 ];
1097
1098 if ( $template->get( 'header' ) || $template->get( 'formheader' ) ) {
1099 // B/C for old extensions that haven't been converted to AuthManager (or have been
1100 // but somebody is using the old version) and still use templates via the
1101 // UserCreateForm/UserLoginForm hook.
1102 // 'header' used by ConfirmEdit, ConfirmAccount, Persona, WikimediaIncubator, SemanticSignup
1103 // 'formheader' used by MobileFrontend
1104 $fieldDefinitions['header'] = [
1105 'type' => 'info',
1106 'raw' => true,
1107 'default' => $template->get( 'header' ) ?: $template->get( 'formheader' ),
1108 'weight' => -110,
1109 ];
1110 }
1111 if ( $this->mEntryError ) {
1112 $fieldDefinitions['entryError'] = [
1113 'type' => 'info',
1114 'default' => Html::rawElement( 'div', [ 'class' => $this->mEntryErrorType . 'box', ],
1115 $this->mEntryError ),
1116 'raw' => true,
1117 'rawrow' => true,
1118 'weight' => -100,
1119 ];
1120 }
1121 if ( !$this->showExtraInformation() ) {
1122 unset( $fieldDefinitions['linkcontainer'], $fieldDefinitions['signupend'] );
1123 }
1124 if ( $this->isSignup() && $this->showExtraInformation() ) {
1125 // blank signup footer for site customization
1126 // uses signupend-https for HTTPS requests if it's not blank, signupend otherwise
1127 $signupendMsg = $this->msg( 'signupend' );
1128 $signupendHttpsMsg = $this->msg( 'signupend-https' );
1129 if ( !$signupendMsg->isDisabled() ) {
1130 $usingHTTPS = $this->getRequest()->getProtocol() === 'https';
1131 $signupendText = ( $usingHTTPS && !$signupendHttpsMsg->isBlank() )
1132 ? $signupendHttpsMsg ->parse() : $signupendMsg->parse();
1133 $fieldDefinitions['signupend'] = [
1134 'type' => 'info',
1135 'raw' => true,
1136 'default' => Html::rawElement( 'div', [ 'id' => 'signupend' ], $signupendText ),
1137 'weight' => 225,
1138 ];
1139 }
1140 }
1141 if ( !$this->isSignup() && $this->showExtraInformation() ) {
1142 $passwordReset = new PasswordReset( $this->getConfig(), AuthManager::singleton() );
1143 if ( $passwordReset->isAllowed( $this->getUser() )->isGood() ) {
1144 $fieldDefinitions['passwordReset'] = [
1145 'type' => 'info',
1146 'raw' => true,
1147 'cssclass' => 'mw-form-related-link-container',
1148 'default' => $this->getLinkRenderer()->makeLink(
1149 SpecialPage::getTitleFor( 'PasswordReset' ),
1150 $this->msg( 'userlogin-resetpassword-link' )->text()
1151 ),
1152 'weight' => 230,
1153 ];
1154 }
1155
1156 // Don't show a "create account" link if the user can't.
1157 if ( $this->showCreateAccountLink() ) {
1158 // link to the other action
1159 $linkTitle = $this->getTitleFor( $this->isSignup() ? 'Userlogin' : 'CreateAccount' );
1160 $linkq = $this->getReturnToQueryStringFragment();
1161 // Pass any language selection on to the mode switch link
1162 if ( $this->mLanguage ) {
1163 $linkq .= '&uselang=' . urlencode( $this->mLanguage );
1164 }
1165 $loggedIn = $this->getUser()->isLoggedIn();
1166
1167 $fieldDefinitions['createOrLogin'] = [
1168 'type' => 'info',
1169 'raw' => true,
1170 'linkQuery' => $linkq,
1171 'default' => function ( $params ) use ( $loggedIn, $linkTitle ) {
1172 return Html::rawElement( 'div',
1173 [ 'id' => 'mw-createaccount' . ( !$loggedIn ? '-cta' : '' ),
1174 'class' => ( $loggedIn ? 'mw-form-related-link-container' : 'mw-ui-vform-field' ) ],
1175 ( $loggedIn ? '' : $this->msg( 'userlogin-noaccount' )->escaped() )
1176 . Html::element( 'a',
1177 [
1178 'id' => 'mw-createaccount-join' . ( $loggedIn ? '-loggedin' : '' ),
1179 'href' => $linkTitle->getLocalURL( $params['linkQuery'] ),
1180 'class' => ( $loggedIn ? '' : 'mw-ui-button' ),
1181 'tabindex' => 100,
1182 ],
1183 $this->msg(
1184 $loggedIn ? 'userlogin-createanother' : 'userlogin-joinproject'
1185 )->escaped()
1186 )
1187 );
1188 },
1189 'weight' => 235,
1190 ];
1191 }
1192 }
1193
1194 $fieldDefinitions = $this->getBCFieldDefinitions( $fieldDefinitions, $template );
1195 $fieldDefinitions = array_filter( $fieldDefinitions );
1196
1197 return $fieldDefinitions;
1198 }
1199
1206 protected function getBCFieldDefinitions( $fieldDefinitions, $template ) {
1207 if ( $template->get( 'usedomain', false ) ) {
1208 // TODO probably should be translated to the new domain notation in AuthManager
1209 $fieldDefinitions['domain'] = [
1210 'type' => 'select',
1211 'label-message' => 'yourdomainname',
1212 'options' => array_combine( $template->get( 'domainnames', [] ),
1213 $template->get( 'domainnames', [] ) ),
1214 'default' => $template->get( 'domain', '' ),
1215 'name' => 'wpDomain',
1216 // FIXME id => 'mw-user-domain-section' on the parent div
1217 ];
1218 }
1219
1220 // poor man's associative array_splice
1221 $extraInputPos = array_search( 'extrainput', array_keys( $fieldDefinitions ), true );
1222 $fieldDefinitions = array_slice( $fieldDefinitions, 0, $extraInputPos, true )
1223 + $template->getExtraInputDefinitions()
1224 + array_slice( $fieldDefinitions, $extraInputPos + 1, null, true );
1225
1226 return $fieldDefinitions;
1227 }
1228
1238 protected function hasSessionCookie() {
1240
1241 return $wgDisableCookieCheck || (
1243 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1244 );
1245 }
1246
1252 protected function getReturnToQueryStringFragment() {
1253 $returnto = '';
1254 if ( $this->mReturnTo !== '' ) {
1255 $returnto = 'returnto=' . wfUrlencode( $this->mReturnTo );
1256 if ( $this->mReturnToQuery !== '' ) {
1257 $returnto .= '&returntoquery=' . wfUrlencode( $this->mReturnToQuery );
1258 }
1259 }
1260 return $returnto;
1261 }
1262
1268 private function showCreateAccountLink() {
1269 if ( $this->isSignup() ) {
1270 return true;
1271 } elseif ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1272 return true;
1273 } else {
1274 return false;
1275 }
1276 }
1277
1278 protected function getTokenName() {
1279 return $this->isSignup() ? 'wpCreateaccountToken' : 'wpLoginToken';
1280 }
1281
1288 protected function makeLanguageSelector() {
1289 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1290 if ( $msg->isBlank() ) {
1291 return '';
1292 }
1293 $langs = explode( "\n", $msg->text() );
1294 $links = [];
1295 foreach ( $langs as $lang ) {
1296 $lang = trim( $lang, '* ' );
1297 $parts = explode( '|', $lang );
1298 if ( count( $parts ) >= 2 ) {
1299 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1300 }
1301 }
1302
1303 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1304 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1305 }
1306
1315 protected function makeLanguageSelectorLink( $text, $lang ) {
1316 if ( $this->getLanguage()->getCode() == $lang ) {
1317 // no link for currently used language
1318 return htmlspecialchars( $text );
1319 }
1320 $query = [ 'uselang' => $lang ];
1321 if ( $this->mReturnTo !== '' ) {
1322 $query['returnto'] = $this->mReturnTo;
1323 $query['returntoquery'] = $this->mReturnToQuery;
1324 }
1325
1326 $attr = [];
1327 $targetLanguage = Language::factory( $lang );
1328 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1329
1330 return $this->getLinkRenderer()->makeKnownLink(
1331 $this->getPageTitle(),
1332 $text,
1333 $attr,
1334 $query
1335 );
1336 }
1337
1338 protected function getGroupName() {
1339 return 'login';
1340 }
1341
1346 protected function postProcessFormDescriptor( &$formDescriptor, $requests ) {
1347 // Pre-fill username (if not creating an account, T46775).
1348 if (
1349 isset( $formDescriptor['username'] ) &&
1350 !isset( $formDescriptor['username']['default'] ) &&
1351 !$this->isSignup()
1352 ) {
1353 $user = $this->getUser();
1354 if ( $user->isLoggedIn() ) {
1355 $formDescriptor['username']['default'] = $user->getName();
1356 } else {
1357 $formDescriptor['username']['default'] =
1358 $this->getRequest()->getSession()->suggestLoginUsername();
1359 }
1360 }
1361
1362 // don't show a submit button if there is nothing to submit (i.e. the only form content
1363 // is other submit buttons, for redirect flows)
1364 if ( !$this->needsSubmitButton( $requests ) ) {
1365 unset( $formDescriptor['createaccount'], $formDescriptor['loginattempt'] );
1366 }
1367
1368 if ( !$this->isSignup() ) {
1369 // FIXME HACK don't focus on non-empty field
1370 // maybe there should be an autofocus-if similar to hide-if?
1371 if (
1372 isset( $formDescriptor['username'] )
1373 && empty( $formDescriptor['username']['default'] )
1374 && !$this->getRequest()->getCheck( 'wpName' )
1375 ) {
1376 $formDescriptor['username']['autofocus'] = true;
1377 } elseif ( isset( $formDescriptor['password'] ) ) {
1378 $formDescriptor['password']['autofocus'] = true;
1379 }
1380 }
1381
1382 $this->addTabIndex( $formDescriptor );
1383 }
1384}
1385
1393 public function execute() {
1394 throw new LogicException( 'not used' );
1395 }
1396
1406 public function addInputItem( $name, $value, $type, $msg, $helptext = false ) {
1407 // use the same indexes as UserCreateForm just in case someone adds an item manually
1408 $this->data['extrainput'][] = [
1409 'name' => $name,
1410 'value' => $value,
1411 'type' => $type,
1412 'msg' => $msg,
1413 'helptext' => $helptext,
1414 ];
1415 }
1416
1421 public function getExtraInputDefinitions() {
1422 $definitions = [];
1423
1424 foreach ( $this->get( 'extrainput', [] ) as $field ) {
1425 $definition = [
1426 'type' => $field['type'] === 'checkbox' ? 'check' : $field['type'],
1427 'name' => $field['name'],
1428 'value' => $field['value'],
1429 'id' => $field['name'],
1430 ];
1431 if ( $field['msg'] ) {
1432 $definition['label-message'] = $this->getMsg( $field['msg'] );
1433 }
1434 if ( $field['helptext'] ) {
1435 $definition['help'] = $this->msgWiki( $field['helptext'] );
1436 }
1437
1438 // the array key doesn't matter much when name is defined explicitly but
1439 // let's try and follow HTMLForm conventions
1440 $name = preg_replace( '/^wp(?=[A-Z])/', '', $field['name'] );
1441 $definitions[$name] = $definition;
1442 }
1443
1444 if ( $this->haveData( 'extrafields' ) ) {
1445 $definitions['extrafields'] = [
1446 'type' => 'info',
1447 'raw' => true,
1448 'default' => $this->get( 'extrafields' ),
1449 ];
1450 }
1451
1452 return $definitions;
1453 }
1454}
1455
1461class LoginForm extends SpecialPage {
1462 const SUCCESS = 0;
1463 const NO_NAME = 1;
1464 const ILLEGAL = 2;
1466 const NOT_EXISTS = 4;
1467 const WRONG_PASS = 5;
1468 const EMPTY_PASS = 6;
1469 const RESET_PASS = 7;
1470 const ABORTED = 8;
1472 const THROTTLED = 10;
1473 const USER_BLOCKED = 11;
1474 const NEED_TOKEN = 12;
1475 const WRONG_TOKEN = 13;
1476 const USER_MIGRATED = 14;
1477
1478 public static $statusCodes = [
1479 self::SUCCESS => 'success',
1480 self::NO_NAME => 'no_name',
1481 self::ILLEGAL => 'illegal',
1482 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
1483 self::NOT_EXISTS => 'not_exists',
1484 self::WRONG_PASS => 'wrong_pass',
1485 self::EMPTY_PASS => 'empty_pass',
1486 self::RESET_PASS => 'reset_pass',
1487 self::ABORTED => 'aborted',
1488 self::CREATE_BLOCKED => 'create_blocked',
1489 self::THROTTLED => 'throttled',
1490 self::USER_BLOCKED => 'user_blocked',
1491 self::NEED_TOKEN => 'need_token',
1492 self::WRONG_TOKEN => 'wrong_token',
1493 self::USER_MIGRATED => 'user_migrated',
1494 ];
1495
1499 public function __construct( $request = null ) {
1500 wfDeprecated( 'LoginForm', '1.27' );
1501 parent::__construct();
1502 }
1503
1508 public static function getValidErrorMessages() {
1510 }
1511
1517 public static function incrementLoginThrottle( $username ) {
1518 wfDeprecated( __METHOD__, "1.27" );
1519 global $wgRequest;
1520 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1521 $throttler = new Throttler();
1522 return $throttler->increase( $username, $wgRequest->getIP(), __METHOD__ );
1523 }
1524
1530 public static function incLoginThrottle( $username ) {
1531 wfDeprecated( __METHOD__, "1.27" );
1532 $res = self::incrementLoginThrottle( $username );
1533 return is_array( $res ) ? true : 0;
1534 }
1535
1541 public static function clearLoginThrottle( $username ) {
1542 wfDeprecated( __METHOD__, "1.27" );
1543 global $wgRequest;
1544 $username = User::getCanonicalName( $username, 'usable' ) ?: $username;
1545 $throttler = new Throttler();
1546 return $throttler->clear( $username, $wgRequest->getIP() );
1547 }
1548
1552 public static function getLoginToken() {
1553 wfDeprecated( __METHOD__, '1.27' );
1554 global $wgRequest;
1555 return $wgRequest->getSession()->getToken( '', 'login' )->toString();
1556 }
1557
1561 public static function setLoginToken() {
1562 wfDeprecated( __METHOD__, '1.27' );
1563 }
1564
1568 public static function clearLoginToken() {
1569 wfDeprecated( __METHOD__, '1.27' );
1570 global $wgRequest;
1571 $wgRequest->getSession()->resetToken( 'login' );
1572 }
1573
1578 public static function getCreateaccountToken() {
1579 wfDeprecated( __METHOD__, '1.27' );
1580 global $wgRequest;
1581 return $wgRequest->getSession()->getToken( '', 'createaccount' )->toString();
1582 }
1583
1587 public static function setCreateaccountToken() {
1588 wfDeprecated( __METHOD__, '1.27' );
1589 }
1590
1594 public static function clearCreateaccountToken() {
1595 wfDeprecated( __METHOD__, '1.27' );
1596 global $wgRequest;
1597 $wgRequest->getSession()->resetToken( 'createaccount' );
1598 }
1599}
$wgDisableCookieCheck
By default, MediaWiki checks if the client supports cookies during the login process,...
$wgHiddenPrefs
An array of preferences to not show for the user.
$wgLoginLanguageSelector
Show a bar of language selection links in the user login and user registration forms; edit the "login...
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
$wgPasswordResetRoutes
Whether to allow password resets ("enter some identifying data, and we'll send an email with a tempor...
$wgEnableEmail
Set to true to enable the e-mail basic features: Password reminders, etc.
$wgSecureLogin
This is to let user authenticate using https when they come from http.
$wgEmailConfirmToEdit
Should editors be required to have a validated e-mail address before being allowed to edit?
$wgAuth $wgAuth
Authentication plugin.
$wgUseMediaWikiUIEverywhere
Temporary variable that applies MediaWiki UI wherever it can be supported.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$wgUser
Definition Setup.php:817
$wgInitialSessionId
Definition Setup.php:745
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:662
A special page subclass for authentication-related special pages.
getContinueAction( $action)
Gets the _CONTINUE version of an action.
isActionAllowed( $action)
Checks whether AuthManager is ready to perform the action.
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
getDefaultAction( $subPage)
Get the default action for this special page, if none is given via URL/POST data.
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button.
string $subPage
Subpage of the special page.
isContinued()
Returns true if this is not the first step of the authentication.
getRequest()
Get the WebRequest being used for this instance.
trySubmit()
Attempts to do an authentication step with the submitted data.
getToken()
Returns the CSRF token.
addTabIndex(&$formDescriptor)
Adds a sequential tabindex starting from 1 to all form elements.
New base template for a skin's template extended from QuickTemplate this class features helper method...
msgWiki( $str)
An ugly, ugly hack.
getMsg( $name)
Get a Message object with its context set.
An IContextSource implementation which will inherit context from another source but allow individual ...
An error page which can definitely be safely rendered using the OutputPage.
B/C class to try handling login/signup template modifications even though login/signup does not actua...
addInputItem( $name, $value, $type, $msg, $helptext=false)
Extensions (AntiSpoof and TitleBlacklist) call this in response to UserCreateForm hook to add checkbo...
getExtraInputDefinitions()
Turns addInputItem-style field definitions into HTMLForm field definitions.
execute()
Main function, used by classes that subclass QuickTemplate to show the actual HTML output.
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition HTMLForm.php:128
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition HTMLForm.php:277
LoginForm as a special page has been replaced by SpecialUserLogin and SpecialCreateAccount,...
static incrementLoginThrottle( $username)
static incLoginThrottle( $username)
__construct( $request=null)
static clearLoginThrottle( $username)
static clearCreateaccountToken()
Helper functions for the login form that need to be shared with other special pages (such as CentralA...
static getValidErrorMessages()
Returns an array of all valid error messages.
Holds shared logic for login and account creation pages.
mainLoginForm(array $requests, $msg='', $msgtype='error')
canBypassForm(&$button_name)
Determine if the login form can be bypassed.
getPreservedParams( $withToken=false)
Returns URL query parameters which can be used to reload the page (or leave and return) while preserv...
logAuthResult( $success, $status=null)
Logs to the authmanager-stats channel.
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Change the form descriptor that determines how a field will look in the authentication form.
loadRequestParameters( $subPage)
Load basic request parameters for this Special page.
setSessionUserForCurrentRequest()
Replace some globals to make sure the fact that the user has just been logged in is reflected in the ...
getFakeTemplate( $msg, $msgType)
Temporary B/C method to handle extensions using the UserLoginForm/UserCreateForm hooks.
showSuccessPage( $type, $title, $msgname, $injected_html, $extraMessages)
Show the success page.
getReturnToQueryStringFragment()
Returns a string that can be appended to the URL (without encoding) to preserve the return target.
User $targetUser
FIXME another flag for passing data.
successfulAction( $direct=false, $extraMessages=null)
getBCFieldDefinitions( $fieldDefinitions, $template)
Adds fields provided via the deprecated UserLoginForm / UserCreateForm hooks.
showExtraInformation()
Show extra information such as password recovery information, link from login to signup,...
getPageHtml( $formHtml)
Add page elements which are outside the form.
hasSessionCookie()
Check if a session cookie is present.
getAuthForm(array $requests, $action, $msg='', $msgType='error')
Generates a form from the given request.
getTokenName()
Returns the name of the CSRF token (under which it should be found in the POST or GET data).
makeLanguageSelectorLink( $text, $lang)
Create a language selector link for a particular language Links back to this page preserving type and...
bool $proxyAccountCreation
True if the user if creating an account for someone else.
showCreateAccountLink()
Whether the login/create account form should display a link to the other form (in addition to whateve...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
beforeExecute( $subPage)
Gets called before.
getFieldDefinitions( $template)
Create a HTMLForm descriptor for the core login fields.
postProcessFormDescriptor(&$formDescriptor, $requests)
setRequest(array $data, $wasPosted=null)
Override the POST data, GET data from the real request is preserved.
showReturnToPage( $type, $returnTo='', $returnToQuery='', $stickHTTPS=false)
Add a "return to" link or redirect to it.
makeLanguageSelector()
Produce a bar of links which allow the user to select another language during login/registration but ...
load( $subPage)
Load data from request.
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
This is a value object to hold authentication response data.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This serves as the entry point to the MediaWiki session handling system.
Helper class for the password reset functionality shared by the web UI and the API.
static getMain()
Static methods.
static makeInternalOrExternalUrl( $name)
If url string starts with http, consider as external URL, else internal.
Definition Skin.php:1161
Parent class for all special pages.
setContext( $context)
Sets the context this SpecialPage is executed in.
getName()
Get the name of this Special Page.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
getSkin()
Shortcut to get the skin being used for this instance.
checkPermissions()
Checks if userCanExecute, and if not throws a PermissionsError.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
getContext()
Gets the context this SpecialPage is executed in.
msg( $key)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getPageTitle( $subpage=false)
Get a self-referential title object.
getLanguage()
Shortcut to get user's language.
getFullTitle()
Return the full title, including $par.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:51
$res
Definition database.txt:21
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition design.txt:56
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2775
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1778
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:181
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping $template
Definition hooks.txt:829
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:863
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2780
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:1976
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:862
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:1983
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead. & $feedLinks hooks can tweak the array to change how login etc forms should look $requests
Definition hooks.txt:304
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:783
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
this hook is for auditing only $response
Definition hooks.txt:781
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1049
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1610
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
const PROTO_HTTPS
Definition Defines.php:221
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load
Definition memcached.txt:6
$params
if(!isset( $args[0])) $lang