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