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