Fix for r79874: only set $mRevIdFetched from fetchContent(), it was overriden by...
[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, $mMailmypassword;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50
51 private $mExtUser = null;
52
53 public function __construct( $request = null ) {
54 parent::__construct( 'Userlogin' );
55
56 if ( $request === null ) {
57 global $wgRequest;
58 $this->load( $wgRequest );
59 } else {
60 $this->load( $request );
61 }
62 }
63
64 /**
65 * Loader
66 *
67 * @param $request WebRequest object
68 */
69 function load( $request ) {
70 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
71
72 $this->mType = $request->getText( 'type' );
73 $this->mUsername = $request->getText( 'wpName' );
74 $this->mPassword = $request->getText( 'wpPassword' );
75 $this->mRetype = $request->getText( 'wpRetype' );
76 $this->mDomain = $request->getText( 'wpDomain' );
77 $this->mReason = $request->getText( 'wpReason' );
78 $this->mReturnTo = $request->getVal( 'returnto' );
79 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
80 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
81 $this->mPosted = $request->wasPosted();
82 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
83 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
84 && $wgEnableEmail;
85 $this->mMailmypassword = $request->getCheck( 'wpMailmypassword' )
86 && $wgEnableEmail;
87 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
88 $this->mAction = $request->getVal( 'action' );
89 $this->mRemember = $request->getCheck( 'wpRemember' );
90 $this->mStickHTTPS = $request->getCheck( 'wpStickHTTPS' );
91 $this->mLanguage = $request->getText( 'uselang' );
92 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
93 $this->mToken = ( $this->mType == 'signup' ) ? $request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
94
95 if ( $wgRedirectOnLogin ) {
96 $this->mReturnTo = $wgRedirectOnLogin;
97 $this->mReturnToQuery = '';
98 }
99
100 if( $wgEnableEmail ) {
101 $this->mEmail = $request->getText( 'wpEmail' );
102 } else {
103 $this->mEmail = '';
104 }
105 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
106 $this->mRealName = $request->getText( 'wpRealName' );
107 } else {
108 $this->mRealName = '';
109 }
110
111 if( !$wgAuth->validDomain( $this->mDomain ) ) {
112 $this->mDomain = 'invaliddomain';
113 }
114 $wgAuth->setDomain( $this->mDomain );
115
116 # When switching accounts, it sucks to get automatically logged out
117 $returnToTitle = Title::newFromText( $this->mReturnTo );
118 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
119 $this->mReturnTo = '';
120 $this->mReturnToQuery = '';
121 }
122 }
123
124 public function execute( $par ) {
125 if ( session_id() == '' ) {
126 wfSetupSession();
127 }
128
129 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
130 $this->mType = 'signup';
131 }
132
133 if ( !is_null( $this->mCookieCheck ) ) {
134 $this->onCookieRedirectCheck( $this->mCookieCheck );
135 return;
136 } elseif( $this->mPosted ) {
137 if( $this->mCreateaccount ) {
138 return $this->addNewAccount();
139 } elseif ( $this->mCreateaccountMail ) {
140 return $this->addNewAccountMailPassword();
141 } elseif ( $this->mMailmypassword ) {
142 return $this->mailPassword();
143 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
144 return $this->processLogin();
145 }
146 }
147 $this->mainLoginForm( '' );
148 }
149
150 /**
151 * @private
152 */
153 function addNewAccountMailPassword() {
154 global $wgOut;
155
156 if ( $this->mEmail == '' ) {
157 $this->mainLoginForm( wfMsgExt( 'noemail', array( 'parsemag', 'escape' ), $this->mUsername ) );
158 return;
159 }
160
161 $u = $this->addNewaccountInternal();
162
163 if ( $u == null ) {
164 return;
165 }
166
167 // Wipe the initial password and mail a temporary one
168 $u->setPassword( null );
169 $u->saveSettings();
170 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
171
172 wfRunHooks( 'AddNewAccount', array( $u, true ) );
173 $u->addNewUserLogEntry( true, $this->mReason );
174
175 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
176
177 if( !$result->isGood() ) {
178 $this->mainLoginForm( wfMsg( 'mailerror', $result->getWikiText() ) );
179 } else {
180 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
181 $wgOut->returnToMain( false );
182 }
183 }
184
185 /**
186 * @private
187 */
188 function addNewAccount() {
189 global $wgUser, $wgEmailAuthentication, $wgOut;
190
191 # Create the account and abort if there's a problem doing so
192 $u = $this->addNewAccountInternal();
193 if( $u == null ) {
194 return;
195 }
196
197 # If we showed up language selection links, and one was in use, be
198 # smart (and sensible) and save that language as the user's preference
199 global $wgLoginLanguageSelector;
200 if( $wgLoginLanguageSelector && $this->mLanguage ) {
201 $u->setOption( 'language', $this->mLanguage );
202 }
203
204 # Send out an email authentication message if needed
205 if( $wgEmailAuthentication && User::isValidEmailAddr( $u->getEmail() ) ) {
206 $status = $u->sendConfirmationMail();
207 if( $status->isGood() ) {
208 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
209 } else {
210 $wgOut->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
211 }
212 }
213
214 # Save settings (including confirmation token)
215 $u->saveSettings();
216
217 # If not logged in, assume the new account as the current one and set
218 # session cookies then show a "welcome" message or a "need cookies"
219 # message as needed
220 if( $wgUser->isAnon() ) {
221 $wgUser = $u;
222 $wgUser->setCookies();
223 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
224 $wgUser->addNewUserLogEntry();
225 if( $this->hasSessionCookie() ) {
226 return $this->successfulCreation();
227 } else {
228 return $this->cookieRedirectCheck( 'new' );
229 }
230 } else {
231 # Confirm that the account was created
232 $self = SpecialPage::getTitleFor( 'Userlogin' );
233 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
234 $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
235 $wgOut->returnToMain( false, $self );
236 wfRunHooks( 'AddNewAccount', array( $u, false ) );
237 $u->addNewUserLogEntry( false, $this->mReason );
238 return true;
239 }
240 }
241
242 /**
243 * @private
244 */
245 function addNewAccountInternal() {
246 global $wgUser, $wgOut;
247 global $wgMemc, $wgAccountCreationThrottle;
248 global $wgAuth, $wgMinimalPasswordLength;
249 global $wgEmailConfirmToEdit;
250
251 // If the user passes an invalid domain, something is fishy
252 if( !$wgAuth->validDomain( $this->mDomain ) ) {
253 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
254 return false;
255 }
256
257 // If we are not allowing users to login locally, we should be checking
258 // to see if the user is actually able to authenticate to the authenti-
259 // cation server before they create an account (otherwise, they can
260 // create a local account and login as any domain user). We only need
261 // to check this for domains that aren't local.
262 if( 'local' != $this->mDomain && $this->mDomain != '' ) {
263 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mUsername ) || !$wgAuth->authenticate( $this->mUsername, $this->mPassword ) ) ) {
264 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
265 return false;
266 }
267 }
268
269 if ( wfReadOnly() ) {
270 $wgOut->readOnlyPage();
271 return false;
272 }
273
274 # Request forgery checks.
275 if ( !self::getCreateaccountToken() ) {
276 self::setCreateaccountToken();
277 $this->mainLoginForm( wfMsgExt( 'nocookiesfornew', array( 'parseinline' ) ) );
278 return false;
279 }
280
281 # The user didn't pass a createaccount token
282 if ( !$this->mToken ) {
283 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
284 return false;
285 }
286
287 # Validate the createaccount token
288 if ( $this->mToken !== self::getCreateaccountToken() ) {
289 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
290 return false;
291 }
292
293 # Check permissions
294 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
295 $wgOut->permissionRequired( 'createaccount' );
296 return false;
297 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
298 $this->userBlockedMessage();
299 return false;
300 }
301
302 $ip = wfGetIP();
303 if ( $wgUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
304 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
305 return false;
306 }
307
308 # Now create a dummy user ($u) and check if it is valid
309 $name = trim( $this->mUsername );
310 $u = User::newFromName( $name, 'creatable' );
311 if ( !is_object( $u ) ) {
312 $this->mainLoginForm( wfMsg( 'noname' ) );
313 return false;
314 }
315
316 if ( 0 != $u->idForName() ) {
317 $this->mainLoginForm( wfMsg( 'userexists' ) );
318 return false;
319 }
320
321 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
322 $this->mainLoginForm( wfMsg( 'badretype' ) );
323 return false;
324 }
325
326 # check for minimal password length
327 $valid = $u->getPasswordValidity( $this->mPassword );
328 if ( $valid !== true ) {
329 if ( !$this->mCreateaccountMail ) {
330 $this->mainLoginForm( wfMsgExt( $valid, array( 'parsemag' ), $wgMinimalPasswordLength ) );
331 return false;
332 } else {
333 # do not force a password for account creation by email
334 # set invalid password, it will be replaced later by a random generated password
335 $this->mPassword = null;
336 }
337 }
338
339 # if you need a confirmed email address to edit, then obviously you
340 # need an email address.
341 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
342 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
343 return false;
344 }
345
346 if( !empty( $this->mEmail ) && !User::isValidEmailAddr( $this->mEmail ) ) {
347 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
348 return false;
349 }
350
351 # Set some additional data so the AbortNewAccount hook can be used for
352 # more than just username validation
353 $u->setEmail( $this->mEmail );
354 $u->setRealName( $this->mRealName );
355
356 $abortError = '';
357 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
358 // Hook point to add extra creation throttles and blocks
359 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
360 $this->mainLoginForm( $abortError );
361 return false;
362 }
363
364 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
365 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
366 $value = $wgMemc->get( $key );
367 if ( !$value ) {
368 $wgMemc->set( $key, 0, 86400 );
369 }
370 if ( $value >= $wgAccountCreationThrottle ) {
371 $this->throttleHit( $wgAccountCreationThrottle );
372 return false;
373 }
374 $wgMemc->incr( $key );
375 }
376
377 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
378 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
379 return false;
380 }
381
382 self::clearCreateaccountToken();
383 return $this->initUser( $u, false );
384 }
385
386 /**
387 * Actually add a user to the database.
388 * Give it a User object that has been initialised with a name.
389 *
390 * @param $u User object.
391 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
392 * @return User object.
393 * @private
394 */
395 function initUser( $u, $autocreate ) {
396 global $wgAuth;
397
398 $u->addToDatabase();
399
400 if ( $wgAuth->allowPasswordChange() ) {
401 $u->setPassword( $this->mPassword );
402 }
403
404 $u->setEmail( $this->mEmail );
405 $u->setRealName( $this->mRealName );
406 $u->setToken();
407
408 $wgAuth->initUser( $u, $autocreate );
409
410 if ( $this->mExtUser ) {
411 $this->mExtUser->linkToLocal( $u->getId() );
412 $email = $this->mExtUser->getPref( 'emailaddress' );
413 if ( $email && !$this->mEmail ) {
414 $u->setEmail( $email );
415 }
416 }
417
418 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
419 $u->saveSettings();
420
421 # Update user count
422 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
423 $ssUpdate->doUpdate();
424
425 return $u;
426 }
427
428 /**
429 * Internally authenticate the login request.
430 *
431 * This may create a local account as a side effect if the
432 * authentication plugin allows transparent local account
433 * creation.
434 */
435 public function authenticateUserData() {
436 global $wgUser, $wgAuth, $wgMemc;
437
438 if ( $this->mUsername == '' ) {
439 return self::NO_NAME;
440 }
441
442 // We require a login token to prevent login CSRF
443 // Handle part of this before incrementing the throttle so
444 // token-less login attempts don't count towards the throttle
445 // but wrong-token attempts do.
446
447 // If the user doesn't have a login token yet, set one.
448 if ( !self::getLoginToken() ) {
449 self::setLoginToken();
450 return self::NEED_TOKEN;
451 }
452 // If the user didn't pass a login token, tell them we need one
453 if ( !$this->mToken ) {
454 return self::NEED_TOKEN;
455 }
456
457 global $wgPasswordAttemptThrottle;
458
459 $throttleCount = 0;
460 if ( is_array( $wgPasswordAttemptThrottle ) ) {
461 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername ) );
462 $count = $wgPasswordAttemptThrottle['count'];
463 $period = $wgPasswordAttemptThrottle['seconds'];
464
465 $throttleCount = $wgMemc->get( $throttleKey );
466 if ( !$throttleCount ) {
467 $wgMemc->add( $throttleKey, 1, $period ); // start counter
468 } elseif ( $throttleCount < $count ) {
469 $wgMemc->incr( $throttleKey );
470 } elseif ( $throttleCount >= $count ) {
471 return self::THROTTLED;
472 }
473 }
474
475 // Validate the login token
476 if ( $this->mToken !== self::getLoginToken() ) {
477 return self::WRONG_TOKEN;
478 }
479
480 // Load $wgUser now, and check to see if we're logging in as the same
481 // name. This is necessary because loading $wgUser (say by calling
482 // getName()) calls the UserLoadFromSession hook, which potentially
483 // creates the user in the database. Until we load $wgUser, checking
484 // for user existence using User::newFromName($name)->getId() below
485 // will effectively be using stale data.
486 if ( $wgUser->getName() === $this->mUsername ) {
487 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
488 return self::SUCCESS;
489 }
490
491 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
492
493 # TODO: Allow some magic here for invalid external names, e.g., let the
494 # user choose a different wiki name.
495 $u = User::newFromName( $this->mUsername );
496 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
497 return self::ILLEGAL;
498 }
499
500 $isAutoCreated = false;
501 if ( 0 == $u->getID() ) {
502 $status = $this->attemptAutoCreate( $u );
503 if ( $status !== self::SUCCESS ) {
504 return $status;
505 } else {
506 $isAutoCreated = true;
507 }
508 } else {
509 global $wgExternalAuthType, $wgAutocreatePolicy;
510 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
511 && is_object( $this->mExtUser )
512 && $this->mExtUser->authenticate( $this->mPassword ) ) {
513 # The external user and local user have the same name and
514 # password, so we assume they're the same.
515 $this->mExtUser->linkToLocal( $u->getID() );
516 }
517
518 $u->load();
519 }
520
521 // Give general extensions, such as a captcha, a chance to abort logins
522 $abort = self::ABORTED;
523 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort ) ) ) {
524 return $abort;
525 }
526
527 global $wgBlockDisablesLogin;
528 if ( !$u->checkPassword( $this->mPassword ) ) {
529 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
530 // The e-mailed temporary password should not be used for actu-
531 // al logins; that's a very sloppy habit, and insecure if an
532 // attacker has a few seconds to click "search" on someone's o-
533 // pen mail reader.
534 //
535 // Allow it to be used only to reset the password a single time
536 // to a new value, which won't be in the user's e-mail ar-
537 // chives.
538 //
539 // For backwards compatibility, we'll still recognize it at the
540 // login form to minimize surprises for people who have been
541 // logging in with a temporary password for some time.
542 //
543 // As a side-effect, we can authenticate the user's e-mail ad-
544 // dress if it's not already done, since the temporary password
545 // was sent via e-mail.
546 if( !$u->isEmailConfirmed() ) {
547 $u->confirmEmail();
548 $u->saveSettings();
549 }
550
551 // At this point we just return an appropriate code/ indicating
552 // that the UI should show a password reset form; bot inter-
553 // faces etc will probably just fail cleanly here.
554 $retval = self::RESET_PASS;
555 } else {
556 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
557 }
558 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
559 // If we've enabled it, make it so that a blocked user cannot login
560 $retval = self::USER_BLOCKED;
561 } else {
562 $wgAuth->updateUser( $u );
563 $wgUser = $u;
564
565 // Please reset throttle for successful logins, thanks!
566 if( $throttleCount ) {
567 $wgMemc->delete( $throttleKey );
568 }
569
570 if ( $isAutoCreated ) {
571 // Must be run after $wgUser is set, for correct new user log
572 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
573 }
574
575 $retval = self::SUCCESS;
576 }
577 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
578 return $retval;
579 }
580
581 /**
582 * Attempt to automatically create a user on login. Only succeeds if there
583 * is an external authentication method which allows it.
584 * @return integer Status code
585 */
586 function attemptAutoCreate( $user ) {
587 global $wgAuth, $wgUser, $wgAutocreatePolicy;
588
589 if ( $wgUser->isBlockedFromCreateAccount() ) {
590 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
591 return self::CREATE_BLOCKED;
592 }
593
594 /**
595 * If the external authentication plugin allows it, automatically cre-
596 * ate a new account for users that are externally defined but have not
597 * yet logged in.
598 */
599 if ( $this->mExtUser ) {
600 # mExtUser is neither null nor false, so use the new ExternalAuth
601 # system.
602 if ( $wgAutocreatePolicy == 'never' ) {
603 return self::NOT_EXISTS;
604 }
605 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
606 return self::WRONG_PLUGIN_PASS;
607 }
608 } else {
609 # Old AuthPlugin.
610 if ( !$wgAuth->autoCreate() ) {
611 return self::NOT_EXISTS;
612 }
613 if ( !$wgAuth->userExists( $user->getName() ) ) {
614 wfDebug( __METHOD__ . ": user does not exist\n" );
615 return self::NOT_EXISTS;
616 }
617 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
618 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
619 return self::WRONG_PLUGIN_PASS;
620 }
621 }
622
623 wfDebug( __METHOD__ . ": creating account\n" );
624 $this->initUser( $user, true );
625 return self::SUCCESS;
626 }
627
628 function processLogin() {
629 global $wgUser;
630
631 switch ( $this->authenticateUserData() ) {
632 case self::SUCCESS:
633 # We've verified now, update the real record
634 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
635 $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
636 $wgUser->saveSettings();
637 } else {
638 $wgUser->invalidateCache();
639 }
640 $wgUser->setCookies();
641 self::clearLoginToken();
642
643 // Reset the throttle
644 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername ) );
645 global $wgMemc;
646 $wgMemc->delete( $key );
647
648 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
649 /* Replace the language object to provide user interface in
650 * correct language immediately on this first page load.
651 */
652 global $wgLang, $wgRequest;
653 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
654 $wgLang = Language::factory( $code );
655 return $this->successfulLogin();
656 } else {
657 return $this->cookieRedirectCheck( 'login' );
658 }
659 break;
660
661 case self::NEED_TOKEN:
662 $this->mainLoginForm( wfMsgExt( 'nocookiesforlogin', array( 'parseinline' ) ) );
663 break;
664 case self::WRONG_TOKEN:
665 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
666 break;
667 case self::NO_NAME:
668 case self::ILLEGAL:
669 $this->mainLoginForm( wfMsg( 'noname' ) );
670 break;
671 case self::WRONG_PLUGIN_PASS:
672 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
673 break;
674 case self::NOT_EXISTS:
675 if( $wgUser->isAllowed( 'createaccount' ) ) {
676 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mUsername ) ) );
677 } else {
678 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mUsername ) ) );
679 }
680 break;
681 case self::WRONG_PASS:
682 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
683 break;
684 case self::EMPTY_PASS:
685 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
686 break;
687 case self::RESET_PASS:
688 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
689 break;
690 case self::CREATE_BLOCKED:
691 $this->userBlockedMessage();
692 break;
693 case self::THROTTLED:
694 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
695 break;
696 case self::USER_BLOCKED:
697 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
698 array( 'parsemag', 'escape' ), $this->mUsername ) );
699 break;
700 default:
701 throw new MWException( 'Unhandled case value' );
702 }
703 }
704
705 function resetLoginForm( $error ) {
706 global $wgOut;
707 $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
708 $reset = new SpecialResetpass();
709 $reset->execute( null );
710 }
711
712 /**
713 * @private
714 */
715 function mailPassword() {
716 global $wgUser, $wgOut, $wgAuth;
717
718 if ( wfReadOnly() ) {
719 $wgOut->readOnlyPage();
720 return false;
721 }
722
723 if( !$wgAuth->allowPasswordChange() ) {
724 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
725 return;
726 }
727
728 # Check against blocked IPs so blocked users can't flood admins
729 # with password resets
730 if( $wgUser->isBlocked() ) {
731 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
732 return;
733 }
734
735 # Check for hooks
736 $error = null;
737 if ( !wfRunHooks( 'UserLoginMailPassword', array( $this->mUsername, &$error ) ) ) {
738 $this->mainLoginForm( $error );
739 return;
740 }
741
742 # If the user doesn't have a login token yet, set one.
743 if ( !self::getLoginToken() ) {
744 self::setLoginToken();
745 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
746 return;
747 }
748
749 # If the user didn't pass a login token, tell them we need one
750 if ( !$this->mToken ) {
751 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
752 return;
753 }
754
755 # Check against the rate limiter
756 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
757 $wgOut->rateLimited();
758 return;
759 }
760
761 if ( $this->mUsername == '' ) {
762 $this->mainLoginForm( wfMsg( 'noname' ) );
763 return;
764 }
765 $u = User::newFromName( $this->mUsername );
766 if( !$u instanceof User ) {
767 $this->mainLoginForm( wfMsg( 'noname' ) );
768 return;
769 }
770 if ( 0 == $u->getID() ) {
771 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
772 return;
773 }
774
775 # Validate the login token
776 if ( $this->mToken !== self::getLoginToken() ) {
777 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
778 return;
779 }
780
781 # Check against password throttle
782 if ( $u->isPasswordReminderThrottled() ) {
783 global $wgPasswordReminderResendTime;
784 # Round the time in hours to 3 d.p., in case someone is specifying
785 # minutes or seconds.
786 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
787 round( $wgPasswordReminderResendTime, 3 ) ) );
788 return;
789 }
790
791 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
792 if( $result->isGood() ) {
793 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
794 self::clearLoginToken();
795 } else {
796 $this->mainLoginForm( $result->getWikiText( 'mailerror' ) );
797 }
798 }
799
800
801 /**
802 * @param $u User object
803 * @param $throttle Boolean
804 * @param $emailTitle String: message name of email title
805 * @param $emailText String: message name of email text
806 * @return Status object
807 * @private
808 */
809 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
810 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
811
812 if ( $u->getEmail() == '' ) {
813 return Status::newFatal( 'noemail', $u->getName() );
814 }
815 $ip = wfGetIP();
816 if( !$ip ) {
817 return Status::newFatal( 'badipaddress' );
818 }
819
820 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
821
822 $np = $u->randomPassword();
823 $u->setNewpassword( $np, $throttle );
824 $u->saveSettings();
825 $userLanguage = $u->getOption( 'language' );
826 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
827 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
828 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
829
830 return $result;
831 }
832
833
834 /**
835 * Run any hooks registered for logins, then HTTP redirect to
836 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
837 * nice message here, but that's really not as useful as just being sent to
838 * wherever you logged in from. It should be clear that the action was
839 * successful, given the lack of error messages plus the appearance of your
840 * name in the upper right.
841 *
842 * @private
843 */
844 function successfulLogin() {
845 global $wgUser, $wgOut;
846
847 # Run any hooks; display injected HTML if any, else redirect
848 $injected_html = '';
849 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
850
851 if( $injected_html !== '' ) {
852 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
853 } else {
854 $titleObj = Title::newFromText( $this->mReturnTo );
855 if ( !$titleObj instanceof Title ) {
856 $titleObj = Title::newMainPage();
857 }
858 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
859 global $wgSecureLogin;
860 if( $wgSecureLogin && !$this->mStickHTTPS ) {
861 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
862 }
863 $wgOut->redirect( $redirectUrl );
864 }
865 }
866
867 /**
868 * Run any hooks registered for logins, then display a message welcoming
869 * the user.
870 *
871 * @private
872 */
873 function successfulCreation() {
874 global $wgUser;
875 # Run any hooks; display injected HTML
876 $injected_html = '';
877 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
878
879 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
880 }
881
882 /**
883 * Display a "login successful" page.
884 */
885 private function displaySuccessfulLogin( $msgname, $injected_html ) {
886 global $wgOut, $wgUser;
887
888 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
889 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
890 $wgOut->addHTML( $injected_html );
891
892 if ( !empty( $this->mReturnTo ) ) {
893 $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
894 } else {
895 $wgOut->returnToMain( null );
896 }
897 }
898
899 /** */
900 function userBlockedMessage() {
901 global $wgOut, $wgUser;
902
903 # Let's be nice about this, it's likely that this feature will be used
904 # for blocking large numbers of innocent people, e.g. range blocks on
905 # schools. Don't blame it on the user. There's a small chance that it
906 # really is the user's fault, i.e. the username is blocked and they
907 # haven't bothered to log out before trying to create an account to
908 # evade it, but we'll leave that to their guilty conscience to figure
909 # out.
910
911 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
912
913 $ip = wfGetIP();
914 $blocker = User::whoIs( $wgUser->mBlock->mBy );
915 $block_reason = $wgUser->mBlock->mReason;
916
917 if ( strval( $block_reason ) === '' ) {
918 $block_reason = wfMsg( 'blockednoreason' );
919 }
920 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
921 $wgOut->returnToMain( false );
922 }
923
924 /**
925 * @private
926 */
927 function mainLoginForm( $msg, $msgtype = 'error' ) {
928 global $wgUser, $wgOut, $wgHiddenPrefs, $wgEnableEmail;
929 global $wgRequest, $wgLoginLanguageSelector;
930 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
931 global $wgSecureLogin;
932
933 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
934
935 if ( $this->mType == 'signup' ) {
936 // Block signup here if in readonly. Keeps user from
937 // going through the process (filling out data, etc)
938 // and being informed later.
939 if ( wfReadOnly() ) {
940 $wgOut->readOnlyPage();
941 return;
942 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
943 $this->userBlockedMessage();
944 return;
945 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
946 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
947 return;
948 }
949 }
950
951 if ( $this->mUsername == '' ) {
952 if ( $wgUser->isLoggedIn() ) {
953 $this->mUsername = $wgUser->getName();
954 } else {
955 $this->mUsername = $wgRequest->getCookie( 'UserName' );
956 }
957 }
958
959 if ( $this->mType == 'signup' ) {
960 global $wgLivePasswordStrengthChecks;
961 if ( $wgLivePasswordStrengthChecks ) {
962 $wgOut->addPasswordSecurity( 'wpPassword2', 'wpRetype' );
963 }
964 $template = new UsercreateTemplate();
965 $q = 'action=submitlogin&type=signup';
966 $linkq = 'type=login';
967 $linkmsg = 'gotaccount';
968 } else {
969 $template = new UserloginTemplate();
970 $q = 'action=submitlogin&type=login';
971 $linkq = 'type=signup';
972 $linkmsg = 'nologin';
973 }
974
975 if ( !empty( $this->mReturnTo ) ) {
976 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
977 if ( !empty( $this->mReturnToQuery ) ) {
978 $returnto .= '&returntoquery=' .
979 wfUrlencode( $this->mReturnToQuery );
980 }
981 $q .= $returnto;
982 $linkq .= $returnto;
983 }
984
985 # Pass any language selection on to the mode switch link
986 if( $wgLoginLanguageSelector && $this->mLanguage ) {
987 $linkq .= '&uselang=' . $this->mLanguage;
988 }
989
990 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
991 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
992 $link .= '</a>';
993
994 # Don't show a "create account" link if the user can't
995 if( $this->showCreateOrLoginLink( $wgUser ) ) {
996 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
997 } else {
998 $template->set( 'link', '' );
999 }
1000
1001 $template->set( 'header', '' );
1002 $template->set( 'name', $this->mUsername );
1003 $template->set( 'password', $this->mPassword );
1004 $template->set( 'retype', $this->mRetype );
1005 $template->set( 'email', $this->mEmail );
1006 $template->set( 'realname', $this->mRealName );
1007 $template->set( 'domain', $this->mDomain );
1008 $template->set( 'reason', $this->mReason );
1009
1010 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1011 $template->set( 'message', $msg );
1012 $template->set( 'messagetype', $msgtype );
1013 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1014 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1015 $template->set( 'useemail', $wgEnableEmail );
1016 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1017 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1018 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1019 $template->set( 'usereason', $wgUser->isLoggedIn() );
1020 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) || $this->mRemember );
1021 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1022 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1023
1024 if ( $this->mType == 'signup' ) {
1025 if ( !self::getCreateaccountToken() ) {
1026 self::setCreateaccountToken();
1027 }
1028 $template->set( 'token', self::getCreateaccountToken() );
1029 } else {
1030 if ( !self::getLoginToken() ) {
1031 self::setLoginToken();
1032 }
1033 $template->set( 'token', self::getLoginToken() );
1034 }
1035
1036 # Prepare language selection links as needed
1037 if( $wgLoginLanguageSelector ) {
1038 $template->set( 'languages', $this->makeLanguageSelector() );
1039 if( $this->mLanguage )
1040 $template->set( 'uselang', $this->mLanguage );
1041 }
1042
1043 // Give authentication and captcha plugins a chance to modify the form
1044 $wgAuth->modifyUITemplate( $template, $this->mType );
1045 if ( $this->mType == 'signup' ) {
1046 wfRunHooks( 'UserCreateForm', array( &$template ) );
1047 } else {
1048 wfRunHooks( 'UserLoginForm', array( &$template ) );
1049 }
1050
1051 // Changes the title depending on permissions for creating account
1052 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1053 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1054 } else {
1055 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1056 }
1057
1058 $wgOut->disallowUserJs(); // just in case...
1059 $wgOut->addTemplate( $template );
1060 }
1061
1062 /**
1063 * @private
1064 */
1065 function showCreateOrLoginLink( &$user ) {
1066 if( $this->mType == 'signup' ) {
1067 return( true );
1068 } elseif( $user->isAllowed( 'createaccount' ) ) {
1069 return( true );
1070 } else {
1071 return( false );
1072 }
1073 }
1074
1075 /**
1076 * Check if a session cookie is present.
1077 *
1078 * This will not pick up a cookie set during _this_ request, but is meant
1079 * to ensure that the client is returning the cookie which was set on a
1080 * previous pass through the system.
1081 *
1082 * @private
1083 */
1084 function hasSessionCookie() {
1085 global $wgDisableCookieCheck, $wgRequest;
1086 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
1087 }
1088
1089 /**
1090 * Get the login token from the current session
1091 */
1092 public static function getLoginToken() {
1093 global $wgRequest;
1094 return $wgRequest->getSessionData( 'wsLoginToken' );
1095 }
1096
1097 /**
1098 * Randomly generate a new login token and attach it to the current session
1099 */
1100 public static function setLoginToken() {
1101 global $wgRequest;
1102 // Use User::generateToken() instead of $user->editToken()
1103 // because the latter reuses $_SESSION['wsEditToken']
1104 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1105 }
1106
1107 /**
1108 * Remove any login token attached to the current session
1109 */
1110 public static function clearLoginToken() {
1111 global $wgRequest;
1112 $wgRequest->setSessionData( 'wsLoginToken', null );
1113 }
1114
1115 /**
1116 * Get the createaccount token from the current session
1117 */
1118 public static function getCreateaccountToken() {
1119 global $wgRequest;
1120 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1121 }
1122
1123 /**
1124 * Randomly generate a new createaccount token and attach it to the current session
1125 */
1126 public static function setCreateaccountToken() {
1127 global $wgRequest;
1128 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1129 }
1130
1131 /**
1132 * Remove any createaccount token attached to the current session
1133 */
1134 public static function clearCreateaccountToken() {
1135 global $wgRequest;
1136 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1137 }
1138
1139 /**
1140 * @private
1141 */
1142 function cookieRedirectCheck( $type ) {
1143 global $wgOut;
1144
1145 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1146 $query = array( 'wpCookieCheck' => $type );
1147 if ( $this->mReturnTo ) {
1148 $query['returnto'] = $this->mReturnTo;
1149 }
1150 $check = $titleObj->getFullURL( $query );
1151
1152 return $wgOut->redirect( $check );
1153 }
1154
1155 /**
1156 * @private
1157 */
1158 function onCookieRedirectCheck( $type ) {
1159 if ( !$this->hasSessionCookie() ) {
1160 if ( $type == 'new' ) {
1161 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1162 } elseif ( $type == 'login' ) {
1163 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1164 } else {
1165 # shouldn't happen
1166 return $this->mainLoginForm( wfMsg( 'error' ) );
1167 }
1168 } else {
1169 return $this->successfulLogin();
1170 }
1171 }
1172
1173 /**
1174 * @private
1175 */
1176 function throttleHit( $limit ) {
1177 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1178 }
1179
1180 /**
1181 * Produce a bar of links which allow the user to select another language
1182 * during login/registration but retain "returnto"
1183 *
1184 * @return string
1185 */
1186 function makeLanguageSelector() {
1187 global $wgLang;
1188
1189 $msg = wfMsgForContent( 'loginlanguagelinks' );
1190 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
1191 $langs = explode( "\n", $msg );
1192 $links = array();
1193 foreach( $langs as $lang ) {
1194 $lang = trim( $lang, '* ' );
1195 $parts = explode( '|', $lang );
1196 if ( count( $parts ) >= 2 ) {
1197 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1198 }
1199 }
1200 return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1201 } else {
1202 return '';
1203 }
1204 }
1205
1206 /**
1207 * Create a language selector link for a particular language
1208 * Links back to this page preserving type and returnto
1209 *
1210 * @param $text Link text
1211 * @param $lang Language code
1212 */
1213 function makeLanguageSelectorLink( $text, $lang ) {
1214 global $wgUser;
1215 $self = SpecialPage::getTitleFor( 'Userlogin' );
1216 $attr = array( 'uselang' => $lang );
1217 if( $this->mType == 'signup' ) {
1218 $attr['type'] = 'signup';
1219 }
1220 if( $this->mReturnTo ) {
1221 $attr['returnto'] = $this->mReturnTo;
1222 }
1223 $skin = $wgUser->getSkin();
1224 return $skin->linkKnown(
1225 $self,
1226 htmlspecialchars( $text ),
1227 array(),
1228 $attr
1229 );
1230 }
1231 }