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