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