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