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