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