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