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