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