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