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