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