Merge "LivePreview: bind a delegated click event for #wpPreview/Diff"
[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 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
468 $ssUpdate->doUpdate();
469
470 return $u;
471 }
472
473 /**
474 * Internally authenticate the login request.
475 *
476 * This may create a local account as a side effect if the
477 * authentication plugin allows transparent local account
478 * creation.
479 * @return int
480 */
481 public function authenticateUserData() {
482 global $wgUser, $wgAuth;
483
484 $this->load();
485
486 if ( $this->mUsername == '' ) {
487 return self::NO_NAME;
488 }
489
490 // We require a login token to prevent login CSRF
491 // Handle part of this before incrementing the throttle so
492 // token-less login attempts don't count towards the throttle
493 // but wrong-token attempts do.
494
495 // If the user doesn't have a login token yet, set one.
496 if ( !self::getLoginToken() ) {
497 self::setLoginToken();
498 return self::NEED_TOKEN;
499 }
500 // If the user didn't pass a login token, tell them we need one
501 if ( !$this->mToken ) {
502 return self::NEED_TOKEN;
503 }
504
505 $throttleCount = self::incLoginThrottle( $this->mUsername );
506 if ( $throttleCount === true ) {
507 return self::THROTTLED;
508 }
509
510 // Validate the login token
511 if ( $this->mToken !== self::getLoginToken() ) {
512 return self::WRONG_TOKEN;
513 }
514
515 // Load the current user now, and check to see if we're logging in as
516 // the same name. This is necessary because loading the current user
517 // (say by calling getName()) calls the UserLoadFromSession hook, which
518 // potentially creates the user in the database. Until we load $wgUser,
519 // checking for user existence using User::newFromName($name)->getId() below
520 // will effectively be using stale data.
521 if ( $this->getUser()->getName() === $this->mUsername ) {
522 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
523 return self::SUCCESS;
524 }
525
526 $this->mExtUser = ExternalUser::newFromName( $this->mUsername );
527
528 # TODO: Allow some magic here for invalid external names, e.g., let the
529 # user choose a different wiki name.
530 $u = User::newFromName( $this->mUsername );
531 if( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
532 return self::ILLEGAL;
533 }
534
535 $isAutoCreated = false;
536 if ( 0 == $u->getID() ) {
537 $status = $this->attemptAutoCreate( $u );
538 if ( $status !== self::SUCCESS ) {
539 return $status;
540 } else {
541 $isAutoCreated = true;
542 }
543 } else {
544 global $wgExternalAuthType, $wgAutocreatePolicy;
545 if ( $wgExternalAuthType && $wgAutocreatePolicy != 'never'
546 && is_object( $this->mExtUser )
547 && $this->mExtUser->authenticate( $this->mPassword ) ) {
548 # The external user and local user have the same name and
549 # password, so we assume they're the same.
550 $this->mExtUser->linkToLocal( $u->getID() );
551 }
552
553 $u->load();
554 }
555
556 // Give general extensions, such as a captcha, a chance to abort logins
557 $abort = self::ABORTED;
558 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$this->mAbortLoginErrorMsg ) ) ) {
559 return $abort;
560 }
561
562 global $wgBlockDisablesLogin;
563 if ( !$u->checkPassword( $this->mPassword ) ) {
564 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
565 // The e-mailed temporary password should not be used for actu-
566 // al logins; that's a very sloppy habit, and insecure if an
567 // attacker has a few seconds to click "search" on someone's o-
568 // pen mail reader.
569 //
570 // Allow it to be used only to reset the password a single time
571 // to a new value, which won't be in the user's e-mail ar-
572 // chives.
573 //
574 // For backwards compatibility, we'll still recognize it at the
575 // login form to minimize surprises for people who have been
576 // logging in with a temporary password for some time.
577 //
578 // As a side-effect, we can authenticate the user's e-mail ad-
579 // dress if it's not already done, since the temporary password
580 // was sent via e-mail.
581 if( !$u->isEmailConfirmed() ) {
582 $u->confirmEmail();
583 $u->saveSettings();
584 }
585
586 // At this point we just return an appropriate code/ indicating
587 // that the UI should show a password reset form; bot inter-
588 // faces etc will probably just fail cleanly here.
589 $retval = self::RESET_PASS;
590 } else {
591 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
592 }
593 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
594 // If we've enabled it, make it so that a blocked user cannot login
595 $retval = self::USER_BLOCKED;
596 } else {
597 $wgAuth->updateUser( $u );
598 $wgUser = $u;
599 // This should set it for OutputPage and the Skin
600 // which is needed or the personal links will be
601 // wrong.
602 $this->getContext()->setUser( $u );
603
604 // Please reset throttle for successful logins, thanks!
605 if ( $throttleCount ) {
606 self::clearLoginThrottle( $this->mUsername );
607 }
608
609 if ( $isAutoCreated ) {
610 // Must be run after $wgUser is set, for correct new user log
611 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
612 }
613
614 $retval = self::SUCCESS;
615 }
616 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
617 return $retval;
618 }
619
620 /**
621 * Increment the login attempt throttle hit count for the (username,current IP)
622 * tuple unless the throttle was already reached.
623 * @param $username string The user name
624 * @return Bool|Integer The integer hit count or True if it is already at the limit
625 */
626 public static function incLoginThrottle( $username ) {
627 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
628 $username = trim( $username ); // sanity
629
630 $throttleCount = 0;
631 if ( is_array( $wgPasswordAttemptThrottle ) ) {
632 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
633 $count = $wgPasswordAttemptThrottle['count'];
634 $period = $wgPasswordAttemptThrottle['seconds'];
635
636 $throttleCount = $wgMemc->get( $throttleKey );
637 if ( !$throttleCount ) {
638 $wgMemc->add( $throttleKey, 1, $period ); // start counter
639 } elseif ( $throttleCount < $count ) {
640 $wgMemc->incr( $throttleKey );
641 } elseif ( $throttleCount >= $count ) {
642 return true;
643 }
644 }
645
646 return $throttleCount;
647 }
648
649 /**
650 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
651 * @param $username string The user name
652 * @return void
653 */
654 public static function clearLoginThrottle( $username ) {
655 global $wgMemc, $wgRequest;
656 $username = trim( $username ); // sanity
657
658 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
659 $wgMemc->delete( $throttleKey );
660 }
661
662 /**
663 * Attempt to automatically create a user on login. Only succeeds if there
664 * is an external authentication method which allows it.
665 *
666 * @param $user User
667 *
668 * @return integer Status code
669 */
670 function attemptAutoCreate( $user ) {
671 global $wgAuth, $wgAutocreatePolicy;
672
673 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
674 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
675 return self::CREATE_BLOCKED;
676 }
677
678 /**
679 * If the external authentication plugin allows it, automatically cre-
680 * ate a new account for users that are externally defined but have not
681 * yet logged in.
682 */
683 if ( $this->mExtUser ) {
684 # mExtUser is neither null nor false, so use the new ExternalAuth
685 # system.
686 if ( $wgAutocreatePolicy == 'never' ) {
687 return self::NOT_EXISTS;
688 }
689 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
690 return self::WRONG_PLUGIN_PASS;
691 }
692 } else {
693 # Old AuthPlugin.
694 if ( !$wgAuth->autoCreate() ) {
695 return self::NOT_EXISTS;
696 }
697 if ( !$wgAuth->userExists( $user->getName() ) ) {
698 wfDebug( __METHOD__ . ": user does not exist\n" );
699 return self::NOT_EXISTS;
700 }
701 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
702 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
703 return self::WRONG_PLUGIN_PASS;
704 }
705 }
706
707 $abortError = '';
708 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
709 // Hook point to add extra creation throttles and blocks
710 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
711 $this->mAbortLoginErrorMsg = $abortError;
712 return self::ABORTED;
713 }
714
715 wfDebug( __METHOD__ . ": creating account\n" );
716 $this->initUser( $user, true );
717 return self::SUCCESS;
718 }
719
720 function processLogin() {
721 global $wgMemc, $wgLang;
722
723 switch ( $this->authenticateUserData() ) {
724 case self::SUCCESS:
725 # We've verified now, update the real record
726 $user = $this->getUser();
727 if( (bool)$this->mRemember != (bool)$user->getOption( 'rememberpassword' ) ) {
728 $user->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
729 $user->saveSettings();
730 } else {
731 $user->invalidateCache();
732 }
733 $user->setCookies();
734 self::clearLoginToken();
735
736 // Reset the throttle
737 $request = $this->getRequest();
738 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
739 $wgMemc->delete( $key );
740
741 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
742 /* Replace the language object to provide user interface in
743 * correct language immediately on this first page load.
744 */
745 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
746 $userLang = Language::factory( $code );
747 $wgLang = $userLang;
748 $this->getContext()->setLanguage( $userLang );
749 $this->successfulLogin();
750 } else {
751 $this->cookieRedirectCheck( 'login' );
752 }
753 break;
754
755 case self::NEED_TOKEN:
756 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
757 break;
758 case self::WRONG_TOKEN:
759 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
760 break;
761 case self::NO_NAME:
762 case self::ILLEGAL:
763 $this->mainLoginForm( $this->msg( 'noname' )->text() );
764 break;
765 case self::WRONG_PLUGIN_PASS:
766 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
767 break;
768 case self::NOT_EXISTS:
769 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
770 $this->mainLoginForm( $this->msg( 'nosuchuser',
771 wfEscapeWikiText( $this->mUsername ) )->parse() );
772 } else {
773 $this->mainLoginForm( $this->msg( 'nosuchusershort',
774 wfEscapeWikiText( $this->mUsername ) )->text() );
775 }
776 break;
777 case self::WRONG_PASS:
778 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
779 break;
780 case self::EMPTY_PASS:
781 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
782 break;
783 case self::RESET_PASS:
784 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
785 break;
786 case self::CREATE_BLOCKED:
787 $this->userBlockedMessage( $this->getUser()->mBlock );
788 break;
789 case self::THROTTLED:
790 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
791 break;
792 case self::USER_BLOCKED:
793 $this->mainLoginForm( $this->msg( 'login-userblocked',
794 $this->mUsername )->escaped() );
795 break;
796 case self::ABORTED:
797 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg )->text() );
798 break;
799 default:
800 throw new MWException( 'Unhandled case value' );
801 }
802 }
803
804 function resetLoginForm( $error ) {
805 $this->getOutput()->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
806 $reset = new SpecialChangePassword();
807 $reset->setContext( $this->getContext() );
808 $reset->execute( null );
809 }
810
811 /**
812 * @param $u User object
813 * @param $throttle Boolean
814 * @param $emailTitle String: message name of email title
815 * @param $emailText String: message name of email text
816 * @return Status object
817 */
818 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
819 global $wgServer, $wgScript, $wgNewPasswordExpiry;
820
821 if ( $u->getEmail() == '' ) {
822 return Status::newFatal( 'noemail', $u->getName() );
823 }
824 $ip = $this->getRequest()->getIP();
825 if( !$ip ) {
826 return Status::newFatal( 'badipaddress' );
827 }
828
829 $currentUser = $this->getUser();
830 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
831
832 $np = $u->randomPassword();
833 $u->setNewpassword( $np, $throttle );
834 $u->saveSettings();
835 $userLanguage = $u->getOption( 'language' );
836 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgServer . $wgScript . '>',
837 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
838 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
839
840 return $result;
841 }
842
843
844 /**
845 * Run any hooks registered for logins, then HTTP redirect to
846 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
847 * nice message here, but that's really not as useful as just being sent to
848 * wherever you logged in from. It should be clear that the action was
849 * successful, given the lack of error messages plus the appearance of your
850 * name in the upper right.
851 *
852 * @private
853 */
854 function successfulLogin() {
855 # Run any hooks; display injected HTML if any, else redirect
856 $currentUser = $this->getUser();
857 $injected_html = '';
858 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
859
860 if( $injected_html !== '' ) {
861 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
862 } else {
863 $this->executeReturnTo( 'successredirect' );
864 }
865 }
866
867 /**
868 * Run any hooks registered for logins, then display a message welcoming
869 * the user.
870 *
871 * @private
872 */
873 function successfulCreation() {
874 # Run any hooks; display injected HTML
875 $currentUser = $this->getUser();
876 $injected_html = '';
877 $welcome_creation_msg = 'welcomecreation';
878
879 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
880
881 /**
882 * Let any extensions change what message is shown.
883 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
884 * @since 1.18
885 */
886 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
887
888 $this->displaySuccessfulLogin( $welcome_creation_msg, $injected_html );
889 }
890
891 /**
892 * Display a "login successful" page.
893 * @param $msgname string
894 * @param $injected_html string
895 */
896 private function displaySuccessfulLogin( $msgname, $injected_html ) {
897 $out = $this->getOutput();
898 $out->setPageTitle( $this->msg( 'loginsuccesstitle' ) );
899 if( $msgname ){
900 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
901 }
902
903 $out->addHTML( $injected_html );
904
905 $this->executeReturnTo( 'success' );
906 }
907
908 /**
909 * Output a message that informs the user that they cannot create an account because
910 * there is a block on them or their IP which prevents account creation. Note that
911 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
912 * setting on blocks (bug 13611).
913 * @param $block Block the block causing this error
914 */
915 function userBlockedMessage( Block $block ) {
916 # Let's be nice about this, it's likely that this feature will be used
917 # for blocking large numbers of innocent people, e.g. range blocks on
918 # schools. Don't blame it on the user. There's a small chance that it
919 # really is the user's fault, i.e. the username is blocked and they
920 # haven't bothered to log out before trying to create an account to
921 # evade it, but we'll leave that to their guilty conscience to figure
922 # out.
923
924 $out = $this->getOutput();
925 $out->setPageTitle( $this->msg( 'cantcreateaccounttitle' ) );
926
927 $block_reason = $block->mReason;
928 if ( strval( $block_reason ) === '' ) {
929 $block_reason = $this->msg( 'blockednoreason' )->text();
930 }
931
932 $out->addWikiMsg(
933 'cantcreateaccount-text',
934 $block->getTarget(),
935 $block_reason,
936 $block->getByName()
937 );
938
939 $this->executeReturnTo( 'error' );
940 }
941
942 /**
943 * Add a "return to" link or redirect to it.
944 *
945 * @param $type string, one of the following:
946 * - error: display a return to link ignoring $wgRedirectOnLogin
947 * - success: display a return to link using $wgRedirectOnLogin if needed
948 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
949 */
950 private function executeReturnTo( $type ) {
951 global $wgRedirectOnLogin, $wgSecureLogin;
952
953 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
954 $returnTo = $wgRedirectOnLogin;
955 $returnToQuery = array();
956 } else {
957 $returnTo = $this->mReturnTo;
958 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
959 }
960
961 $returnToTitle = Title::newFromText( $returnTo );
962 if ( !$returnToTitle ) {
963 $returnToTitle = Title::newMainPage();
964 }
965
966 if ( $type == 'successredirect' ) {
967 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery );
968 if( $wgSecureLogin && !$this->mStickHTTPS ) {
969 $redirectUrl = preg_replace( '/^https:/', 'http:', $redirectUrl );
970 }
971 $this->getOutput()->redirect( $redirectUrl );
972 } else {
973 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery );
974 }
975 }
976
977 /**
978 * @private
979 */
980 function mainLoginForm( $msg, $msgtype = 'error' ) {
981 global $wgEnableEmail, $wgEnableUserEmail;
982 global $wgHiddenPrefs, $wgLoginLanguageSelector;
983 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
984 global $wgSecureLogin, $wgPasswordResetRoutes;
985
986 $titleObj = $this->getTitle();
987 $user = $this->getUser();
988
989 if ( $this->mType == 'signup' ) {
990 // Block signup here if in readonly. Keeps user from
991 // going through the process (filling out data, etc)
992 // and being informed later.
993 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
994 if ( count( $permErrors ) ) {
995 throw new PermissionsError( 'createaccount', $permErrors );
996 } elseif ( $user->isBlockedFromCreateAccount() ) {
997 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
998 return;
999 } elseif ( wfReadOnly() ) {
1000 throw new ReadOnlyError;
1001 }
1002 }
1003
1004 if ( $this->mUsername == '' ) {
1005 if ( $user->isLoggedIn() ) {
1006 $this->mUsername = $user->getName();
1007 } else {
1008 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
1009 }
1010 }
1011
1012 if ( $this->mType == 'signup' ) {
1013 $template = new UsercreateTemplate();
1014 $q = 'action=submitlogin&type=signup';
1015 $linkq = 'type=login';
1016 $linkmsg = 'gotaccount';
1017 } else {
1018 $template = new UserloginTemplate();
1019 $q = 'action=submitlogin&type=login';
1020 $linkq = 'type=signup';
1021 $linkmsg = 'nologin';
1022 }
1023
1024 if ( $this->mReturnTo !== '' ) {
1025 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1026 if ( $this->mReturnToQuery !== '' ) {
1027 $returnto .= '&returntoquery=' .
1028 wfUrlencode( $this->mReturnToQuery );
1029 }
1030 $q .= $returnto;
1031 $linkq .= $returnto;
1032 }
1033
1034 # Don't show a "create account" link if the user can't
1035 if( $this->showCreateOrLoginLink( $user ) ) {
1036 # Pass any language selection on to the mode switch link
1037 if( $wgLoginLanguageSelector && $this->mLanguage ) {
1038 $linkq .= '&uselang=' . $this->mLanguage;
1039 }
1040 $link = Html::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1041 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1042
1043 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1044 } else {
1045 $template->set( 'link', '' );
1046 }
1047
1048 $resetLink = $this->mType == 'signup'
1049 ? null
1050 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1051
1052 $template->set( 'header', '' );
1053 $template->set( 'name', $this->mUsername );
1054 $template->set( 'password', $this->mPassword );
1055 $template->set( 'retype', $this->mRetype );
1056 $template->set( 'email', $this->mEmail );
1057 $template->set( 'realname', $this->mRealName );
1058 $template->set( 'domain', $this->mDomain );
1059 $template->set( 'reason', $this->mReason );
1060
1061 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1062 $template->set( 'message', $msg );
1063 $template->set( 'messagetype', $msgtype );
1064 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1065 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1066 $template->set( 'useemail', $wgEnableEmail );
1067 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1068 $template->set( 'emailothers', $wgEnableUserEmail );
1069 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1070 $template->set( 'resetlink', $resetLink );
1071 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1072 $template->set( 'usereason', $user->isLoggedIn() );
1073 $template->set( 'remember', $user->getOption( 'rememberpassword' ) || $this->mRemember );
1074 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1075 $template->set( 'stickHTTPS', $this->mStickHTTPS );
1076
1077 if ( $this->mType == 'signup' ) {
1078 if ( !self::getCreateaccountToken() ) {
1079 self::setCreateaccountToken();
1080 }
1081 $template->set( 'token', self::getCreateaccountToken() );
1082 } else {
1083 if ( !self::getLoginToken() ) {
1084 self::setLoginToken();
1085 }
1086 $template->set( 'token', self::getLoginToken() );
1087 }
1088
1089 # Prepare language selection links as needed
1090 if( $wgLoginLanguageSelector ) {
1091 $template->set( 'languages', $this->makeLanguageSelector() );
1092 if( $this->mLanguage ) {
1093 $template->set( 'uselang', $this->mLanguage );
1094 }
1095 }
1096
1097 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1098 // Ditto for signupend
1099 $usingHTTPS = WebRequest::detectProtocol() == 'https';
1100 $loginendHTTPS = $this->msg( 'loginend-https' );
1101 $signupendHTTPS = $this->msg( 'signupend-https' );
1102 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1103 $template->set( 'loginend', $loginendHTTPS->parse() );
1104 } else {
1105 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1106 }
1107 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1108 $template->set( 'signupend', $signupendHTTPS->parse() );
1109 } else {
1110 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1111 }
1112
1113 // Give authentication and captcha plugins a chance to modify the form
1114 $wgAuth->modifyUITemplate( $template, $this->mType );
1115 if ( $this->mType == 'signup' ) {
1116 wfRunHooks( 'UserCreateForm', array( &$template ) );
1117 } else {
1118 wfRunHooks( 'UserLoginForm', array( &$template ) );
1119 }
1120
1121 $out = $this->getOutput();
1122 $out->disallowUserJs(); // just in case...
1123 $out->addTemplate( $template );
1124 }
1125
1126 /**
1127 * @private
1128 *
1129 * @param $user User
1130 *
1131 * @return Boolean
1132 */
1133 function showCreateOrLoginLink( &$user ) {
1134 if( $this->mType == 'signup' ) {
1135 return true;
1136 } elseif( $user->isAllowed( 'createaccount' ) ) {
1137 return true;
1138 } else {
1139 return false;
1140 }
1141 }
1142
1143 /**
1144 * Check if a session cookie is present.
1145 *
1146 * This will not pick up a cookie set during _this_ request, but is meant
1147 * to ensure that the client is returning the cookie which was set on a
1148 * previous pass through the system.
1149 *
1150 * @private
1151 * @return bool
1152 */
1153 function hasSessionCookie() {
1154 global $wgDisableCookieCheck;
1155 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1156 }
1157
1158 /**
1159 * Get the login token from the current session
1160 * @return Mixed
1161 */
1162 public static function getLoginToken() {
1163 global $wgRequest;
1164 return $wgRequest->getSessionData( 'wsLoginToken' );
1165 }
1166
1167 /**
1168 * Randomly generate a new login token and attach it to the current session
1169 */
1170 public static function setLoginToken() {
1171 global $wgRequest;
1172 // Generate a token directly instead of using $user->editToken()
1173 // because the latter reuses $_SESSION['wsEditToken']
1174 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand::generateHex( 32 ) );
1175 }
1176
1177 /**
1178 * Remove any login token attached to the current session
1179 */
1180 public static function clearLoginToken() {
1181 global $wgRequest;
1182 $wgRequest->setSessionData( 'wsLoginToken', null );
1183 }
1184
1185 /**
1186 * Get the createaccount token from the current session
1187 * @return Mixed
1188 */
1189 public static function getCreateaccountToken() {
1190 global $wgRequest;
1191 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1192 }
1193
1194 /**
1195 * Randomly generate a new createaccount token and attach it to the current session
1196 */
1197 public static function setCreateaccountToken() {
1198 global $wgRequest;
1199 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand::generateHex( 32 ) );
1200 }
1201
1202 /**
1203 * Remove any createaccount token attached to the current session
1204 */
1205 public static function clearCreateaccountToken() {
1206 global $wgRequest;
1207 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1208 }
1209
1210 /**
1211 * @private
1212 */
1213 function cookieRedirectCheck( $type ) {
1214 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1215 $query = array( 'wpCookieCheck' => $type );
1216 if ( $this->mReturnTo !== '' ) {
1217 $query['returnto'] = $this->mReturnTo;
1218 $query['returntoquery'] = $this->mReturnToQuery;
1219 }
1220 $check = $titleObj->getFullURL( $query );
1221
1222 $this->getOutput()->redirect( $check );
1223 }
1224
1225 /**
1226 * @private
1227 */
1228 function onCookieRedirectCheck( $type ) {
1229 if ( !$this->hasSessionCookie() ) {
1230 if ( $type == 'new' ) {
1231 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1232 } elseif ( $type == 'login' ) {
1233 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1234 } else {
1235 # shouldn't happen
1236 $this->mainLoginForm( $this->msg( 'error' )->text() );
1237 }
1238 } else {
1239 $this->successfulLogin();
1240 }
1241 }
1242
1243 /**
1244 * @private
1245 */
1246 function throttleHit( $limit ) {
1247 $this->mainLoginForm( $this->msg( 'acct_creation_throttle_hit' )->numParams( $limit )->parse() );
1248 }
1249
1250 /**
1251 * Produce a bar of links which allow the user to select another language
1252 * during login/registration but retain "returnto"
1253 *
1254 * @return string
1255 */
1256 function makeLanguageSelector() {
1257 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1258 if( !$msg->isBlank() ) {
1259 $langs = explode( "\n", $msg->text() );
1260 $links = array();
1261 foreach( $langs as $lang ) {
1262 $lang = trim( $lang, '* ' );
1263 $parts = explode( '|', $lang );
1264 if ( count( $parts ) >= 2 ) {
1265 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1266 }
1267 }
1268 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1269 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1270 } else {
1271 return '';
1272 }
1273 }
1274
1275 /**
1276 * Create a language selector link for a particular language
1277 * Links back to this page preserving type and returnto
1278 *
1279 * @param $text Link text
1280 * @param $lang Language code
1281 * @return string
1282 */
1283 function makeLanguageSelectorLink( $text, $lang ) {
1284 if( $this->getLanguage()->getCode() == $lang ) {
1285 // no link for currently used language
1286 return htmlspecialchars( $text );
1287 }
1288 $query = array( 'uselang' => $lang );
1289 if( $this->mType == 'signup' ) {
1290 $query['type'] = 'signup';
1291 }
1292 if( $this->mReturnTo !== '' ) {
1293 $query['returnto'] = $this->mReturnTo;
1294 $query['returntoquery'] = $this->mReturnToQuery;
1295 }
1296
1297 $attr = array();
1298 $targetLanguage = Language::factory( $lang );
1299 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1300
1301 return Linker::linkKnown(
1302 $this->getTitle(),
1303 htmlspecialchars( $text ),
1304 $attr,
1305 $query
1306 );
1307 }
1308 }