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