Move CSRF token handling into MediaWiki\Session\Session
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3 * Implements Special:UserLogin
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 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\Session\SessionManager;
25
26 /**
27 * Implements Special:UserLogin
28 *
29 * @ingroup SpecialPage
30 */
31 class LoginForm extends SpecialPage {
32 const SUCCESS = 0;
33 const NO_NAME = 1;
34 const ILLEGAL = 2;
35 const WRONG_PLUGIN_PASS = 3;
36 const NOT_EXISTS = 4;
37 const WRONG_PASS = 5;
38 const EMPTY_PASS = 6;
39 const RESET_PASS = 7;
40 const ABORTED = 8;
41 const CREATE_BLOCKED = 9;
42 const THROTTLED = 10;
43 const USER_BLOCKED = 11;
44 const NEED_TOKEN = 12;
45 const WRONG_TOKEN = 13;
46 const USER_MIGRATED = 14;
47
48 public static $statusCodes = array(
49 self::SUCCESS => 'success',
50 self::NO_NAME => 'no_name',
51 self::ILLEGAL => 'illegal',
52 self::WRONG_PLUGIN_PASS => 'wrong_plugin_pass',
53 self::NOT_EXISTS => 'not_exists',
54 self::WRONG_PASS => 'wrong_pass',
55 self::EMPTY_PASS => 'empty_pass',
56 self::RESET_PASS => 'reset_pass',
57 self::ABORTED => 'aborted',
58 self::CREATE_BLOCKED => 'create_blocked',
59 self::THROTTLED => 'throttled',
60 self::USER_BLOCKED => 'user_blocked',
61 self::NEED_TOKEN => 'need_token',
62 self::WRONG_TOKEN => 'wrong_token',
63 self::USER_MIGRATED => 'user_migrated',
64 );
65
66 /**
67 * Valid error and warning messages
68 *
69 * Special:Userlogin can show an error or warning message on the form when
70 * coming from another page. This is done via the ?error= or ?warning= GET
71 * parameters.
72 *
73 * This array is the list of valid message keys. All other values will be
74 * ignored.
75 *
76 * @since 1.24
77 * @var string[]
78 */
79 public static $validErrorMessages = array(
80 'exception-nologin-text',
81 'watchlistanontext',
82 'changeemail-no-info',
83 'resetpass-no-info',
84 'confirmemail_needlogin',
85 'prefsnologintext2',
86 );
87
88 public $mAbortLoginErrorMsg = null;
89
90 protected $mUsername;
91 protected $mPassword;
92 protected $mRetype;
93 protected $mReturnTo;
94 protected $mCookieCheck;
95 protected $mPosted;
96 protected $mAction;
97 protected $mCreateaccount;
98 protected $mCreateaccountMail;
99 protected $mLoginattempt;
100 protected $mRemember;
101 protected $mEmail;
102 protected $mDomain;
103 protected $mLanguage;
104 protected $mSkipCookieCheck;
105 protected $mReturnToQuery;
106 protected $mToken;
107 protected $mStickHTTPS;
108 protected $mType;
109 protected $mReason;
110 protected $mRealName;
111 protected $mEntryError = '';
112 protected $mEntryErrorType = 'error';
113
114 private $mTempPasswordUsed;
115 private $mLoaded = false;
116 private $mSecureLoginUrl;
117
118 /** @var WebRequest */
119 private $mOverrideRequest = null;
120
121 /** @var WebRequest Effective request; set at the beginning of load */
122 private $mRequest = null;
123
124 /**
125 * @param WebRequest $request
126 */
127 public function __construct( $request = null ) {
128 global $wgUseMediaWikiUIEverywhere;
129 parent::__construct( 'Userlogin' );
130
131 $this->mOverrideRequest = $request;
132 // Override UseMediaWikiEverywhere to true, to force login and create form to use mw ui
133 $wgUseMediaWikiUIEverywhere = true;
134 }
135
136 public function doesWrites() {
137 return true;
138 }
139
140 /**
141 * Returns an array of all valid error messages.
142 *
143 * @return array
144 */
145 public static function getValidErrorMessages() {
146 static $messages = null;
147 if ( !$messages ) {
148 $messages = self::$validErrorMessages;
149 Hooks::run( 'LoginFormValidErrorMessages', array( &$messages ) );
150 }
151
152 return $messages;
153 }
154
155 /**
156 * Loader
157 */
158 function load() {
159 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
160
161 if ( $this->mLoaded ) {
162 return;
163 }
164 $this->mLoaded = true;
165
166 if ( $this->mOverrideRequest === null ) {
167 $request = $this->getRequest();
168 } else {
169 $request = $this->mOverrideRequest;
170 }
171 $this->mRequest = $request;
172
173 $this->mType = $request->getText( 'type' );
174 $this->mUsername = $request->getText( 'wpName' );
175 $this->mPassword = $request->getText( 'wpPassword' );
176 $this->mRetype = $request->getText( 'wpRetype' );
177 $this->mDomain = $request->getText( 'wpDomain' );
178 $this->mReason = $request->getText( 'wpReason' );
179 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
180 $this->mPosted = $request->wasPosted();
181 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
182 && $wgEnableEmail;
183 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail;
184 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
185 $this->mAction = $request->getVal( 'action' );
186 $this->mRemember = $request->getCheck( 'wpRemember' );
187 $this->mFromHTTP = $request->getBool( 'fromhttp', false )
188 || $request->getBool( 'wpFromhttp', false );
189 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
190 || $request->getBool( 'wpForceHttps', false );
191 $this->mLanguage = $request->getText( 'uselang' );
192 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
193 $this->mToken = $this->mType == 'signup'
194 ? $request->getVal( 'wpCreateaccountToken' )
195 : $request->getVal( 'wpLoginToken' );
196 $this->mReturnTo = $request->getVal( 'returnto', '' );
197 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
198
199 // Show an error or warning passed on from a previous page
200 $entryError = $this->msg( $request->getVal( 'error', '' ) );
201 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
202 // bc: provide login link as a parameter for messages where the translation
203 // was not updated
204 $loginreqlink = Linker::linkKnown(
205 $this->getPageTitle(),
206 $this->msg( 'loginreqlink' )->escaped(),
207 array(),
208 array(
209 'returnto' => $this->mReturnTo,
210 'returntoquery' => $this->mReturnToQuery,
211 'uselang' => $this->mLanguage,
212 'fromhttp' => $this->mFromHTTP ? '1' : '0',
213 )
214 );
215
216 // Only show valid error or warning messages.
217 if ( $entryError->exists()
218 && in_array( $entryError->getKey(), self::getValidErrorMessages() )
219 ) {
220 $this->mEntryErrorType = 'error';
221 $this->mEntryError = $entryError->rawParams( $loginreqlink )->parse();
222
223 } elseif ( $entryWarning->exists()
224 && in_array( $entryWarning->getKey(), self::getValidErrorMessages() )
225 ) {
226 $this->mEntryErrorType = 'warning';
227 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->parse();
228 }
229
230 if ( $wgEnableEmail ) {
231 $this->mEmail = $request->getText( 'wpEmail' );
232 } else {
233 $this->mEmail = '';
234 }
235 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
236 $this->mRealName = $request->getText( 'wpRealName' );
237 } else {
238 $this->mRealName = '';
239 }
240
241 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
242 $this->mDomain = $wgAuth->getDomain();
243 }
244 $wgAuth->setDomain( $this->mDomain );
245
246 # 1. When switching accounts, it sucks to get automatically logged out
247 # 2. Do not return to PasswordReset after a successful password change
248 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
249 $returnToTitle = Title::newFromText( $this->mReturnTo );
250 if ( is_object( $returnToTitle )
251 && ( $returnToTitle->isSpecial( 'Userlogout' )
252 || $returnToTitle->isSpecial( 'PasswordReset' ) )
253 ) {
254 $this->mReturnTo = '';
255 $this->mReturnToQuery = '';
256 }
257 }
258
259 function getDescription() {
260 if ( $this->mType === 'signup' ) {
261 return $this->msg( 'createaccount' )->text();
262 } else {
263 return $this->msg( 'login' )->text();
264 }
265 }
266
267 /**
268 * @param string|null $subPage
269 */
270 public function execute( $subPage ) {
271 // Make sure session is persisted
272 $session = MediaWiki\Session\SessionManager::getGlobalSession();
273 $session->persist();
274
275 $this->load();
276
277 // Check for [[Special:Userlogin/signup]]. This affects form display and
278 // page title.
279 if ( $subPage == 'signup' ) {
280 $this->mType = 'signup';
281 }
282 $this->setHeaders();
283
284 // Make sure it's possible to log in
285 if ( $this->mType !== 'signup' && !$session->canSetUser() ) {
286 throw new ErrorPageError(
287 'cannotloginnow-title',
288 'cannotloginnow-text',
289 array(
290 $session->getProvider()->describe( RequestContext::getMain()->getLanguage() )
291 )
292 );
293 }
294
295 /**
296 * In the case where the user is already logged in, and was redirected to
297 * the login form from a page that requires login, do not show the login
298 * page. The use case scenario for this is when a user opens a large number
299 * of tabs, is redirected to the login page on all of them, and then logs
300 * in on one, expecting all the others to work properly.
301 *
302 * However, do show the form if it was visited intentionally (no 'returnto'
303 * is present). People who often switch between several accounts have grown
304 * accustomed to this behavior.
305 */
306 if (
307 $this->mType !== 'signup' &&
308 !$this->mPosted &&
309 $this->getUser()->isLoggedIn() &&
310 ( $this->mReturnTo !== '' || $this->mReturnToQuery !== '' )
311 ) {
312 $this->successfulLogin();
313 }
314
315 // If logging in and not on HTTPS, either redirect to it or offer a link.
316 global $wgSecureLogin;
317 if ( $this->mRequest->getProtocol() !== 'https' ) {
318 $title = $this->getFullTitle();
319 $query = array(
320 'returnto' => $this->mReturnTo !== '' ? $this->mReturnTo : null,
321 'returntoquery' => $this->mReturnToQuery !== '' ?
322 $this->mReturnToQuery : null,
323 'title' => null,
324 ( $this->mEntryErrorType === 'error' ? 'error' : 'warning' ) => $this->mEntryError,
325 ) + $this->mRequest->getQueryValues();
326 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
327 if ( $wgSecureLogin
328 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
329 && !$this->mFromHTTP ) // Avoid infinite redirect
330 {
331 $url = wfAppendQuery( $url, 'fromhttp=1' );
332 $this->getOutput()->redirect( $url );
333 // Since we only do this redir to change proto, always vary
334 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
335
336 return;
337 } else {
338 // A wiki without HTTPS login support should set $wgServer to
339 // http://somehost, in which case the secure URL generated
340 // above won't actually start with https://
341 if ( substr( $url, 0, 8 ) === 'https://' ) {
342 $this->mSecureLoginUrl = $url;
343 }
344 }
345 }
346
347 if ( !is_null( $this->mCookieCheck ) ) {
348 $this->onCookieRedirectCheck( $this->mCookieCheck );
349
350 return;
351 } elseif ( $this->mPosted ) {
352 if ( $this->mCreateaccount ) {
353 $this->addNewAccount();
354
355 return;
356 } elseif ( $this->mCreateaccountMail ) {
357 $this->addNewAccountMailPassword();
358
359 return;
360 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
361 $this->processLogin();
362
363 return;
364 }
365 }
366 $this->mainLoginForm( $this->mEntryError, $this->mEntryErrorType );
367 }
368
369 /**
370 * @private
371 */
372 function addNewAccountMailPassword() {
373 if ( $this->mEmail == '' ) {
374 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
375
376 return;
377 }
378
379 $status = $this->addNewAccountInternal();
380 LoggerFactory::getInstance( 'authmanager' )->info(
381 'Account creation attempt with mailed password',
382 array( 'event' => 'accountcreation', 'status' => $status )
383 );
384 if ( !$status->isGood() ) {
385 $error = $status->getMessage();
386 $this->mainLoginForm( $error->toString() );
387
388 return;
389 }
390
391 /** @var User $u */
392 $u = $status->getValue();
393
394 // Wipe the initial password and mail a temporary one
395 $u->setPassword( null );
396 $u->saveSettings();
397 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
398
399 Hooks::run( 'AddNewAccount', array( $u, true ) );
400 $u->addNewUserLogEntry( 'byemail', $this->mReason );
401
402 $out = $this->getOutput();
403 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
404
405 if ( !$result->isGood() ) {
406 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
407 } else {
408 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
409 $this->executeReturnTo( 'success' );
410 }
411 }
412
413 /**
414 * @private
415 * @return bool
416 */
417 function addNewAccount() {
418 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
419
420 # Create the account and abort if there's a problem doing so
421 $status = $this->addNewAccountInternal();
422 LoggerFactory::getInstance( 'authmanager' )->info( 'Account creation attempt', array(
423 'event' => 'accountcreation',
424 'status' => $status,
425 ) );
426
427 if ( !$status->isGood() ) {
428 $error = $status->getMessage();
429 $this->mainLoginForm( $error->toString() );
430
431 return false;
432 }
433
434 $u = $status->getValue();
435
436 # Only save preferences if the user is not creating an account for someone else.
437 if ( $this->getUser()->isAnon() ) {
438 # If we showed up language selection links, and one was in use, be
439 # smart (and sensible) and save that language as the user's preference
440 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
441 $u->setOption( 'language', $this->mLanguage );
442 } else {
443
444 # Otherwise the user's language preference defaults to $wgContLang,
445 # but it may be better to set it to their preferred $wgContLang variant,
446 # based on browser preferences or URL parameters.
447 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
448 }
449 if ( $wgContLang->hasVariants() ) {
450 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
451 }
452 }
453
454 $out = $this->getOutput();
455
456 # Send out an email authentication message if needed
457 if ( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
458 $status = $u->sendConfirmationMail();
459 if ( $status->isGood() ) {
460 $out->addWikiMsg( 'confirmemail_oncreate' );
461 } else {
462 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
463 }
464 }
465
466 # Save settings (including confirmation token)
467 $u->saveSettings();
468
469 # If not logged in, assume the new account as the current one and set
470 # session cookies then show a "welcome" message or a "need cookies"
471 # message as needed
472 if ( $this->getUser()->isAnon() ) {
473 $u->setCookies();
474 $wgUser = $u;
475 // This should set it for OutputPage and the Skin
476 // which is needed or the personal links will be
477 // wrong.
478 $this->getContext()->setUser( $u );
479 Hooks::run( 'AddNewAccount', array( $u, false ) );
480 $u->addNewUserLogEntry( 'create' );
481 if ( $this->hasSessionCookie() ) {
482 $this->successfulCreation();
483 } else {
484 $this->cookieRedirectCheck( 'new' );
485 }
486 } else {
487 # Confirm that the account was created
488 $out->setPageTitle( $this->msg( 'accountcreated' ) );
489 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
490 $out->addReturnTo( $this->getPageTitle() );
491 Hooks::run( 'AddNewAccount', array( $u, false ) );
492 $u->addNewUserLogEntry( 'create2', $this->mReason );
493 }
494
495 return true;
496 }
497
498 /**
499 * Make a new user account using the loaded data.
500 * @private
501 * @throws PermissionsError|ReadOnlyError
502 * @return Status
503 */
504 public function addNewAccountInternal() {
505 global $wgAuth, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
506
507 // If the user passes an invalid domain, something is fishy
508 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
509 return Status::newFatal( 'wrongpassword' );
510 }
511
512 // If we are not allowing users to login locally, we should be checking
513 // to see if the user is actually able to authenticate to the authenti-
514 // cation server before they create an account (otherwise, they can
515 // create a local account and login as any domain user). We only need
516 // to check this for domains that aren't local.
517 if ( 'local' != $this->mDomain && $this->mDomain != '' ) {
518 if (
519 !$wgAuth->canCreateAccounts() &&
520 (
521 !$wgAuth->userExists( $this->mUsername ) ||
522 !$wgAuth->authenticate( $this->mUsername, $this->mPassword )
523 )
524 ) {
525 return Status::newFatal( 'wrongpassword' );
526 }
527 }
528
529 if ( wfReadOnly() ) {
530 throw new ReadOnlyError;
531 }
532
533 # Request forgery checks.
534 $token = self::getCreateaccountToken();
535 if ( $token->wasNew() ) {
536 return Status::newFatal( 'nocookiesfornew' );
537 }
538
539 # The user didn't pass a createaccount token
540 if ( !$this->mToken ) {
541 return Status::newFatal( 'sessionfailure' );
542 }
543
544 # Validate the createaccount token
545 if ( !$token->match( $this->mToken ) ) {
546 return Status::newFatal( 'sessionfailure' );
547 }
548
549 # Check permissions
550 $currentUser = $this->getUser();
551 $creationBlock = $currentUser->isBlockedFromCreateAccount();
552 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
553 throw new PermissionsError( 'createaccount' );
554 } elseif ( $creationBlock instanceof Block ) {
555 // Throws an ErrorPageError.
556 $this->userBlockedMessage( $creationBlock );
557
558 // This should never be reached.
559 return false;
560 }
561
562 # Include checks that will include GlobalBlocking (Bug 38333)
563 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
564 'createaccount',
565 $currentUser,
566 true
567 );
568
569 if ( count( $permErrors ) ) {
570 throw new PermissionsError( 'createaccount', $permErrors );
571 }
572
573 $ip = $this->getRequest()->getIP();
574 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
575 return Status::newFatal( 'sorbs_create_account_reason' );
576 }
577
578 # Now create a dummy user ($u) and check if it is valid
579 $u = User::newFromName( $this->mUsername, 'creatable' );
580 if ( !$u ) {
581 return Status::newFatal( 'noname' );
582 }
583
584 $cache = ObjectCache::getLocalClusterInstance();
585 # Make sure the user does not exist already
586 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $this->mUsername ) ) );
587 if ( !$lock ) {
588 return Status::newFatal( 'usernameinprogress' );
589 } elseif ( $u->idForName( User::READ_LOCKING ) ) {
590 return Status::newFatal( 'userexists' );
591 }
592
593 if ( $this->mCreateaccountMail ) {
594 # do not force a password for account creation by email
595 # set invalid password, it will be replaced later by a random generated password
596 $this->mPassword = null;
597 } else {
598 if ( $this->mPassword !== $this->mRetype ) {
599 return Status::newFatal( 'badretype' );
600 }
601
602 # check for password validity, return a fatal Status if invalid
603 $validity = $u->checkPasswordValidity( $this->mPassword, 'create' );
604 if ( !$validity->isGood() ) {
605 $validity->ok = false; // make sure this Status is fatal
606 return $validity;
607 }
608 }
609
610 # if you need a confirmed email address to edit, then obviously you
611 # need an email address.
612 if ( $wgEmailConfirmToEdit && strval( $this->mEmail ) === '' ) {
613 return Status::newFatal( 'noemailtitle' );
614 }
615
616 if ( strval( $this->mEmail ) !== '' && !Sanitizer::validateEmail( $this->mEmail ) ) {
617 return Status::newFatal( 'invalidemailaddress' );
618 }
619
620 # Set some additional data so the AbortNewAccount hook can be used for
621 # more than just username validation
622 $u->setEmail( $this->mEmail );
623 $u->setRealName( $this->mRealName );
624
625 $abortError = '';
626 $abortStatus = null;
627 if ( !Hooks::run( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
628 // Hook point to add extra creation throttles and blocks
629 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
630 if ( $abortStatus === null ) {
631 // Report back the old string as a raw message status.
632 // This will report the error back as 'createaccount-hook-aborted'
633 // with the given string as the message.
634 // To return a different error code, return a Status object.
635 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
636 $abortError->text();
637
638 return Status::newFatal( $abortError );
639 } else {
640 // For MediaWiki 1.23+ and updated hooks, return the Status object
641 // returned from the hook.
642 return $abortStatus;
643 }
644 }
645
646 // Hook point to check for exempt from account creation throttle
647 if ( !Hooks::run( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
648 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
649 "allowed account creation w/o throttle\n" );
650 } else {
651 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
652 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
653 $value = $cache->get( $key );
654 if ( !$value ) {
655 $cache->set( $key, 0, $cache::TTL_DAY );
656 }
657 if ( $value >= $wgAccountCreationThrottle ) {
658 return Status::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
659 }
660 $cache->incr( $key );
661 }
662 }
663
664 if ( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
665 return Status::newFatal( 'externaldberror' );
666 }
667
668 self::clearCreateaccountToken();
669
670 return $this->initUser( $u, false );
671 }
672
673 /**
674 * Actually add a user to the database.
675 * Give it a User object that has been initialised with a name.
676 *
677 * @param User $u
678 * @param bool $autocreate True if this is an autocreation via auth plugin
679 * @return Status Status object, with the User object in the value member on success
680 * @private
681 */
682 function initUser( $u, $autocreate ) {
683 global $wgAuth;
684
685 $status = $u->addToDatabase();
686 if ( !$status->isOK() ) {
687 return $status;
688 }
689
690 if ( $wgAuth->allowPasswordChange() ) {
691 $u->setPassword( $this->mPassword );
692 }
693
694 $u->setEmail( $this->mEmail );
695 $u->setRealName( $this->mRealName );
696 $u->setToken();
697
698 Hooks::run( 'LocalUserCreated', array( $u, $autocreate ) );
699 $oldUser = $u;
700 $wgAuth->initUser( $u, $autocreate );
701 if ( $oldUser !== $u ) {
702 wfWarn( get_class( $wgAuth ) . '::initUser() replaced the user object' );
703 }
704
705 $u->saveSettings();
706
707 // Update user count
708 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
709
710 // Watch user's userpage and talk page
711 $u->addWatch( $u->getUserPage(), WatchedItem::IGNORE_USER_RIGHTS );
712
713 return Status::newGood( $u );
714 }
715
716 /**
717 * Internally authenticate the login request.
718 *
719 * This may create a local account as a side effect if the
720 * authentication plugin allows transparent local account
721 * creation.
722 * @return int
723 */
724 public function authenticateUserData() {
725 global $wgUser, $wgAuth;
726
727 $this->load();
728
729 if ( $this->mUsername == '' ) {
730 return self::NO_NAME;
731 }
732
733 // We require a login token to prevent login CSRF
734 // Handle part of this before incrementing the throttle so
735 // token-less login attempts don't count towards the throttle
736 // but wrong-token attempts do.
737
738 // If the user doesn't have a login token yet, set one.
739 $token = self::getLoginToken();
740 if ( $token->wasNew() ) {
741 return self::NEED_TOKEN;
742 }
743 // If the user didn't pass a login token, tell them we need one
744 if ( !$this->mToken ) {
745 return self::NEED_TOKEN;
746 }
747
748 $throttleCount = self::incLoginThrottle( $this->mUsername );
749 if ( $throttleCount === true ) {
750 return self::THROTTLED;
751 }
752
753 // Validate the login token
754 if ( !$token->match( $this->mToken ) ) {
755 return self::WRONG_TOKEN;
756 }
757
758 // Load the current user now, and check to see if we're logging in as
759 // the same name. This is necessary because loading the current user
760 // (say by calling getName()) calls the UserLoadFromSession hook, which
761 // potentially creates the user in the database. Until we load $wgUser,
762 // checking for user existence using User::newFromName($name)->getId() below
763 // will effectively be using stale data.
764 if ( $this->getUser()->getName() === $this->mUsername ) {
765 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
766
767 return self::SUCCESS;
768 }
769
770 $u = User::newFromName( $this->mUsername );
771 if ( $u === false ) {
772 return self::ILLEGAL;
773 }
774
775 $msg = null;
776 // Give extensions a way to indicate the username has been updated,
777 // rather than telling the user the account doesn't exist.
778 if ( !Hooks::run( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
779 $this->mAbortLoginErrorMsg = $msg;
780 return self::USER_MIGRATED;
781 }
782
783 if ( !User::isUsableName( $u->getName() ) ) {
784 return self::ILLEGAL;
785 }
786
787 $isAutoCreated = false;
788 if ( $u->getID() == 0 ) {
789 $status = $this->attemptAutoCreate( $u );
790 if ( $status !== self::SUCCESS ) {
791 return $status;
792 } else {
793 $isAutoCreated = true;
794 }
795 } else {
796 $u->load();
797 }
798
799 // Give general extensions, such as a captcha, a chance to abort logins
800 $abort = self::ABORTED;
801 if ( !Hooks::run( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$msg ) ) ) {
802 if ( !in_array( $abort, array_keys( self::$statusCodes ), true ) ) {
803 throw new Exception( 'Invalid status code returned from AbortLogin hook: ' . $abort );
804 }
805 $this->mAbortLoginErrorMsg = $msg;
806 return $abort;
807 }
808
809 global $wgBlockDisablesLogin;
810 if ( !$u->checkPassword( $this->mPassword ) ) {
811 if ( $u->checkTemporaryPassword( $this->mPassword ) ) {
812 /**
813 * The e-mailed temporary password should not be used for actu-
814 * al logins; that's a very sloppy habit, and insecure if an
815 * attacker has a few seconds to click "search" on someone's
816 * open mail reader.
817 *
818 * Allow it to be used only to reset the password a single time
819 * to a new value, which won't be in the user's e-mail ar-
820 * chives.
821 *
822 * For backwards compatibility, we'll still recognize it at the
823 * login form to minimize surprises for people who have been
824 * logging in with a temporary password for some time.
825 *
826 * As a side-effect, we can authenticate the user's e-mail ad-
827 * dress if it's not already done, since the temporary password
828 * was sent via e-mail.
829 */
830 if ( !$u->isEmailConfirmed() && !wfReadOnly() ) {
831 $u->confirmEmail();
832 $u->saveSettings();
833 }
834
835 // At this point we just return an appropriate code/ indicating
836 // that the UI should show a password reset form; bot inter-
837 // faces etc will probably just fail cleanly here.
838 $this->mAbortLoginErrorMsg = 'resetpass-temp-emailed';
839 $this->mTempPasswordUsed = true;
840 $retval = self::RESET_PASS;
841 } else {
842 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
843 }
844 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
845 // If we've enabled it, make it so that a blocked user cannot login
846 $retval = self::USER_BLOCKED;
847 } elseif ( $this->checkUserPasswordExpired( $u ) == 'hard' ) {
848 // Force reset now, without logging in
849 $retval = self::RESET_PASS;
850 $this->mAbortLoginErrorMsg = 'resetpass-expired';
851 } else {
852 Hooks::run( 'UserLoggedIn', array( $u ) );
853 $oldUser = $u;
854 $wgAuth->updateUser( $u );
855 if ( $oldUser !== $u ) {
856 wfWarn( get_class( $wgAuth ) . '::updateUser() replaced the user object' );
857 }
858 $wgUser = $u;
859 // This should set it for OutputPage and the Skin
860 // which is needed or the personal links will be
861 // wrong.
862 $this->getContext()->setUser( $u );
863
864 // Please reset throttle for successful logins, thanks!
865 if ( $throttleCount ) {
866 self::clearLoginThrottle( $this->mUsername );
867 }
868
869 if ( $isAutoCreated ) {
870 // Must be run after $wgUser is set, for correct new user log
871 Hooks::run( 'AuthPluginAutoCreate', array( $u ) );
872 }
873
874 $retval = self::SUCCESS;
875 }
876 Hooks::run( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
877
878 return $retval;
879 }
880
881 /**
882 * Increment the login attempt throttle hit count for the (username,current IP)
883 * tuple unless the throttle was already reached.
884 * @param string $username The user name
885 * @return bool|int The integer hit count or True if it is already at the limit
886 */
887 public static function incLoginThrottle( $username ) {
888 global $wgPasswordAttemptThrottle, $wgRequest;
889 $username = trim( $username ); // sanity
890
891 $throttleCount = 0;
892 if ( is_array( $wgPasswordAttemptThrottle ) ) {
893 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
894 $count = $wgPasswordAttemptThrottle['count'];
895 $period = $wgPasswordAttemptThrottle['seconds'];
896
897 $cache = ObjectCache::getLocalClusterInstance();
898 $throttleCount = $cache->get( $throttleKey );
899 if ( !$throttleCount ) {
900 $cache->add( $throttleKey, 1, $period ); // start counter
901 } elseif ( $throttleCount < $count ) {
902 $cache->incr( $throttleKey );
903 } elseif ( $throttleCount >= $count ) {
904 return true;
905 }
906 }
907
908 return $throttleCount;
909 }
910
911 /**
912 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
913 * @param string $username The user name
914 * @return void
915 */
916 public static function clearLoginThrottle( $username ) {
917 global $wgRequest;
918 $username = trim( $username ); // sanity
919
920 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
921 ObjectCache::getLocalClusterInstance()->delete( $throttleKey );
922 }
923
924 /**
925 * Attempt to automatically create a user on login. Only succeeds if there
926 * is an external authentication method which allows it.
927 *
928 * @param User $user
929 *
930 * @return int Status code
931 */
932 function attemptAutoCreate( $user ) {
933 global $wgAuth;
934
935 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
936 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
937
938 return self::CREATE_BLOCKED;
939 }
940
941 if ( !$wgAuth->autoCreate() ) {
942 return self::NOT_EXISTS;
943 }
944
945 if ( !$wgAuth->userExists( $user->getName() ) ) {
946 wfDebug( __METHOD__ . ": user does not exist\n" );
947
948 return self::NOT_EXISTS;
949 }
950
951 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
952 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
953
954 return self::WRONG_PLUGIN_PASS;
955 }
956
957 $abortError = '';
958 if ( !Hooks::run( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
959 // Hook point to add extra creation throttles and blocks
960 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
961 $this->mAbortLoginErrorMsg = $abortError;
962
963 return self::ABORTED;
964 }
965
966 wfDebug( __METHOD__ . ": creating account\n" );
967 $status = $this->initUser( $user, true );
968
969 if ( !$status->isOK() ) {
970 $errors = $status->getErrorsByType( 'error' );
971 $this->mAbortLoginErrorMsg = $errors[0]['message'];
972
973 return self::ABORTED;
974 }
975
976 return self::SUCCESS;
977 }
978
979 function processLogin() {
980 global $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle, $wgInvalidPasswordReset;
981
982 $cache = ObjectCache::getLocalClusterInstance();
983 $authRes = $this->authenticateUserData();
984 switch ( $authRes ) {
985 case self::SUCCESS:
986 # We've verified now, update the real record
987 $user = $this->getUser();
988 $user->touch();
989
990 if ( $user->requiresHTTPS() ) {
991 $this->mStickHTTPS = true;
992 }
993
994 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
995 $user->setCookies( $this->mRequest, false, $this->mRemember );
996 } else {
997 $user->setCookies( $this->mRequest, null, $this->mRemember );
998 }
999 self::clearLoginToken();
1000
1001 // Reset the throttle
1002 $request = $this->getRequest();
1003 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
1004 $cache->delete( $key );
1005
1006 if ( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
1007 /* Replace the language object to provide user interface in
1008 * correct language immediately on this first page load.
1009 */
1010 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
1011 $userLang = Language::factory( $code );
1012 $wgLang = $userLang;
1013 $this->getContext()->setLanguage( $userLang );
1014 // Reset SessionID on Successful login (bug 40995)
1015 $this->renewSessionId();
1016 if ( $this->checkUserPasswordExpired( $this->getUser() ) == 'soft' ) {
1017 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
1018 } elseif ( $wgInvalidPasswordReset
1019 && !$user->isValidPassword( $this->mPassword )
1020 ) {
1021 $status = $user->checkPasswordValidity(
1022 $this->mPassword,
1023 'login'
1024 );
1025 $this->resetLoginForm(
1026 $status->getMessage( 'resetpass-validity-soft' )
1027 );
1028 } else {
1029 $this->successfulLogin();
1030 }
1031 } else {
1032 $this->cookieRedirectCheck( 'login' );
1033 }
1034 break;
1035
1036 case self::NEED_TOKEN:
1037 $error = $this->mAbortLoginErrorMsg ?: 'nocookiesforlogin';
1038 $this->mainLoginForm( $this->msg( $error )->parse() );
1039 break;
1040 case self::WRONG_TOKEN:
1041 $error = $this->mAbortLoginErrorMsg ?: 'sessionfailure';
1042 $this->mainLoginForm( $this->msg( $error )->text() );
1043 break;
1044 case self::NO_NAME:
1045 case self::ILLEGAL:
1046 $error = $this->mAbortLoginErrorMsg ?: 'noname';
1047 $this->mainLoginForm( $this->msg( $error )->text() );
1048 break;
1049 case self::WRONG_PLUGIN_PASS:
1050 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1051 $this->mainLoginForm( $this->msg( $error )->text() );
1052 break;
1053 case self::NOT_EXISTS:
1054 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
1055 $error = $this->mAbortLoginErrorMsg ?: 'nosuchuser';
1056 $this->mainLoginForm( $this->msg( $error,
1057 wfEscapeWikiText( $this->mUsername ) )->parse() );
1058 } else {
1059 $error = $this->mAbortLoginErrorMsg ?: 'nosuchusershort';
1060 $this->mainLoginForm( $this->msg( $error,
1061 wfEscapeWikiText( $this->mUsername ) )->text() );
1062 }
1063 break;
1064 case self::WRONG_PASS:
1065 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
1066 $this->mainLoginForm( $this->msg( $error )->text() );
1067 break;
1068 case self::EMPTY_PASS:
1069 $error = $this->mAbortLoginErrorMsg ?: 'wrongpasswordempty';
1070 $this->mainLoginForm( $this->msg( $error )->text() );
1071 break;
1072 case self::RESET_PASS:
1073 $error = $this->mAbortLoginErrorMsg ?: 'resetpass_announce';
1074 $this->resetLoginForm( $this->msg( $error ) );
1075 break;
1076 case self::CREATE_BLOCKED:
1077 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
1078 break;
1079 case self::THROTTLED:
1080 $error = $this->mAbortLoginErrorMsg ?: 'login-throttled';
1081 $this->mainLoginForm( $this->msg( $error )
1082 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
1083 ->text()
1084 );
1085 break;
1086 case self::USER_BLOCKED:
1087 $error = $this->mAbortLoginErrorMsg ?: 'login-userblocked';
1088 $this->mainLoginForm( $this->msg( $error, $this->mUsername )->escaped() );
1089 break;
1090 case self::ABORTED:
1091 $error = $this->mAbortLoginErrorMsg ?: 'login-abort-generic';
1092 $this->mainLoginForm( $this->msg( $error,
1093 wfEscapeWikiText( $this->mUsername ) )->text() );
1094 break;
1095 case self::USER_MIGRATED:
1096 $error = $this->mAbortLoginErrorMsg ?: 'login-migrated-generic';
1097 $params = array();
1098 if ( is_array( $error ) ) {
1099 $error = array_shift( $this->mAbortLoginErrorMsg );
1100 $params = $this->mAbortLoginErrorMsg;
1101 }
1102 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1103 break;
1104 default:
1105 throw new MWException( 'Unhandled case value' );
1106 }
1107
1108 LoggerFactory::getInstance( 'authmanager' )->info( 'Login attempt', array(
1109 'event' => 'login',
1110 'successful' => $authRes === self::SUCCESS,
1111 'status' => LoginForm::$statusCodes[$authRes],
1112 ) );
1113 }
1114
1115 /**
1116 * Show the Special:ChangePassword form, with custom message
1117 * @param Message $msg
1118 */
1119 protected function resetLoginForm( Message $msg ) {
1120 // Allow hooks to explain this password reset in more detail
1121 Hooks::run( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername ) );
1122 $reset = new SpecialChangePassword();
1123 $derivative = new DerivativeContext( $this->getContext() );
1124 $derivative->setTitle( $reset->getPageTitle() );
1125 $reset->setContext( $derivative );
1126 if ( !$this->mTempPasswordUsed ) {
1127 $reset->setOldPasswordMessage( 'oldpassword' );
1128 }
1129 $reset->setChangeMessage( $msg );
1130 $reset->execute( null );
1131 }
1132
1133 /**
1134 * @param User $u
1135 * @param bool $throttle
1136 * @param string $emailTitle Message name of email title
1137 * @param string $emailText Message name of email text
1138 * @return Status
1139 */
1140 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1141 $emailText = 'passwordremindertext'
1142 ) {
1143 global $wgNewPasswordExpiry, $wgMinimalPasswordLength;
1144
1145 if ( $u->getEmail() == '' ) {
1146 return Status::newFatal( 'noemail', $u->getName() );
1147 }
1148 $ip = $this->getRequest()->getIP();
1149 if ( !$ip ) {
1150 return Status::newFatal( 'badipaddress' );
1151 }
1152
1153 $currentUser = $this->getUser();
1154 Hooks::run( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1155
1156 $np = PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1157 $u->setNewpassword( $np, $throttle );
1158 $u->saveSettings();
1159 $userLanguage = $u->getOption( 'language' );
1160
1161 $mainPage = Title::newMainPage();
1162 $mainPageUrl = $mainPage->getCanonicalURL();
1163
1164 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1165 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1166 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1167
1168 return $result;
1169 }
1170
1171 /**
1172 * Run any hooks registered for logins, then HTTP redirect to
1173 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1174 * nice message here, but that's really not as useful as just being sent to
1175 * wherever you logged in from. It should be clear that the action was
1176 * successful, given the lack of error messages plus the appearance of your
1177 * name in the upper right.
1178 *
1179 * @private
1180 */
1181 function successfulLogin() {
1182 # Run any hooks; display injected HTML if any, else redirect
1183 $currentUser = $this->getUser();
1184 $injected_html = '';
1185 Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1186
1187 if ( $injected_html !== '' ) {
1188 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1189 'loginsuccess', $injected_html );
1190 } else {
1191 $this->executeReturnTo( 'successredirect' );
1192 }
1193 }
1194
1195 /**
1196 * Run any hooks registered for logins, then display a message welcoming
1197 * the user.
1198 *
1199 * @private
1200 */
1201 function successfulCreation() {
1202 # Run any hooks; display injected HTML
1203 $currentUser = $this->getUser();
1204 $injected_html = '';
1205 $welcome_creation_msg = 'welcomecreation-msg';
1206
1207 Hooks::run( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1208
1209 /**
1210 * Let any extensions change what message is shown.
1211 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1212 * @since 1.18
1213 */
1214 Hooks::run( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1215
1216 $this->displaySuccessfulAction(
1217 'signup',
1218 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1219 $welcome_creation_msg, $injected_html
1220 );
1221 }
1222
1223 /**
1224 * Display a "successful action" page.
1225 *
1226 * @param string $type Condition of return to; see `executeReturnTo`
1227 * @param string|Message $title Page's title
1228 * @param string $msgname
1229 * @param string $injected_html
1230 */
1231 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1232 $out = $this->getOutput();
1233 $out->setPageTitle( $title );
1234 if ( $msgname ) {
1235 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1236 }
1237
1238 $out->addHTML( $injected_html );
1239
1240 $this->executeReturnTo( $type );
1241 }
1242
1243 /**
1244 * Output a message that informs the user that they cannot create an account because
1245 * there is a block on them or their IP which prevents account creation. Note that
1246 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1247 * setting on blocks (bug 13611).
1248 * @param Block $block The block causing this error
1249 * @throws ErrorPageError
1250 */
1251 function userBlockedMessage( Block $block ) {
1252 # Let's be nice about this, it's likely that this feature will be used
1253 # for blocking large numbers of innocent people, e.g. range blocks on
1254 # schools. Don't blame it on the user. There's a small chance that it
1255 # really is the user's fault, i.e. the username is blocked and they
1256 # haven't bothered to log out before trying to create an account to
1257 # evade it, but we'll leave that to their guilty conscience to figure
1258 # out.
1259 $errorParams = array(
1260 $block->getTarget(),
1261 $block->mReason ? $block->mReason : $this->msg( 'blockednoreason' )->text(),
1262 $block->getByName()
1263 );
1264
1265 if ( $block->getType() === Block::TYPE_RANGE ) {
1266 $errorMessage = 'cantcreateaccount-range-text';
1267 $errorParams[] = $this->getRequest()->getIP();
1268 } else {
1269 $errorMessage = 'cantcreateaccount-text';
1270 }
1271
1272 throw new ErrorPageError(
1273 'cantcreateaccounttitle',
1274 $errorMessage,
1275 $errorParams
1276 );
1277 }
1278
1279 /**
1280 * Add a "return to" link or redirect to it.
1281 * Extensions can use this to reuse the "return to" logic after
1282 * inject steps (such as redirection) into the login process.
1283 *
1284 * @param string $type One of the following:
1285 * - error: display a return to link ignoring $wgRedirectOnLogin
1286 * - signup: display a return to link using $wgRedirectOnLogin if needed
1287 * - success: display a return to link using $wgRedirectOnLogin if needed
1288 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1289 * @param string $returnTo
1290 * @param array|string $returnToQuery
1291 * @param bool $stickHTTPs Keep redirect link on HTTPs
1292 * @since 1.22
1293 */
1294 public function showReturnToPage(
1295 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1296 ) {
1297 $this->mReturnTo = $returnTo;
1298 $this->mReturnToQuery = $returnToQuery;
1299 $this->mStickHTTPS = $stickHTTPs;
1300 $this->executeReturnTo( $type );
1301 }
1302
1303 /**
1304 * Add a "return to" link or redirect to it.
1305 *
1306 * @param string $type One of the following:
1307 * - error: display a return to link ignoring $wgRedirectOnLogin
1308 * - signup: display a return to link using $wgRedirectOnLogin if needed
1309 * - success: display a return to link using $wgRedirectOnLogin if needed
1310 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1311 */
1312 private function executeReturnTo( $type ) {
1313 global $wgRedirectOnLogin, $wgSecureLogin;
1314
1315 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1316 $returnTo = $wgRedirectOnLogin;
1317 $returnToQuery = array();
1318 } else {
1319 $returnTo = $this->mReturnTo;
1320 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
1321 }
1322
1323 // Allow modification of redirect behavior
1324 Hooks::run( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1325
1326 $returnToTitle = Title::newFromText( $returnTo );
1327 if ( !$returnToTitle ) {
1328 $returnToTitle = Title::newMainPage();
1329 }
1330
1331 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1332 $options = array( 'http' );
1333 $proto = PROTO_HTTP;
1334 } elseif ( $wgSecureLogin ) {
1335 $options = array( 'https' );
1336 $proto = PROTO_HTTPS;
1337 } else {
1338 $options = array();
1339 $proto = PROTO_RELATIVE;
1340 }
1341
1342 if ( $type == 'successredirect' ) {
1343 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1344 $this->getOutput()->redirect( $redirectUrl );
1345 } else {
1346 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1347 }
1348 }
1349
1350 /**
1351 * @param string $msg
1352 * @param string $msgtype
1353 * @throws ErrorPageError
1354 * @throws Exception
1355 * @throws FatalError
1356 * @throws MWException
1357 * @throws PermissionsError
1358 * @throws ReadOnlyError
1359 * @private
1360 */
1361 function mainLoginForm( $msg, $msgtype = 'error' ) {
1362 global $wgEnableEmail, $wgEnableUserEmail;
1363 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1364 global $wgAuth, $wgEmailConfirmToEdit;
1365 global $wgSecureLogin, $wgPasswordResetRoutes;
1366 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
1367
1368 $titleObj = $this->getPageTitle();
1369 $user = $this->getUser();
1370 $out = $this->getOutput();
1371
1372 if ( $this->mType == 'signup' ) {
1373 // Block signup here if in readonly. Keeps user from
1374 // going through the process (filling out data, etc)
1375 // and being informed later.
1376 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1377 if ( count( $permErrors ) ) {
1378 throw new PermissionsError( 'createaccount', $permErrors );
1379 } elseif ( $user->isBlockedFromCreateAccount() ) {
1380 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1381
1382 return;
1383 } elseif ( wfReadOnly() ) {
1384 throw new ReadOnlyError;
1385 }
1386 }
1387
1388 // Pre-fill username (if not creating an account, bug 44775).
1389 if ( $this->mUsername == '' && $this->mType != 'signup' ) {
1390 if ( $user->isLoggedIn() ) {
1391 $this->mUsername = $user->getName();
1392 } else {
1393 $this->mUsername = $this->getRequest()->getSession()->suggestLoginUsername();
1394 }
1395 }
1396
1397 // Generic styles and scripts for both login and signup form
1398 $out->addModuleStyles( array(
1399 'mediawiki.ui',
1400 'mediawiki.ui.button',
1401 'mediawiki.ui.checkbox',
1402 'mediawiki.ui.input',
1403 'mediawiki.special.userlogin.common.styles'
1404 ) );
1405
1406 if ( $this->mType == 'signup' ) {
1407 // Additional styles and scripts for signup form
1408 $out->addModules( array(
1409 'mediawiki.special.userlogin.signup.js'
1410 ) );
1411 $out->addModuleStyles( array(
1412 'mediawiki.special.userlogin.signup.styles'
1413 ) );
1414
1415 $template = new UsercreateTemplate( $this->getConfig() );
1416
1417 // Must match number of benefits defined in messages
1418 $template->set( 'benefitCount', 3 );
1419
1420 $q = 'action=submitlogin&type=signup';
1421 $linkq = 'type=login';
1422 } else {
1423 // Additional styles for login form
1424 $out->addModuleStyles( array(
1425 'mediawiki.special.userlogin.login.styles'
1426 ) );
1427
1428 $template = new UserloginTemplate( $this->getConfig() );
1429
1430 $q = 'action=submitlogin&type=login';
1431 $linkq = 'type=signup';
1432 }
1433
1434 if ( $this->mReturnTo !== '' ) {
1435 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1436 if ( $this->mReturnToQuery !== '' ) {
1437 $returnto .= '&returntoquery=' .
1438 wfUrlencode( $this->mReturnToQuery );
1439 }
1440 $q .= $returnto;
1441 $linkq .= $returnto;
1442 }
1443
1444 # Don't show a "create account" link if the user can't.
1445 if ( $this->showCreateOrLoginLink( $user ) ) {
1446 # Pass any language selection on to the mode switch link
1447 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1448 $linkq .= '&uselang=' . $this->mLanguage;
1449 }
1450 // Supply URL, login template creates the button.
1451 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1452 } else {
1453 $template->set( 'link', '' );
1454 }
1455
1456 $resetLink = $this->mType == 'signup'
1457 ? null
1458 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1459
1460 $template->set( 'header', '' );
1461 $template->set( 'formheader', '' );
1462 $template->set( 'skin', $this->getSkin() );
1463 $template->set( 'name', $this->mUsername );
1464 $template->set( 'password', $this->mPassword );
1465 $template->set( 'retype', $this->mRetype );
1466 $template->set( 'createemailset', $this->mCreateaccountMail );
1467 $template->set( 'email', $this->mEmail );
1468 $template->set( 'realname', $this->mRealName );
1469 $template->set( 'domain', $this->mDomain );
1470 $template->set( 'reason', $this->mReason );
1471
1472 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1473 $template->set( 'message', $msg );
1474 $template->set( 'messagetype', $msgtype );
1475 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1476 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1477 $template->set( 'useemail', $wgEnableEmail );
1478 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1479 $template->set( 'emailothers', $wgEnableUserEmail );
1480 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1481 $template->set( 'resetlink', $resetLink );
1482 $template->set( 'canremember', $wgExtendedLoginCookieExpiration === null ?
1483 ( $wgCookieExpiration > 0 ) :
1484 ( $wgExtendedLoginCookieExpiration > 0 ) );
1485 $template->set( 'usereason', $user->isLoggedIn() );
1486 $template->set( 'remember', $this->mRemember );
1487 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1488 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
1489 $template->set( 'loggedin', $user->isLoggedIn() );
1490 $template->set( 'loggedinuser', $user->getName() );
1491
1492 if ( $this->mType == 'signup' ) {
1493 $template->set( 'token', self::getCreateaccountToken()->toString() );
1494 } else {
1495 $template->set( 'token', self::getLoginToken()->toString() );
1496 }
1497
1498 # Prepare language selection links as needed
1499 if ( $wgLoginLanguageSelector ) {
1500 $template->set( 'languages', $this->makeLanguageSelector() );
1501 if ( $this->mLanguage ) {
1502 $template->set( 'uselang', $this->mLanguage );
1503 }
1504 }
1505
1506 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl );
1507 // Use signupend-https for HTTPS requests if it's not blank, signupend otherwise
1508 $usingHTTPS = $this->mRequest->getProtocol() == 'https';
1509 $signupendHTTPS = $this->msg( 'signupend-https' );
1510 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1511 $template->set( 'signupend', $signupendHTTPS->parse() );
1512 } else {
1513 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1514 }
1515
1516 // If using HTTPS coming from HTTP, then the 'fromhttp' parameter must be preserved
1517 if ( $usingHTTPS ) {
1518 $template->set( 'fromhttp', $this->mFromHTTP );
1519 }
1520
1521 // Give authentication and captcha plugins a chance to modify the form
1522 $wgAuth->modifyUITemplate( $template, $this->mType );
1523 if ( $this->mType == 'signup' ) {
1524 Hooks::run( 'UserCreateForm', array( &$template ) );
1525 } else {
1526 Hooks::run( 'UserLoginForm', array( &$template ) );
1527 }
1528
1529 $out->disallowUserJs(); // just in case...
1530 $out->addTemplate( $template );
1531 }
1532
1533 /**
1534 * Whether the login/create account form should display a link to the
1535 * other form (in addition to whatever the skin provides).
1536 *
1537 * @param User $user
1538 * @return bool
1539 */
1540 private function showCreateOrLoginLink( &$user ) {
1541 if ( $this->mType == 'signup' ) {
1542 return true;
1543 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1544 return true;
1545 } else {
1546 return false;
1547 }
1548 }
1549
1550 /**
1551 * Check if a session cookie is present.
1552 *
1553 * This will not pick up a cookie set during _this_ request, but is meant
1554 * to ensure that the client is returning the cookie which was set on a
1555 * previous pass through the system.
1556 *
1557 * @private
1558 * @return bool
1559 */
1560 function hasSessionCookie() {
1561 global $wgDisableCookieCheck, $wgInitialSessionId;
1562
1563 return $wgDisableCookieCheck || (
1564 $wgInitialSessionId &&
1565 $this->getRequest()->getSession()->getId() === (string)$wgInitialSessionId
1566 );
1567 }
1568
1569 /**
1570 * Get the login token from the current session
1571 * @since 1.27 returns a MediaWiki\\Session\\Token instead of a string
1572 * @return MediaWiki\\Session\\Token
1573 */
1574 public static function getLoginToken() {
1575 global $wgRequest;
1576 return $wgRequest->getSession()->getToken( '', 'login' );
1577 }
1578
1579 /**
1580 * Formerly randomly generated a login token that would be returned by
1581 * $this->getLoginToken().
1582 *
1583 * Since 1.27, this is a no-op. The token is generated as necessary by
1584 * $this->getLoginToken().
1585 *
1586 * @deprecated since 1.27
1587 */
1588 public static function setLoginToken() {
1589 wfDeprecated( __METHOD__, '1.27' );
1590 }
1591
1592 /**
1593 * Remove any login token attached to the current session
1594 */
1595 public static function clearLoginToken() {
1596 global $wgRequest;
1597 $wgRequest->getSession()->resetToken( 'login' );
1598 }
1599
1600 /**
1601 * Get the createaccount token from the current session
1602 * @since 1.27 returns a MediaWiki\\Session\\Token instead of a string
1603 * @return MediaWiki\\Session\\Token
1604 */
1605 public static function getCreateaccountToken() {
1606 global $wgRequest;
1607 return $wgRequest->getSession()->getToken( '', 'createaccount' );
1608 }
1609
1610 /**
1611 * Formerly randomly generated a createaccount token that would be returned
1612 * by $this->getCreateaccountToken().
1613 *
1614 * Since 1.27, this is a no-op. The token is generated as necessary by
1615 * $this->getCreateaccountToken().
1616 *
1617 * @deprecated since 1.27
1618 */
1619 public static function setCreateaccountToken() {
1620 wfDeprecated( __METHOD__, '1.27' );
1621 }
1622
1623 /**
1624 * Remove any createaccount token attached to the current session
1625 */
1626 public static function clearCreateaccountToken() {
1627 global $wgRequest;
1628 $wgRequest->getSession()->resetToken( 'createaccount' );
1629 }
1630
1631 /**
1632 * Renew the user's session id, using strong entropy
1633 */
1634 private function renewSessionId() {
1635 global $wgSecureLogin, $wgCookieSecure;
1636 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1637 $wgCookieSecure = false;
1638 }
1639
1640 MediaWiki\Session\SessionManager::getGlobalSession()->resetId();
1641 }
1642
1643 /**
1644 * @param string $type
1645 * @private
1646 */
1647 function cookieRedirectCheck( $type ) {
1648 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1649 $query = array( 'wpCookieCheck' => $type );
1650 if ( $this->mReturnTo !== '' ) {
1651 $query['returnto'] = $this->mReturnTo;
1652 $query['returntoquery'] = $this->mReturnToQuery;
1653 }
1654 $check = $titleObj->getFullURL( $query );
1655
1656 $this->getOutput()->redirect( $check );
1657 }
1658
1659 /**
1660 * @param string $type
1661 * @private
1662 */
1663 function onCookieRedirectCheck( $type ) {
1664 if ( !$this->hasSessionCookie() ) {
1665 if ( $type == 'new' ) {
1666 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1667 } elseif ( $type == 'login' ) {
1668 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1669 } else {
1670 # shouldn't happen
1671 $this->mainLoginForm( $this->msg( 'error' )->text() );
1672 }
1673 } else {
1674 $this->successfulLogin();
1675 }
1676 }
1677
1678 /**
1679 * Produce a bar of links which allow the user to select another language
1680 * during login/registration but retain "returnto"
1681 *
1682 * @return string
1683 */
1684 function makeLanguageSelector() {
1685 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1686 if ( $msg->isBlank() ) {
1687 return '';
1688 }
1689 $langs = explode( "\n", $msg->text() );
1690 $links = array();
1691 foreach ( $langs as $lang ) {
1692 $lang = trim( $lang, '* ' );
1693 $parts = explode( '|', $lang );
1694 if ( count( $parts ) >= 2 ) {
1695 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1696 }
1697 }
1698
1699 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1700 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1701 }
1702
1703 /**
1704 * Create a language selector link for a particular language
1705 * Links back to this page preserving type and returnto
1706 *
1707 * @param string $text Link text
1708 * @param string $lang Language code
1709 * @return string
1710 */
1711 function makeLanguageSelectorLink( $text, $lang ) {
1712 if ( $this->getLanguage()->getCode() == $lang ) {
1713 // no link for currently used language
1714 return htmlspecialchars( $text );
1715 }
1716 $query = array( 'uselang' => $lang );
1717 if ( $this->mType == 'signup' ) {
1718 $query['type'] = 'signup';
1719 }
1720 if ( $this->mReturnTo !== '' ) {
1721 $query['returnto'] = $this->mReturnTo;
1722 $query['returntoquery'] = $this->mReturnToQuery;
1723 }
1724
1725 $attr = array();
1726 $targetLanguage = Language::factory( $lang );
1727 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1728
1729 return Linker::linkKnown(
1730 $this->getPageTitle(),
1731 htmlspecialchars( $text ),
1732 $attr,
1733 $query
1734 );
1735 }
1736
1737 protected function getGroupName() {
1738 return 'login';
1739 }
1740
1741 /**
1742 * Private function to check password expiration, until AuthManager comes
1743 * along to handle that.
1744 * @param User $user
1745 * @return string|bool
1746 */
1747 private function checkUserPasswordExpired( User $user ) {
1748 global $wgPasswordExpireGrace;
1749 $dbr = wfGetDB( DB_SLAVE );
1750 $ts = $dbr->selectField( 'user', 'user_password_expires', array( 'user_id' => $user->getId() ) );
1751
1752 $expired = false;
1753 $now = wfTimestamp();
1754 $expUnix = wfTimestamp( TS_UNIX, $ts );
1755 if ( $ts !== null && $expUnix < $now ) {
1756 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
1757 }
1758 return $expired;
1759 }
1760
1761 }