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