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