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