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