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