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