And some more function level documentation
[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 *
592 * @param $user User
593 *
594 * @return integer Status code
595 */
596 function attemptAutoCreate( $user ) {
597 global $wgAuth, $wgUser, $wgAutocreatePolicy;
598
599 if ( $wgUser->isBlockedFromCreateAccount() ) {
600 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
601 return self::CREATE_BLOCKED;
602 }
603
604 /**
605 * If the external authentication plugin allows it, automatically cre-
606 * ate a new account for users that are externally defined but have not
607 * yet logged in.
608 */
609 if ( $this->mExtUser ) {
610 # mExtUser is neither null nor false, so use the new ExternalAuth
611 # system.
612 if ( $wgAutocreatePolicy == 'never' ) {
613 return self::NOT_EXISTS;
614 }
615 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
616 return self::WRONG_PLUGIN_PASS;
617 }
618 } else {
619 # Old AuthPlugin.
620 if ( !$wgAuth->autoCreate() ) {
621 return self::NOT_EXISTS;
622 }
623 if ( !$wgAuth->userExists( $user->getName() ) ) {
624 wfDebug( __METHOD__ . ": user does not exist\n" );
625 return self::NOT_EXISTS;
626 }
627 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
628 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
629 return self::WRONG_PLUGIN_PASS;
630 }
631 }
632
633 wfDebug( __METHOD__ . ": creating account\n" );
634 $this->initUser( $user, true );
635 return self::SUCCESS;
636 }
637
638 function processLogin() {
639 global $wgUser;
640
641 switch ( $this->authenticateUserData() ) {
642 case self::SUCCESS:
643 # We've verified now, update the real record
644 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
645 $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
646 $wgUser->saveSettings();
647 } else {
648 $wgUser->invalidateCache();
649 }
650 $wgUser->setCookies();
651 self::clearLoginToken();
652
653 // Reset the throttle
654 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mUsername ) );
655 global $wgMemc;
656 $wgMemc->delete( $key );
657
658 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
659 /* Replace the language object to provide user interface in
660 * correct language immediately on this first page load.
661 */
662 global $wgLang, $wgRequest;
663 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
664 $wgLang = Language::factory( $code );
665 return $this->successfulLogin();
666 } else {
667 return $this->cookieRedirectCheck( 'login' );
668 }
669 break;
670
671 case self::NEED_TOKEN:
672 $this->mainLoginForm( wfMsgExt( 'nocookiesforlogin', array( 'parseinline' ) ) );
673 break;
674 case self::WRONG_TOKEN:
675 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
676 break;
677 case self::NO_NAME:
678 case self::ILLEGAL:
679 $this->mainLoginForm( wfMsg( 'noname' ) );
680 break;
681 case self::WRONG_PLUGIN_PASS:
682 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
683 break;
684 case self::NOT_EXISTS:
685 if( $wgUser->isAllowed( 'createaccount' ) ) {
686 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $this->mUsername ) );
687 } else {
688 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mUsername ) ) );
689 }
690 break;
691 case self::WRONG_PASS:
692 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
693 break;
694 case self::EMPTY_PASS:
695 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
696 break;
697 case self::RESET_PASS:
698 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
699 break;
700 case self::CREATE_BLOCKED:
701 $this->userBlockedMessage();
702 break;
703 case self::THROTTLED:
704 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
705 break;
706 case self::USER_BLOCKED:
707 $this->mainLoginForm( wfMsgExt( 'login-userblocked',
708 array( 'parsemag', 'escape' ), $this->mUsername ) );
709 break;
710 default:
711 throw new MWException( 'Unhandled case value' );
712 }
713 }
714
715 function resetLoginForm( $error ) {
716 global $wgOut;
717 $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
718 $reset = new SpecialResetpass();
719 $reset->execute( null );
720 }
721
722 /**
723 * @private
724 */
725 function mailPassword() {
726 global $wgUser, $wgOut, $wgAuth;
727
728 if ( wfReadOnly() ) {
729 $wgOut->readOnlyPage();
730 return false;
731 }
732
733 if( !$wgAuth->allowPasswordChange() ) {
734 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
735 return;
736 }
737
738 # Check against blocked IPs so blocked users can't flood admins
739 # with password resets
740 if( $wgUser->isBlocked() ) {
741 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
742 return;
743 }
744
745 # Check for hooks
746 $error = null;
747 if ( !wfRunHooks( 'UserLoginMailPassword', array( $this->mUsername, &$error ) ) ) {
748 $this->mainLoginForm( $error );
749 return;
750 }
751
752 # If the user doesn't have a login token yet, set one.
753 if ( !self::getLoginToken() ) {
754 self::setLoginToken();
755 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
756 return;
757 }
758
759 # If the user didn't pass a login token, tell them we need one
760 if ( !$this->mToken ) {
761 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
762 return;
763 }
764
765 # Check against the rate limiter
766 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
767 $wgOut->rateLimited();
768 return;
769 }
770
771 if ( $this->mUsername == '' ) {
772 $this->mainLoginForm( wfMsg( 'noname' ) );
773 return;
774 }
775 $u = User::newFromName( $this->mUsername );
776 if( !$u instanceof User ) {
777 $this->mainLoginForm( wfMsg( 'noname' ) );
778 return;
779 }
780 if ( 0 == $u->getID() ) {
781 $this->mainLoginForm( wfMsgExt( 'nosuchuser', 'parseinline', $u->getName() ) );
782 return;
783 }
784
785 # Validate the login token
786 if ( $this->mToken !== self::getLoginToken() ) {
787 $this->mainLoginForm( wfMsg( 'sessionfailure' ) );
788 return;
789 }
790
791 # Check against password throttle
792 if ( $u->isPasswordReminderThrottled() ) {
793 global $wgPasswordReminderResendTime;
794 # Round the time in hours to 3 d.p., in case someone is specifying
795 # minutes or seconds.
796 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
797 round( $wgPasswordReminderResendTime, 3 ) ) );
798 return;
799 }
800
801 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
802 if( $result->isGood() ) {
803 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
804 self::clearLoginToken();
805 } else {
806 $this->mainLoginForm( $result->getWikiText( 'mailerror' ) );
807 }
808 }
809
810
811 /**
812 * @param $u User object
813 * @param $throttle Boolean
814 * @param $emailTitle String: message name of email title
815 * @param $emailText String: message name of email text
816 * @return Status object
817 * @private
818 */
819 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
820 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
821
822 if ( $u->getEmail() == '' ) {
823 return Status::newFatal( 'noemail', $u->getName() );
824 }
825 $ip = wfGetIP();
826 if( !$ip ) {
827 return Status::newFatal( 'badipaddress' );
828 }
829
830 wfRunHooks( 'User::mailPasswordInternal', array( &$wgUser, &$ip, &$u ) );
831
832 $np = $u->randomPassword();
833 $u->setNewpassword( $np, $throttle );
834 $u->saveSettings();
835 $userLanguage = $u->getOption( 'language' );
836 $m = wfMsgExt( $emailText, array( 'parsemag', 'language' => $userLanguage ), $ip, $u->getName(), $np,
837 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
838 $result = $u->sendMail( wfMsgExt( $emailTitle, array( 'parsemag', 'language' => $userLanguage ) ), $m );
839
840 return $result;
841 }
842
843
844 /**
845 * Run any hooks registered for logins, then HTTP redirect to
846 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
847 * nice message here, but that's really not as useful as just being sent to
848 * wherever you logged in from. It should be clear that the action was
849 * successful, given the lack of error messages plus the appearance of your
850 * name in the upper right.
851 *
852 * @private
853 */
854 function successfulLogin() {
855 global $wgUser, $wgOut;
856
857 # Run any hooks; display injected HTML if any, else redirect
858 $injected_html = '';
859 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
860
861 if( $injected_html !== '' ) {
862 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
863 } else {
864 $titleObj = Title::newFromText( $this->mReturnTo );
865 if ( !$titleObj instanceof Title ) {
866 $titleObj = Title::newMainPage();
867 }
868 $redirectUrl = $titleObj->getFullURL( $this->mReturnToQuery );
869 global $wgSecureLogin;
870 if( $wgSecureLogin && !$this->mStickHTTPS ) {
871 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
872 }
873 $wgOut->redirect( $redirectUrl );
874 }
875 }
876
877 /**
878 * Run any hooks registered for logins, then display a message welcoming
879 * the user.
880 *
881 * @private
882 */
883 function successfulCreation() {
884 global $wgUser;
885 # Run any hooks; display injected HTML
886 $injected_html = '';
887 wfRunHooks( 'UserLoginComplete', array( &$wgUser, &$injected_html ) );
888
889 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
890 }
891
892 /**
893 * Display a "login successful" page.
894 */
895 private function displaySuccessfulLogin( $msgname, $injected_html ) {
896 global $wgOut, $wgUser;
897
898 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
899 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
900 $wgOut->addHTML( $injected_html );
901
902 if ( !empty( $this->mReturnTo ) ) {
903 $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
904 } else {
905 $wgOut->returnToMain( null );
906 }
907 }
908
909 /** */
910 function userBlockedMessage() {
911 global $wgOut, $wgUser;
912
913 # Let's be nice about this, it's likely that this feature will be used
914 # for blocking large numbers of innocent people, e.g. range blocks on
915 # schools. Don't blame it on the user. There's a small chance that it
916 # really is the user's fault, i.e. the username is blocked and they
917 # haven't bothered to log out before trying to create an account to
918 # evade it, but we'll leave that to their guilty conscience to figure
919 # out.
920
921 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
922
923 $ip = wfGetIP();
924 $blocker = User::whoIs( $wgUser->mBlock->mBy );
925 $block_reason = $wgUser->mBlock->mReason;
926
927 if ( strval( $block_reason ) === '' ) {
928 $block_reason = wfMsg( 'blockednoreason' );
929 }
930 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
931 $wgOut->returnToMain( false );
932 }
933
934 /**
935 * @private
936 */
937 function mainLoginForm( $msg, $msgtype = 'error' ) {
938 global $wgUser, $wgOut, $wgHiddenPrefs;
939 global $wgEnableEmail, $wgEnableUserEmail;
940 global $wgRequest, $wgLoginLanguageSelector;
941 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
942 global $wgSecureLogin;
943
944 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
945
946 if ( $this->mType == 'signup' ) {
947 // Block signup here if in readonly. Keeps user from
948 // going through the process (filling out data, etc)
949 // and being informed later.
950 if ( wfReadOnly() ) {
951 $wgOut->readOnlyPage();
952 return;
953 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
954 $this->userBlockedMessage();
955 return;
956 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
957 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
958 return;
959 }
960 }
961
962 if ( $this->mUsername == '' ) {
963 if ( $wgUser->isLoggedIn() ) {
964 $this->mUsername = $wgUser->getName();
965 } else {
966 $this->mUsername = $wgRequest->getCookie( 'UserName' );
967 }
968 }
969
970 if ( $this->mType == 'signup' ) {
971 global $wgLivePasswordStrengthChecks;
972 if ( $wgLivePasswordStrengthChecks ) {
973 $wgOut->addPasswordSecurity( 'wpPassword2', 'wpRetype' );
974 }
975 $template = new UsercreateTemplate();
976 $q = 'action=submitlogin&type=signup';
977 $linkq = 'type=login';
978 $linkmsg = 'gotaccount';
979 } else {
980 $template = new UserloginTemplate();
981 $q = 'action=submitlogin&type=login';
982 $linkq = 'type=signup';
983 $linkmsg = 'nologin';
984 }
985
986 if ( !empty( $this->mReturnTo ) ) {
987 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
988 if ( !empty( $this->mReturnToQuery ) ) {
989 $returnto .= '&returntoquery=' .
990 wfUrlencode( $this->mReturnToQuery );
991 }
992 $q .= $returnto;
993 $linkq .= $returnto;
994 }
995
996 # Pass any language selection on to the mode switch link
997 if( $wgLoginLanguageSelector && $this->mLanguage ) {
998 $linkq .= '&uselang=' . $this->mLanguage;
999 }
1000
1001 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalURL( $linkq ) ) . '">';
1002 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
1003 $link .= '</a>';
1004
1005 # Don't show a "create account" link if the user can't
1006 if( $this->showCreateOrLoginLink( $wgUser ) ) {
1007 $template->set( 'link', wfMsgExt( $linkmsg, array( 'parseinline', 'replaceafter' ), $link ) );
1008 } else {
1009 $template->set( 'link', '' );
1010 }
1011
1012 $template->set( 'header', '' );
1013 $template->set( 'name', $this->mUsername );
1014 $template->set( 'password', $this->mPassword );
1015 $template->set( 'retype', $this->mRetype );
1016 $template->set( 'email', $this->mEmail );
1017 $template->set( 'realname', $this->mRealName );
1018 $template->set( 'domain', $this->mDomain );
1019 $template->set( 'reason', $this->mReason );
1020
1021 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1022 $template->set( 'message', $msg );
1023 $template->set( 'messagetype', $msgtype );
1024 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
1025 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1026 $template->set( 'useemail', $wgEnableEmail );
1027 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1028 $template->set( 'emailothers', $wgEnableUserEmail );
1029 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1030 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1031 $template->set( 'usereason', $wgUser->isLoggedIn() );
1032 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) || $this->mRemember );
1033 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1034 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1035
1036 if ( $this->mType == 'signup' ) {
1037 if ( !self::getCreateaccountToken() ) {
1038 self::setCreateaccountToken();
1039 }
1040 $template->set( 'token', self::getCreateaccountToken() );
1041 } else {
1042 if ( !self::getLoginToken() ) {
1043 self::setLoginToken();
1044 }
1045 $template->set( 'token', self::getLoginToken() );
1046 }
1047
1048 # Prepare language selection links as needed
1049 if( $wgLoginLanguageSelector ) {
1050 $template->set( 'languages', $this->makeLanguageSelector() );
1051 if( $this->mLanguage )
1052 $template->set( 'uselang', $this->mLanguage );
1053 }
1054
1055 // Give authentication and captcha plugins a chance to modify the form
1056 $wgAuth->modifyUITemplate( $template, $this->mType );
1057 if ( $this->mType == 'signup' ) {
1058 wfRunHooks( 'UserCreateForm', array( &$template ) );
1059 } else {
1060 wfRunHooks( 'UserLoginForm', array( &$template ) );
1061 }
1062
1063 // Changes the title depending on permissions for creating account
1064 if ( $wgUser->isAllowed( 'createaccount' ) ) {
1065 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
1066 } else {
1067 $wgOut->setPageTitle( wfMsg( 'userloginnocreate' ) );
1068 }
1069
1070 $wgOut->disallowUserJs(); // just in case...
1071 $wgOut->addTemplate( $template );
1072 }
1073
1074 /**
1075 * @private
1076 *
1077 * @param $user User
1078 *
1079 * @return Boolean
1080 */
1081 function showCreateOrLoginLink( &$user ) {
1082 if( $this->mType == 'signup' ) {
1083 return true;
1084 } elseif( $user->isAllowed( 'createaccount' ) ) {
1085 return true;
1086 } else {
1087 return false;
1088 }
1089 }
1090
1091 /**
1092 * Check if a session cookie is present.
1093 *
1094 * This will not pick up a cookie set during _this_ request, but is meant
1095 * to ensure that the client is returning the cookie which was set on a
1096 * previous pass through the system.
1097 *
1098 * @private
1099 */
1100 function hasSessionCookie() {
1101 global $wgDisableCookieCheck, $wgRequest;
1102 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
1103 }
1104
1105 /**
1106 * Get the login token from the current session
1107 */
1108 public static function getLoginToken() {
1109 global $wgRequest;
1110 return $wgRequest->getSessionData( 'wsLoginToken' );
1111 }
1112
1113 /**
1114 * Randomly generate a new login token and attach it to the current session
1115 */
1116 public static function setLoginToken() {
1117 global $wgRequest;
1118 // Use User::generateToken() instead of $user->editToken()
1119 // because the latter reuses $_SESSION['wsEditToken']
1120 $wgRequest->setSessionData( 'wsLoginToken', User::generateToken() );
1121 }
1122
1123 /**
1124 * Remove any login token attached to the current session
1125 */
1126 public static function clearLoginToken() {
1127 global $wgRequest;
1128 $wgRequest->setSessionData( 'wsLoginToken', null );
1129 }
1130
1131 /**
1132 * Get the createaccount token from the current session
1133 */
1134 public static function getCreateaccountToken() {
1135 global $wgRequest;
1136 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1137 }
1138
1139 /**
1140 * Randomly generate a new createaccount token and attach it to the current session
1141 */
1142 public static function setCreateaccountToken() {
1143 global $wgRequest;
1144 $wgRequest->setSessionData( 'wsCreateaccountToken', User::generateToken() );
1145 }
1146
1147 /**
1148 * Remove any createaccount token attached to the current session
1149 */
1150 public static function clearCreateaccountToken() {
1151 global $wgRequest;
1152 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1153 }
1154
1155 /**
1156 * @private
1157 */
1158 function cookieRedirectCheck( $type ) {
1159 global $wgOut;
1160
1161 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1162 $query = array( 'wpCookieCheck' => $type );
1163 if ( $this->mReturnTo ) {
1164 $query['returnto'] = $this->mReturnTo;
1165 }
1166 $check = $titleObj->getFullURL( $query );
1167
1168 return $wgOut->redirect( $check );
1169 }
1170
1171 /**
1172 * @private
1173 */
1174 function onCookieRedirectCheck( $type ) {
1175 if ( !$this->hasSessionCookie() ) {
1176 if ( $type == 'new' ) {
1177 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1178 } elseif ( $type == 'login' ) {
1179 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1180 } else {
1181 # shouldn't happen
1182 return $this->mainLoginForm( wfMsg( 'error' ) );
1183 }
1184 } else {
1185 return $this->successfulLogin();
1186 }
1187 }
1188
1189 /**
1190 * @private
1191 */
1192 function throttleHit( $limit ) {
1193 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1194 }
1195
1196 /**
1197 * Produce a bar of links which allow the user to select another language
1198 * during login/registration but retain "returnto"
1199 *
1200 * @return string
1201 */
1202 function makeLanguageSelector() {
1203 global $wgLang;
1204
1205 $msg = wfMessage( 'loginlanguagelinks' )->inContentLanguage();
1206 if( !$msg->isBlank() ) {
1207 $langs = explode( "\n", $msg->text() );
1208 $links = array();
1209 foreach( $langs as $lang ) {
1210 $lang = trim( $lang, '* ' );
1211 $parts = explode( '|', $lang );
1212 if ( count( $parts ) >= 2 ) {
1213 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1214 }
1215 }
1216 return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1217 } else {
1218 return '';
1219 }
1220 }
1221
1222 /**
1223 * Create a language selector link for a particular language
1224 * Links back to this page preserving type and returnto
1225 *
1226 * @param $text Link text
1227 * @param $lang Language code
1228 */
1229 function makeLanguageSelectorLink( $text, $lang ) {
1230 global $wgUser;
1231 $self = SpecialPage::getTitleFor( 'Userlogin' );
1232 $attr = array( 'uselang' => $lang );
1233 if( $this->mType == 'signup' ) {
1234 $attr['type'] = 'signup';
1235 }
1236 if( $this->mReturnTo ) {
1237 $attr['returnto'] = $this->mReturnTo;
1238 }
1239 $skin = $wgUser->getSkin();
1240 return $skin->linkKnown(
1241 $self,
1242 htmlspecialchars( $text ),
1243 array(),
1244 $attr
1245 );
1246 }
1247 }