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