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