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