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