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