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