Merge "Add parser tests about building table with {{!}}"
[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 const SUCCESS = 0;
31 const NO_NAME = 1;
32 const ILLEGAL = 2;
33 const WRONG_PLUGIN_PASS = 3;
34 const NOT_EXISTS = 4;
35 const WRONG_PASS = 5;
36 const EMPTY_PASS = 6;
37 const RESET_PASS = 7;
38 const ABORTED = 8;
39 const CREATE_BLOCKED = 9;
40 const THROTTLED = 10;
41 const USER_BLOCKED = 11;
42 const NEED_TOKEN = 12;
43 const WRONG_TOKEN = 13;
44 const USER_MIGRATED = 14;
45
46 /**
47 * Valid error and warning messages
48 *
49 * Special:Userlogin can show an error or warning message on the form when
50 * coming from another page. This is done via the ?error= or ?warning= GET
51 * parameters.
52 *
53 * This array is the list of valid message keys. All other values will be
54 * ignored.
55 *
56 * @since 1.24
57 * @var string[]
58 */
59 public static $validErrorMessages = array(
60 'exception-nologin-text',
61 'watchlistanontext',
62 'changeemail-no-info',
63 'resetpass-no-info',
64 'confirmemail_needlogin',
65 'prefsnologintext2',
66 );
67
68 public $mAbortLoginErrorMsg = null;
69
70 protected $mUsername;
71 protected $mPassword;
72 protected $mRetype;
73 protected $mReturnTo;
74 protected $mCookieCheck;
75 protected $mPosted;
76 protected $mAction;
77 protected $mCreateaccount;
78 protected $mCreateaccountMail;
79 protected $mLoginattempt;
80 protected $mRemember;
81 protected $mEmail;
82 protected $mDomain;
83 protected $mLanguage;
84 protected $mSkipCookieCheck;
85 protected $mReturnToQuery;
86 protected $mToken;
87 protected $mStickHTTPS;
88 protected $mType;
89 protected $mReason;
90 protected $mRealName;
91 protected $mEntryError = '';
92 protected $mEntryErrorType = 'error';
93
94 private $mTempPasswordUsed;
95 private $mLoaded = false;
96 private $mSecureLoginUrl;
97
98 /** @var WebRequest */
99 private $mOverrideRequest = null;
100
101 /** @var WebRequest Effective request; set at the beginning of load */
102 private $mRequest = null;
103
104 /**
105 * @param WebRequest $request
106 */
107 public function __construct( $request = null ) {
108 parent::__construct( 'Userlogin' );
109
110 $this->mOverrideRequest = $request;
111 }
112
113 /**
114 * Loader
115 */
116 function load() {
117 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
118
119 if ( $this->mLoaded ) {
120 return;
121 }
122 $this->mLoaded = true;
123
124 if ( $this->mOverrideRequest === null ) {
125 $request = $this->getRequest();
126 } else {
127 $request = $this->mOverrideRequest;
128 }
129 $this->mRequest = $request;
130
131 $this->mType = $request->getText( 'type' );
132 $this->mUsername = $request->getText( 'wpName' );
133 $this->mPassword = $request->getText( 'wpPassword' );
134 $this->mRetype = $request->getText( 'wpRetype' );
135 $this->mDomain = $request->getText( 'wpDomain' );
136 $this->mReason = $request->getText( 'wpReason' );
137 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
138 $this->mPosted = $request->wasPosted();
139 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
140 && $wgEnableEmail;
141 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail;
142 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
143 $this->mAction = $request->getVal( 'action' );
144 $this->mRemember = $request->getCheck( 'wpRemember' );
145 $this->mFromHTTP = $request->getBool( 'fromhttp', false );
146 $this->mStickHTTPS = ( !$this->mFromHTTP && $request->getProtocol() === 'https' )
147 || $request->getBool( 'wpForceHttps', false );
148 $this->mLanguage = $request->getText( 'uselang' );
149 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
150 $this->mToken = $this->mType == 'signup'
151 ? $request->getVal( 'wpCreateaccountToken' )
152 : $request->getVal( 'wpLoginToken' );
153 $this->mReturnTo = $request->getVal( 'returnto', '' );
154 $this->mReturnToQuery = $request->getVal( 'returntoquery', '' );
155
156 // Show an error or warning passed on from a previous page
157 $entryError = $this->msg( $request->getVal( 'error', '' ) );
158 $entryWarning = $this->msg( $request->getVal( 'warning', '' ) );
159 // bc: provide login link as a parameter for messages where the translation
160 // was not updated
161 $loginreqlink = Linker::linkKnown(
162 $this->getPageTitle(),
163 $this->msg( 'loginreqlink' )->escaped(),
164 array(),
165 array(
166 'returnto' => $this->mReturnTo,
167 'returntoquery' => $this->mReturnToQuery,
168 'uselang' => $this->mLanguage,
169 'fromhttp' => $this->mFromHTTP ? '1' : '0',
170 )
171 );
172
173 // Only show valid error or warning messages.
174 if ( $entryError->exists()
175 && in_array( $entryError->getKey(), self::$validErrorMessages )
176 ) {
177 $this->mEntryErrorType = 'error';
178 $this->mEntryError = $entryError->rawParams( $loginreqlink )->escaped();
179
180 } elseif ( $entryWarning->exists()
181 && in_array( $entryWarning->getKey(), self::$validErrorMessages )
182 ) {
183 $this->mEntryErrorType = 'warning';
184 $this->mEntryError = $entryWarning->rawParams( $loginreqlink )->escaped();
185 }
186
187 if ( $wgEnableEmail ) {
188 $this->mEmail = $request->getText( 'wpEmail' );
189 } else {
190 $this->mEmail = '';
191 }
192 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
193 $this->mRealName = $request->getText( 'wpRealName' );
194 } else {
195 $this->mRealName = '';
196 }
197
198 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
199 $this->mDomain = $wgAuth->getDomain();
200 }
201 $wgAuth->setDomain( $this->mDomain );
202
203 # 1. When switching accounts, it sucks to get automatically logged out
204 # 2. Do not return to PasswordReset after a successful password change
205 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
206 $returnToTitle = Title::newFromText( $this->mReturnTo );
207 if ( is_object( $returnToTitle )
208 && ( $returnToTitle->isSpecial( 'Userlogout' )
209 || $returnToTitle->isSpecial( 'PasswordReset' ) )
210 ) {
211 $this->mReturnTo = '';
212 $this->mReturnToQuery = '';
213 }
214 }
215
216 function getDescription() {
217 if ( $this->mType === 'signup' ) {
218 return $this->msg( 'createaccount' )->text();
219 } else {
220 return $this->msg( 'login' )->text();
221 }
222 }
223
224 /**
225 * @param string|null $subPage
226 */
227 public function execute( $subPage ) {
228 if ( session_id() == '' ) {
229 wfSetupSession();
230 }
231
232 $this->load();
233
234 // Check for [[Special:Userlogin/signup]]. This affects form display and
235 // page title.
236 if ( $subPage == 'signup' ) {
237 $this->mType = 'signup';
238 }
239 $this->setHeaders();
240
241 // In the case where the user is already logged in, do not show the login page.
242 // The use case scenario for this is when a user opens a large number of tabs, is
243 // redirected to the login page on all of them, and then logs in on one, expecting
244 // all the others to work properly.
245 if ( $this->mType !== 'signup' && !$this->mPosted && $this->getUser()->isLoggedIn() ) {
246 $this->successfulLogin();
247 }
248
249 // If logging in and not on HTTPS, either redirect to it or offer a link.
250 global $wgSecureLogin;
251 if ( $this->mRequest->getProtocol() !== 'https' ) {
252 $title = $this->getFullTitle();
253 $query = array(
254 'returnto' => $this->mReturnTo !== '' ? $this->mReturnTo : null,
255 'returntoquery' => $this->mReturnToQuery !== '' ?
256 $this->mReturnToQuery : null,
257 'title' => null,
258 ( $this->mEntryErrorType === 'error' ? 'error' : 'warning' ) => $this->mEntryError,
259 ) + $this->mRequest->getQueryValues();
260 $url = $title->getFullURL( $query, false, PROTO_HTTPS );
261 if ( $wgSecureLogin
262 && wfCanIPUseHTTPS( $this->getRequest()->getIP() )
263 && !$this->mFromHTTP ) // Avoid infinite redirect
264 {
265 $url = wfAppendQuery( $url, 'fromhttp=1' );
266 $this->getOutput()->redirect( $url );
267 // Since we only do this redir to change proto, always vary
268 $this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
269
270 return;
271 } else {
272 // A wiki without HTTPS login support should set $wgServer to
273 // http://somehost, in which case the secure URL generated
274 // above won't actually start with https://
275 if ( substr( $url, 0, 8 ) === 'https://' ) {
276 $this->mSecureLoginUrl = $url;
277 }
278 }
279 }
280
281 if ( !is_null( $this->mCookieCheck ) ) {
282 $this->onCookieRedirectCheck( $this->mCookieCheck );
283
284 return;
285 } elseif ( $this->mPosted ) {
286 if ( $this->mCreateaccount ) {
287 $this->addNewAccount();
288
289 return;
290 } elseif ( $this->mCreateaccountMail ) {
291 $this->addNewAccountMailPassword();
292
293 return;
294 } elseif ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
295 $this->processLogin();
296
297 return;
298 }
299 }
300 $this->mainLoginForm( $this->mEntryError, $this->mEntryErrorType );
301 }
302
303 /**
304 * @private
305 */
306 function addNewAccountMailPassword() {
307 if ( $this->mEmail == '' ) {
308 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
309
310 return;
311 }
312
313 $status = $this->addNewAccountInternal();
314 if ( !$status->isGood() ) {
315 $error = $status->getMessage();
316 $this->mainLoginForm( $error->toString() );
317
318 return;
319 }
320
321 $u = $status->getValue();
322
323 // Wipe the initial password and mail a temporary one
324 $u->setPassword( null );
325 $u->saveSettings();
326 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
327
328 wfRunHooks( 'AddNewAccount', array( $u, true ) );
329 $u->addNewUserLogEntry( 'byemail', $this->mReason );
330
331 $out = $this->getOutput();
332 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
333
334 if ( !$result->isGood() ) {
335 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
336 } else {
337 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
338 $this->executeReturnTo( 'success' );
339 }
340 }
341
342 /**
343 * @private
344 * @return bool
345 */
346 function addNewAccount() {
347 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
348
349 # Create the account and abort if there's a problem doing so
350 $status = $this->addNewAccountInternal();
351 if ( !$status->isGood() ) {
352 $error = $status->getMessage();
353 $this->mainLoginForm( $error->toString() );
354
355 return false;
356 }
357
358 $u = $status->getValue();
359
360 # Only save preferences if the user is not creating an account for someone else.
361 if ( $this->getUser()->isAnon() ) {
362 # If we showed up language selection links, and one was in use, be
363 # smart (and sensible) and save that language as the user's preference
364 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
365 $u->setOption( 'language', $this->mLanguage );
366 } else {
367
368 # Otherwise the user's language preference defaults to $wgContLang,
369 # but it may be better to set it to their preferred $wgContLang variant,
370 # based on browser preferences or URL parameters.
371 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
372 }
373 if ( $wgContLang->hasVariants() ) {
374 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
375 }
376 }
377
378 $out = $this->getOutput();
379
380 # Send out an email authentication message if needed
381 if ( $wgEmailAuthentication && Sanitizer::validateEmail( $u->getEmail() ) ) {
382 $status = $u->sendConfirmationMail();
383 if ( $status->isGood() ) {
384 $out->addWikiMsg( 'confirmemail_oncreate' );
385 } else {
386 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
387 }
388 }
389
390 # Save settings (including confirmation token)
391 $u->saveSettings();
392
393 # If not logged in, assume the new account as the current one and set
394 # session cookies then show a "welcome" message or a "need cookies"
395 # message as needed
396 if ( $this->getUser()->isAnon() ) {
397 $u->setCookies();
398 $wgUser = $u;
399 // This should set it for OutputPage and the Skin
400 // which is needed or the personal links will be
401 // wrong.
402 $this->getContext()->setUser( $u );
403 wfRunHooks( 'AddNewAccount', array( $u, false ) );
404 $u->addNewUserLogEntry( 'create' );
405 if ( $this->hasSessionCookie() ) {
406 $this->successfulCreation();
407 } else {
408 $this->cookieRedirectCheck( 'new' );
409 }
410 } else {
411 # Confirm that the account was created
412 $out->setPageTitle( $this->msg( 'accountcreated' ) );
413 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
414 $out->addReturnTo( $this->getPageTitle() );
415 wfRunHooks( 'AddNewAccount', array( $u, false ) );
416 $u->addNewUserLogEntry( 'create2', $this->mReason );
417 }
418
419 return true;
420 }
421
422 /**
423 * Make a new user account using the loaded data.
424 * @private
425 * @throws PermissionsError|ReadOnlyError
426 * @return Status
427 */
428 public function addNewAccountInternal() {
429 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
430 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
431
432 // If the user passes an invalid domain, something is fishy
433 if ( !$wgAuth->validDomain( $this->mDomain ) ) {
434 return Status::newFatal( 'wrongpassword' );
435 }
436
437 // If we are not allowing users to login locally, we should be checking
438 // to see if the user is actually able to authenticate to the authenti-
439 // cation server before they create an account (otherwise, they can
440 // create a local account and login as any domain user). We only need
441 // to check this for domains that aren't local.
442 if ( 'local' != $this->mDomain && $this->mDomain != '' ) {
443 if (
444 !$wgAuth->canCreateAccounts() &&
445 (
446 !$wgAuth->userExists( $this->mUsername ) ||
447 !$wgAuth->authenticate( $this->mUsername, $this->mPassword )
448 )
449 ) {
450 return Status::newFatal( 'wrongpassword' );
451 }
452 }
453
454 if ( wfReadOnly() ) {
455 throw new ReadOnlyError;
456 }
457
458 # Request forgery checks.
459 if ( !self::getCreateaccountToken() ) {
460 self::setCreateaccountToken();
461
462 return Status::newFatal( 'nocookiesfornew' );
463 }
464
465 # The user didn't pass a createaccount token
466 if ( !$this->mToken ) {
467 return Status::newFatal( 'sessionfailure' );
468 }
469
470 # Validate the createaccount token
471 if ( $this->mToken !== self::getCreateaccountToken() ) {
472 return Status::newFatal( 'sessionfailure' );
473 }
474
475 # Check permissions
476 $currentUser = $this->getUser();
477 $creationBlock = $currentUser->isBlockedFromCreateAccount();
478 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
479 throw new PermissionsError( 'createaccount' );
480 } elseif ( $creationBlock instanceof Block ) {
481 // Throws an ErrorPageError.
482 $this->userBlockedMessage( $creationBlock );
483
484 // This should never be reached.
485 return false;
486 }
487
488 # Include checks that will include GlobalBlocking (Bug 38333)
489 $permErrors = $this->getPageTitle()->getUserPermissionsErrors(
490 'createaccount',
491 $currentUser,
492 true
493 );
494
495 if ( count( $permErrors ) ) {
496 throw new PermissionsError( 'createaccount', $permErrors );
497 }
498
499 $ip = $this->getRequest()->getIP();
500 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
501 return Status::newFatal( 'sorbs_create_account_reason' );
502 }
503
504 // Normalize the name so that silly things don't cause "invalid username"
505 // errors. User::newFromName does some rather strict checking, rejecting
506 // e.g. leading/trailing/multiple spaces. But first we need to reject
507 // usernames that would be treated as titles with a fragment part.
508 if ( strpos( $this->mUsername, '#' ) !== false ) {
509 return Status::newFatal( 'noname' );
510 }
511 $title = Title::makeTitleSafe( NS_USER, $this->mUsername );
512 if ( !is_object( $title ) ) {
513 return Status::newFatal( 'noname' );
514 }
515
516 # Now create a dummy user ($u) and check if it is valid
517 $u = User::newFromName( $title->getText(), 'creatable' );
518 if ( !is_object( $u ) ) {
519 return Status::newFatal( 'noname' );
520 } elseif ( 0 != $u->idForName() ) {
521 return Status::newFatal( 'userexists' );
522 }
523
524 if ( $this->mCreateaccountMail ) {
525 # do not force a password for account creation by email
526 # set invalid password, it will be replaced later by a random generated password
527 $this->mPassword = null;
528 } else {
529 if ( $this->mPassword !== $this->mRetype ) {
530 return Status::newFatal( 'badretype' );
531 }
532
533 # check for minimal password length
534 $valid = $u->getPasswordValidity( $this->mPassword );
535 if ( $valid !== true ) {
536 if ( !is_array( $valid ) ) {
537 $valid = array( $valid, $wgMinimalPasswordLength );
538 }
539
540 return call_user_func_array( 'Status::newFatal', $valid );
541 }
542 }
543
544 # if you need a confirmed email address to edit, then obviously you
545 # need an email address.
546 if ( $wgEmailConfirmToEdit && strval( $this->mEmail ) === '' ) {
547 return Status::newFatal( 'noemailtitle' );
548 }
549
550 if ( strval( $this->mEmail ) !== '' && !Sanitizer::validateEmail( $this->mEmail ) ) {
551 return Status::newFatal( 'invalidemailaddress' );
552 }
553
554 # Set some additional data so the AbortNewAccount hook can be used for
555 # more than just username validation
556 $u->setEmail( $this->mEmail );
557 $u->setRealName( $this->mRealName );
558
559 $abortError = '';
560 $abortStatus = null;
561 if ( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError, &$abortStatus ) ) ) {
562 // Hook point to add extra creation throttles and blocks
563 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
564 if ( $abortStatus === null ) {
565 // Report back the old string as a raw message status.
566 // This will report the error back as 'createaccount-hook-aborted'
567 // with the given string as the message.
568 // To return a different error code, return a Status object.
569 $abortError = new Message( 'createaccount-hook-aborted', array( $abortError ) );
570 $abortError->text();
571
572 return Status::newFatal( $abortError );
573 } else {
574 // For MediaWiki 1.23+ and updated hooks, return the Status object
575 // returned from the hook.
576 return $abortStatus;
577 }
578 }
579
580 // Hook point to check for exempt from account creation throttle
581 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
582 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook " .
583 "allowed account creation w/o throttle\n" );
584 } else {
585 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
586 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
587 $value = $wgMemc->get( $key );
588 if ( !$value ) {
589 $wgMemc->set( $key, 0, 86400 );
590 }
591 if ( $value >= $wgAccountCreationThrottle ) {
592 return Status::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
593 }
594 $wgMemc->incr( $key );
595 }
596 }
597
598 if ( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
599 return Status::newFatal( 'externaldberror' );
600 }
601
602 self::clearCreateaccountToken();
603
604 return $this->initUser( $u, false );
605 }
606
607 /**
608 * Actually add a user to the database.
609 * Give it a User object that has been initialised with a name.
610 *
611 * @param User $u
612 * @param bool $autocreate True if this is an autocreation via auth plugin
613 * @return Status Status object, with the User object in the value member on success
614 * @private
615 */
616 function initUser( $u, $autocreate ) {
617 global $wgAuth;
618
619 $status = $u->addToDatabase();
620 if ( !$status->isOK() ) {
621 return $status;
622 }
623
624 if ( $wgAuth->allowPasswordChange() ) {
625 $u->setPassword( $this->mPassword );
626 }
627
628 $u->setEmail( $this->mEmail );
629 $u->setRealName( $this->mRealName );
630 $u->setToken();
631
632 $wgAuth->initUser( $u, $autocreate );
633
634 $u->saveSettings();
635
636 // Update user count
637 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
638
639 // Watch user's userpage and talk page
640 $u->addWatch( $u->getUserPage(), WatchedItem::IGNORE_USER_RIGHTS );
641
642 return Status::newGood( $u );
643 }
644
645 /**
646 * Internally authenticate the login request.
647 *
648 * This may create a local account as a side effect if the
649 * authentication plugin allows transparent local account
650 * creation.
651 * @return int
652 */
653 public function authenticateUserData() {
654 global $wgUser, $wgAuth;
655
656 $this->load();
657
658 if ( $this->mUsername == '' ) {
659 return self::NO_NAME;
660 }
661
662 // We require a login token to prevent login CSRF
663 // Handle part of this before incrementing the throttle so
664 // token-less login attempts don't count towards the throttle
665 // but wrong-token attempts do.
666
667 // If the user doesn't have a login token yet, set one.
668 if ( !self::getLoginToken() ) {
669 self::setLoginToken();
670
671 return self::NEED_TOKEN;
672 }
673 // If the user didn't pass a login token, tell them we need one
674 if ( !$this->mToken ) {
675 return self::NEED_TOKEN;
676 }
677
678 $throttleCount = self::incLoginThrottle( $this->mUsername );
679 if ( $throttleCount === true ) {
680 return self::THROTTLED;
681 }
682
683 // Validate the login token
684 if ( $this->mToken !== self::getLoginToken() ) {
685 return self::WRONG_TOKEN;
686 }
687
688 // Load the current user now, and check to see if we're logging in as
689 // the same name. This is necessary because loading the current user
690 // (say by calling getName()) calls the UserLoadFromSession hook, which
691 // potentially creates the user in the database. Until we load $wgUser,
692 // checking for user existence using User::newFromName($name)->getId() below
693 // will effectively be using stale data.
694 if ( $this->getUser()->getName() === $this->mUsername ) {
695 wfDebug( __METHOD__ . ": already logged in as {$this->mUsername}\n" );
696
697 return self::SUCCESS;
698 }
699
700 $u = User::newFromName( $this->mUsername );
701
702 // Give extensions a way to indicate the username has been updated,
703 // rather than telling the user the account doesn't exist.
704 if ( !wfRunHooks( 'LoginUserMigrated', array( $u, &$msg ) ) ) {
705 $this->mAbortLoginErrorMsg = $msg;
706 return self::USER_MIGRATED;
707 }
708
709 if ( !( $u instanceof User ) || !User::isUsableName( $u->getName() ) ) {
710 return self::ILLEGAL;
711 }
712
713 $isAutoCreated = false;
714 if ( $u->getID() == 0 ) {
715 $status = $this->attemptAutoCreate( $u );
716 if ( $status !== self::SUCCESS ) {
717 return $status;
718 } else {
719 $isAutoCreated = true;
720 }
721 } else {
722 $u->load();
723 }
724
725 // Give general extensions, such as a captcha, a chance to abort logins
726 $abort = self::ABORTED;
727 $msg = null;
728 if ( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort, &$msg ) ) ) {
729 $this->mAbortLoginErrorMsg = $msg;
730
731 return $abort;
732 }
733
734 global $wgBlockDisablesLogin;
735 if ( !$u->checkPassword( $this->mPassword ) ) {
736 if ( $u->checkTemporaryPassword( $this->mPassword ) ) {
737 // The e-mailed temporary password should not be used for actu-
738 // al logins; that's a very sloppy habit, and insecure if an
739 // attacker has a few seconds to click "search" on someone's o-
740 // pen mail reader.
741 //
742 // Allow it to be used only to reset the password a single time
743 // to a new value, which won't be in the user's e-mail ar-
744 // chives.
745 //
746 // For backwards compatibility, we'll still recognize it at the
747 // login form to minimize surprises for people who have been
748 // logging in with a temporary password for some time.
749 //
750 // As a side-effect, we can authenticate the user's e-mail ad-
751 // dress if it's not already done, since the temporary password
752 // was sent via e-mail.
753 if ( !$u->isEmailConfirmed() ) {
754 $u->confirmEmail();
755 $u->saveSettings();
756 }
757
758 // At this point we just return an appropriate code/ indicating
759 // that the UI should show a password reset form; bot inter-
760 // faces etc will probably just fail cleanly here.
761 $this->mAbortLoginErrorMsg = 'resetpass-temp-emailed';
762 $this->mTempPasswordUsed = true;
763 $retval = self::RESET_PASS;
764 } else {
765 $retval = ( $this->mPassword == '' ) ? self::EMPTY_PASS : self::WRONG_PASS;
766 }
767 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
768 // If we've enabled it, make it so that a blocked user cannot login
769 $retval = self::USER_BLOCKED;
770 } elseif ( $u->getPasswordExpired() == 'hard' ) {
771 // Force reset now, without logging in
772 $retval = self::RESET_PASS;
773 $this->mAbortLoginErrorMsg = 'resetpass-expired';
774 } else {
775 $wgAuth->updateUser( $u );
776 $wgUser = $u;
777 // This should set it for OutputPage and the Skin
778 // which is needed or the personal links will be
779 // wrong.
780 $this->getContext()->setUser( $u );
781
782 // Please reset throttle for successful logins, thanks!
783 if ( $throttleCount ) {
784 self::clearLoginThrottle( $this->mUsername );
785 }
786
787 if ( $isAutoCreated ) {
788 // Must be run after $wgUser is set, for correct new user log
789 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
790 }
791
792 $retval = self::SUCCESS;
793 }
794 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
795
796 return $retval;
797 }
798
799 /**
800 * Increment the login attempt throttle hit count for the (username,current IP)
801 * tuple unless the throttle was already reached.
802 * @param string $username The user name
803 * @return bool|int The integer hit count or True if it is already at the limit
804 */
805 public static function incLoginThrottle( $username ) {
806 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
807 $username = trim( $username ); // sanity
808
809 $throttleCount = 0;
810 if ( is_array( $wgPasswordAttemptThrottle ) ) {
811 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
812 $count = $wgPasswordAttemptThrottle['count'];
813 $period = $wgPasswordAttemptThrottle['seconds'];
814
815 $throttleCount = $wgMemc->get( $throttleKey );
816 if ( !$throttleCount ) {
817 $wgMemc->add( $throttleKey, 1, $period ); // start counter
818 } elseif ( $throttleCount < $count ) {
819 $wgMemc->incr( $throttleKey );
820 } elseif ( $throttleCount >= $count ) {
821 return true;
822 }
823 }
824
825 return $throttleCount;
826 }
827
828 /**
829 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
830 * @param string $username The user name
831 * @return void
832 */
833 public static function clearLoginThrottle( $username ) {
834 global $wgMemc, $wgRequest;
835 $username = trim( $username ); // sanity
836
837 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
838 $wgMemc->delete( $throttleKey );
839 }
840
841 /**
842 * Attempt to automatically create a user on login. Only succeeds if there
843 * is an external authentication method which allows it.
844 *
845 * @param User $user
846 *
847 * @return int Status code
848 */
849 function attemptAutoCreate( $user ) {
850 global $wgAuth;
851
852 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
853 wfDebug( __METHOD__ . ": user is blocked from account creation\n" );
854
855 return self::CREATE_BLOCKED;
856 }
857
858 if ( !$wgAuth->autoCreate() ) {
859 return self::NOT_EXISTS;
860 }
861
862 if ( !$wgAuth->userExists( $user->getName() ) ) {
863 wfDebug( __METHOD__ . ": user does not exist\n" );
864
865 return self::NOT_EXISTS;
866 }
867
868 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
869 wfDebug( __METHOD__ . ": \$wgAuth->authenticate() returned false, aborting\n" );
870
871 return self::WRONG_PLUGIN_PASS;
872 }
873
874 $abortError = '';
875 if ( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
876 // Hook point to add extra creation throttles and blocks
877 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
878 $this->mAbortLoginErrorMsg = $abortError;
879
880 return self::ABORTED;
881 }
882
883 wfDebug( __METHOD__ . ": creating account\n" );
884 $status = $this->initUser( $user, true );
885
886 if ( !$status->isOK() ) {
887 $errors = $status->getErrorsByType( 'error' );
888 $this->mAbortLoginErrorMsg = $errors[0]['message'];
889
890 return self::ABORTED;
891 }
892
893 return self::SUCCESS;
894 }
895
896 function processLogin() {
897 global $wgMemc, $wgLang, $wgSecureLogin, $wgPasswordAttemptThrottle,
898 $wgInvalidPasswordReset;
899
900 switch ( $this->authenticateUserData() ) {
901 case self::SUCCESS:
902 # We've verified now, update the real record
903 $user = $this->getUser();
904 $user->invalidateCache();
905
906 if ( $user->requiresHTTPS() ) {
907 $this->mStickHTTPS = true;
908 }
909
910 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
911 $user->setCookies( $this->mRequest, false, $this->mRemember );
912 } else {
913 $user->setCookies( $this->mRequest, null, $this->mRemember );
914 }
915 self::clearLoginToken();
916
917 // Reset the throttle
918 $request = $this->getRequest();
919 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername ) );
920 $wgMemc->delete( $key );
921
922 if ( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
923 /* Replace the language object to provide user interface in
924 * correct language immediately on this first page load.
925 */
926 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
927 $userLang = Language::factory( $code );
928 $wgLang = $userLang;
929 $this->getContext()->setLanguage( $userLang );
930 // Reset SessionID on Successful login (bug 40995)
931 $this->renewSessionId();
932 if ( $this->getUser()->getPasswordExpired() == 'soft' ) {
933 $this->resetLoginForm( $this->msg( 'resetpass-expired-soft' ) );
934 } elseif ( $wgInvalidPasswordReset
935 && !$user->isValidPassword( $this->mPassword )
936 ) {
937 $status = $user->checkPasswordValidity( $this->mPassword );
938 $this->resetLoginForm(
939 $status->getMessage( 'resetpass-validity-soft' )
940 );
941 } else {
942 $this->successfulLogin();
943 }
944 } else {
945 $this->cookieRedirectCheck( 'login' );
946 }
947 break;
948
949 case self::NEED_TOKEN:
950 $error = $this->mAbortLoginErrorMsg ?: 'nocookiesforlogin';
951 $this->mainLoginForm( $this->msg( $error )->parse() );
952 break;
953 case self::WRONG_TOKEN:
954 $error = $this->mAbortLoginErrorMsg ?: 'sessionfailure';
955 $this->mainLoginForm( $this->msg( $error )->text() );
956 break;
957 case self::NO_NAME:
958 case self::ILLEGAL:
959 $error = $this->mAbortLoginErrorMsg ?: 'noname';
960 $this->mainLoginForm( $this->msg( $error )->text() );
961 break;
962 case self::WRONG_PLUGIN_PASS:
963 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
964 $this->mainLoginForm( $this->msg( $error )->text() );
965 break;
966 case self::NOT_EXISTS:
967 if ( $this->getUser()->isAllowed( 'createaccount' ) ) {
968 $error = $this->mAbortLoginErrorMsg ?: 'nosuchuser';
969 $this->mainLoginForm( $this->msg( $error,
970 wfEscapeWikiText( $this->mUsername ) )->parse() );
971 } else {
972 $error = $this->mAbortLoginErrorMsg ?: 'nosuchusershort';
973 $this->mainLoginForm( $this->msg( $error,
974 wfEscapeWikiText( $this->mUsername ) )->text() );
975 }
976 break;
977 case self::WRONG_PASS:
978 $error = $this->mAbortLoginErrorMsg ?: 'wrongpassword';
979 $this->mainLoginForm( $this->msg( $error )->text() );
980 break;
981 case self::EMPTY_PASS:
982 $error = $this->mAbortLoginErrorMsg ?: 'wrongpasswordempty';
983 $this->mainLoginForm( $this->msg( $error )->text() );
984 break;
985 case self::RESET_PASS:
986 $error = $this->mAbortLoginErrorMsg ?: 'resetpass_announce';
987 $this->resetLoginForm( $this->msg( $error ) );
988 break;
989 case self::CREATE_BLOCKED:
990 $this->userBlockedMessage( $this->getUser()->isBlockedFromCreateAccount() );
991 break;
992 case self::THROTTLED:
993 $error = $this->mAbortLoginErrorMsg ?: 'login-throttled';
994 $this->mainLoginForm( $this->msg( $error )
995 ->params( $this->getLanguage()->formatDuration( $wgPasswordAttemptThrottle['seconds'] ) )
996 ->text()
997 );
998 break;
999 case self::USER_BLOCKED:
1000 $error = $this->mAbortLoginErrorMsg ?: 'login-userblocked';
1001 $this->mainLoginForm( $this->msg( $error, $this->mUsername )->escaped() );
1002 break;
1003 case self::ABORTED:
1004 $error = $this->mAbortLoginErrorMsg ?: 'login-abort-generic';
1005 $this->mainLoginForm( $this->msg( $error,
1006 wfEscapeWikiText( $this->mUsername ) )->text() );
1007 break;
1008 case self::USER_MIGRATED:
1009 $error = $this->mAbortLoginErrorMsg ?: 'login-migrated-generic';
1010 $params = array();
1011 if ( is_array( $error ) ) {
1012 $error = array_shift( $this->mAbortLoginErrorMsg );
1013 $params = $this->mAbortLoginErrorMsg;
1014 }
1015 $this->mainLoginForm( $this->msg( $error, $params )->text() );
1016 break;
1017 default:
1018 throw new MWException( 'Unhandled case value' );
1019 }
1020 }
1021
1022 /**
1023 * Show the Special:ChangePassword form, with custom message
1024 * @param Message $msg
1025 */
1026 protected function resetLoginForm( Message $msg ) {
1027 // Allow hooks to explain this password reset in more detail
1028 wfRunHooks( 'LoginPasswordResetMessage', array( &$msg, $this->mUsername ) );
1029 $reset = new SpecialChangePassword();
1030 $derivative = new DerivativeContext( $this->getContext() );
1031 $derivative->setTitle( $reset->getPageTitle() );
1032 $reset->setContext( $derivative );
1033 if ( !$this->mTempPasswordUsed ) {
1034 $reset->setOldPasswordMessage( 'oldpassword' );
1035 }
1036 $reset->setChangeMessage( $msg );
1037 $reset->execute( null );
1038 }
1039
1040 /**
1041 * @param User $u
1042 * @param bool $throttle
1043 * @param string $emailTitle Message name of email title
1044 * @param string $emailText Message name of email text
1045 * @return Status
1046 */
1047 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle',
1048 $emailText = 'passwordremindertext'
1049 ) {
1050 global $wgNewPasswordExpiry;
1051
1052 if ( $u->getEmail() == '' ) {
1053 return Status::newFatal( 'noemail', $u->getName() );
1054 }
1055 $ip = $this->getRequest()->getIP();
1056 if ( !$ip ) {
1057 return Status::newFatal( 'badipaddress' );
1058 }
1059
1060 $currentUser = $this->getUser();
1061 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
1062
1063 $np = $u->randomPassword();
1064 $u->setNewpassword( $np, $throttle );
1065 $u->saveSettings();
1066 $userLanguage = $u->getOption( 'language' );
1067
1068 $mainPage = Title::newMainPage();
1069 $mainPageUrl = $mainPage->getCanonicalURL();
1070
1071 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $mainPageUrl . '>',
1072 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
1073 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
1074
1075 return $result;
1076 }
1077
1078 /**
1079 * Run any hooks registered for logins, then HTTP redirect to
1080 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
1081 * nice message here, but that's really not as useful as just being sent to
1082 * wherever you logged in from. It should be clear that the action was
1083 * successful, given the lack of error messages plus the appearance of your
1084 * name in the upper right.
1085 *
1086 * @private
1087 */
1088 function successfulLogin() {
1089 # Run any hooks; display injected HTML if any, else redirect
1090 $currentUser = $this->getUser();
1091 $injected_html = '';
1092 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1093
1094 if ( $injected_html !== '' ) {
1095 $this->displaySuccessfulAction( 'success', $this->msg( 'loginsuccesstitle' ),
1096 'loginsuccess', $injected_html );
1097 } else {
1098 $this->executeReturnTo( 'successredirect' );
1099 }
1100 }
1101
1102 /**
1103 * Run any hooks registered for logins, then display a message welcoming
1104 * the user.
1105 *
1106 * @private
1107 */
1108 function successfulCreation() {
1109 # Run any hooks; display injected HTML
1110 $currentUser = $this->getUser();
1111 $injected_html = '';
1112 $welcome_creation_msg = 'welcomecreation-msg';
1113
1114 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
1115
1116 /**
1117 * Let any extensions change what message is shown.
1118 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
1119 * @since 1.18
1120 */
1121 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
1122
1123 $this->displaySuccessfulAction(
1124 'signup',
1125 $this->msg( 'welcomeuser', $this->getUser()->getName() ),
1126 $welcome_creation_msg, $injected_html
1127 );
1128 }
1129
1130 /**
1131 * Display a "successful action" page.
1132 *
1133 * @param string $type Condition of return to; see `executeReturnTo`
1134 * @param string|Message $title Page's title
1135 * @param string $msgname
1136 * @param string $injected_html
1137 */
1138 private function displaySuccessfulAction( $type, $title, $msgname, $injected_html ) {
1139 $out = $this->getOutput();
1140 $out->setPageTitle( $title );
1141 if ( $msgname ) {
1142 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
1143 }
1144
1145 $out->addHTML( $injected_html );
1146
1147 $this->executeReturnTo( $type );
1148 }
1149
1150 /**
1151 * Output a message that informs the user that they cannot create an account because
1152 * there is a block on them or their IP which prevents account creation. Note that
1153 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
1154 * setting on blocks (bug 13611).
1155 * @param Block $block The block causing this error
1156 * @throws ErrorPageError
1157 */
1158 function userBlockedMessage( Block $block ) {
1159 # Let's be nice about this, it's likely that this feature will be used
1160 # for blocking large numbers of innocent people, e.g. range blocks on
1161 # schools. Don't blame it on the user. There's a small chance that it
1162 # really is the user's fault, i.e. the username is blocked and they
1163 # haven't bothered to log out before trying to create an account to
1164 # evade it, but we'll leave that to their guilty conscience to figure
1165 # out.
1166 $errorParams = array(
1167 $block->getTarget(),
1168 $block->mReason ? $block->mReason : $this->msg( 'blockednoreason' )->text(),
1169 $block->getByName()
1170 );
1171
1172 if ( $block->getType() === Block::TYPE_RANGE ) {
1173 $errorMessage = 'cantcreateaccount-range-text';
1174 $errorParams[] = $this->getRequest()->getIP();
1175 } else {
1176 $errorMessage = 'cantcreateaccount-text';
1177 }
1178
1179 throw new ErrorPageError(
1180 'cantcreateaccounttitle',
1181 $errorMessage,
1182 $errorParams
1183 );
1184 }
1185
1186 /**
1187 * Add a "return to" link or redirect to it.
1188 * Extensions can use this to reuse the "return to" logic after
1189 * inject steps (such as redirection) into the login process.
1190 *
1191 * @param string $type One of the following:
1192 * - error: display a return to link ignoring $wgRedirectOnLogin
1193 * - signup: display a return to link using $wgRedirectOnLogin if needed
1194 * - success: display a return to link using $wgRedirectOnLogin if needed
1195 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1196 * @param string $returnTo
1197 * @param array|string $returnToQuery
1198 * @param bool $stickHTTPs Keep redirect link on HTTPs
1199 * @since 1.22
1200 */
1201 public function showReturnToPage(
1202 $type, $returnTo = '', $returnToQuery = '', $stickHTTPs = false
1203 ) {
1204 $this->mReturnTo = $returnTo;
1205 $this->mReturnToQuery = $returnToQuery;
1206 $this->mStickHTTPS = $stickHTTPs;
1207 $this->executeReturnTo( $type );
1208 }
1209
1210 /**
1211 * Add a "return to" link or redirect to it.
1212 *
1213 * @param string $type One of the following:
1214 * - error: display a return to link ignoring $wgRedirectOnLogin
1215 * - signup: display a return to link using $wgRedirectOnLogin if needed
1216 * - success: display a return to link using $wgRedirectOnLogin if needed
1217 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
1218 */
1219 private function executeReturnTo( $type ) {
1220 global $wgRedirectOnLogin, $wgSecureLogin;
1221
1222 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
1223 $returnTo = $wgRedirectOnLogin;
1224 $returnToQuery = array();
1225 } else {
1226 $returnTo = $this->mReturnTo;
1227 $returnToQuery = wfCgiToArray( $this->mReturnToQuery );
1228 }
1229
1230 // Allow modification of redirect behavior
1231 wfRunHooks( 'PostLoginRedirect', array( &$returnTo, &$returnToQuery, &$type ) );
1232
1233 $returnToTitle = Title::newFromText( $returnTo );
1234 if ( !$returnToTitle ) {
1235 $returnToTitle = Title::newMainPage();
1236 }
1237
1238 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1239 $options = array( 'http' );
1240 $proto = PROTO_HTTP;
1241 } elseif ( $wgSecureLogin ) {
1242 $options = array( 'https' );
1243 $proto = PROTO_HTTPS;
1244 } else {
1245 $options = array();
1246 $proto = PROTO_RELATIVE;
1247 }
1248
1249 if ( $type == 'successredirect' ) {
1250 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
1251 $this->getOutput()->redirect( $redirectUrl );
1252 } else {
1253 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
1254 }
1255 }
1256
1257 /**
1258 * @param string $msg
1259 * @param string $msgtype
1260 * @private
1261 */
1262 function mainLoginForm( $msg, $msgtype = 'error' ) {
1263 global $wgEnableEmail, $wgEnableUserEmail;
1264 global $wgHiddenPrefs, $wgLoginLanguageSelector;
1265 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
1266 global $wgSecureLogin, $wgPasswordResetRoutes;
1267
1268 $titleObj = $this->getPageTitle();
1269 $user = $this->getUser();
1270 $out = $this->getOutput();
1271
1272 if ( $this->mType == 'signup' ) {
1273 // Block signup here if in readonly. Keeps user from
1274 // going through the process (filling out data, etc)
1275 // and being informed later.
1276 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
1277 if ( count( $permErrors ) ) {
1278 throw new PermissionsError( 'createaccount', $permErrors );
1279 } elseif ( $user->isBlockedFromCreateAccount() ) {
1280 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1281
1282 return;
1283 } elseif ( wfReadOnly() ) {
1284 throw new ReadOnlyError;
1285 }
1286 }
1287
1288 // Pre-fill username (if not creating an account, bug 44775).
1289 if ( $this->mUsername == '' && $this->mType != 'signup' ) {
1290 if ( $user->isLoggedIn() ) {
1291 $this->mUsername = $user->getName();
1292 } else {
1293 $this->mUsername = $this->getRequest()->getCookie( 'UserName' );
1294 }
1295 }
1296
1297 // Generic styles and scripts for both login and signup form
1298 $out->addModuleStyles( array(
1299 'mediawiki.ui',
1300 'mediawiki.ui.button',
1301 'mediawiki.ui.checkbox',
1302 'mediawiki.ui.input',
1303 'mediawiki.special.userlogin.common.styles'
1304 ) );
1305 $out->addModules( array(
1306 'mediawiki.special.userlogin.common.js'
1307 ) );
1308
1309 if ( $this->mType == 'signup' ) {
1310 // XXX hack pending RL or JS parse() support for complex content messages
1311 // https://bugzilla.wikimedia.org/show_bug.cgi?id=25349
1312 $out->addJsConfigVars( 'wgCreateacctImgcaptchaHelp',
1313 $this->msg( 'createacct-imgcaptcha-help' )->parse() );
1314
1315 // Additional styles and scripts for signup form
1316 $out->addModules( array(
1317 'mediawiki.special.userlogin.signup.js'
1318 ) );
1319 $out->addModuleStyles( array(
1320 'mediawiki.special.userlogin.signup.styles'
1321 ) );
1322
1323 $template = new UsercreateTemplate();
1324
1325 // Must match number of benefits defined in messages
1326 $template->set( 'benefitCount', 3 );
1327
1328 $q = 'action=submitlogin&type=signup';
1329 $linkq = 'type=login';
1330 } else {
1331 // Additional styles for login form
1332 $out->addModuleStyles( array(
1333 'mediawiki.special.userlogin.login.styles'
1334 ) );
1335
1336 $template = new UserloginTemplate();
1337
1338 $q = 'action=submitlogin&type=login';
1339 $linkq = 'type=signup';
1340 }
1341
1342 if ( $this->mReturnTo !== '' ) {
1343 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
1344 if ( $this->mReturnToQuery !== '' ) {
1345 $returnto .= '&returntoquery=' .
1346 wfUrlencode( $this->mReturnToQuery );
1347 }
1348 $q .= $returnto;
1349 $linkq .= $returnto;
1350 }
1351
1352 # Don't show a "create account" link if the user can't.
1353 if ( $this->showCreateOrLoginLink( $user ) ) {
1354 # Pass any language selection on to the mode switch link
1355 if ( $wgLoginLanguageSelector && $this->mLanguage ) {
1356 $linkq .= '&uselang=' . $this->mLanguage;
1357 }
1358 // Supply URL, login template creates the button.
1359 $template->set( 'createOrLoginHref', $titleObj->getLocalURL( $linkq ) );
1360 } else {
1361 $template->set( 'link', '' );
1362 }
1363
1364 $resetLink = $this->mType == 'signup'
1365 ? null
1366 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1367
1368 $template->set( 'header', '' );
1369 $template->set( 'skin', $this->getSkin() );
1370 $template->set( 'name', $this->mUsername );
1371 $template->set( 'password', $this->mPassword );
1372 $template->set( 'retype', $this->mRetype );
1373 $template->set( 'createemailset', $this->mCreateaccountMail );
1374 $template->set( 'email', $this->mEmail );
1375 $template->set( 'realname', $this->mRealName );
1376 $template->set( 'domain', $this->mDomain );
1377 $template->set( 'reason', $this->mReason );
1378
1379 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1380 $template->set( 'message', $msg );
1381 $template->set( 'messagetype', $msgtype );
1382 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1383 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1384 $template->set( 'useemail', $wgEnableEmail );
1385 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1386 $template->set( 'emailothers', $wgEnableUserEmail );
1387 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1388 $template->set( 'resetlink', $resetLink );
1389 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1390 $template->set( 'usereason', $user->isLoggedIn() );
1391 $template->set( 'remember', $this->mRemember );
1392 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1393 $template->set( 'stickhttps', (int)$this->mStickHTTPS );
1394 $template->set( 'loggedin', $user->isLoggedIn() );
1395
1396 if ( $this->mType == 'signup' ) {
1397 if ( !self::getCreateaccountToken() ) {
1398 self::setCreateaccountToken();
1399 }
1400 $template->set( 'token', self::getCreateaccountToken() );
1401 } else {
1402 if ( !self::getLoginToken() ) {
1403 self::setLoginToken();
1404 }
1405 $template->set( 'token', self::getLoginToken() );
1406 }
1407
1408 # Prepare language selection links as needed
1409 if ( $wgLoginLanguageSelector ) {
1410 $template->set( 'languages', $this->makeLanguageSelector() );
1411 if ( $this->mLanguage ) {
1412 $template->set( 'uselang', $this->mLanguage );
1413 }
1414 }
1415
1416 $template->set( 'secureLoginUrl', $this->mSecureLoginUrl );
1417 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1418 // Ditto for signupend. New forms use neither.
1419 $usingHTTPS = $this->mRequest->getProtocol() == 'https';
1420 $loginendHTTPS = $this->msg( 'loginend-https' );
1421 $signupendHTTPS = $this->msg( 'signupend-https' );
1422 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1423 $template->set( 'loginend', $loginendHTTPS->parse() );
1424 } else {
1425 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1426 }
1427 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1428 $template->set( 'signupend', $signupendHTTPS->parse() );
1429 } else {
1430 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1431 }
1432
1433 // Give authentication and captcha plugins a chance to modify the form
1434 $wgAuth->modifyUITemplate( $template, $this->mType );
1435 if ( $this->mType == 'signup' ) {
1436 wfRunHooks( 'UserCreateForm', array( &$template ) );
1437 } else {
1438 wfRunHooks( 'UserLoginForm', array( &$template ) );
1439 }
1440
1441 $out->disallowUserJs(); // just in case...
1442 $out->addTemplate( $template );
1443 }
1444
1445 /**
1446 * Whether the login/create account form should display a link to the
1447 * other form (in addition to whatever the skin provides).
1448 *
1449 * @param User $user
1450 * @return bool
1451 */
1452 private function showCreateOrLoginLink( &$user ) {
1453 if ( $this->mType == 'signup' ) {
1454 return true;
1455 } elseif ( $user->isAllowed( 'createaccount' ) ) {
1456 return true;
1457 } else {
1458 return false;
1459 }
1460 }
1461
1462 /**
1463 * Check if a session cookie is present.
1464 *
1465 * This will not pick up a cookie set during _this_ request, but is meant
1466 * to ensure that the client is returning the cookie which was set on a
1467 * previous pass through the system.
1468 *
1469 * @private
1470 * @return bool
1471 */
1472 function hasSessionCookie() {
1473 global $wgDisableCookieCheck;
1474
1475 return $wgDisableCookieCheck ? true : $this->getRequest()->checkSessionCookie();
1476 }
1477
1478 /**
1479 * Get the login token from the current session
1480 * @return mixed
1481 */
1482 public static function getLoginToken() {
1483 global $wgRequest;
1484
1485 return $wgRequest->getSessionData( 'wsLoginToken' );
1486 }
1487
1488 /**
1489 * Randomly generate a new login token and attach it to the current session
1490 */
1491 public static function setLoginToken() {
1492 global $wgRequest;
1493 // Generate a token directly instead of using $user->getEditToken()
1494 // because the latter reuses $_SESSION['wsEditToken']
1495 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand::generateHex( 32 ) );
1496 }
1497
1498 /**
1499 * Remove any login token attached to the current session
1500 */
1501 public static function clearLoginToken() {
1502 global $wgRequest;
1503 $wgRequest->setSessionData( 'wsLoginToken', null );
1504 }
1505
1506 /**
1507 * Get the createaccount token from the current session
1508 * @return mixed
1509 */
1510 public static function getCreateaccountToken() {
1511 global $wgRequest;
1512
1513 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1514 }
1515
1516 /**
1517 * Randomly generate a new createaccount token and attach it to the current session
1518 */
1519 public static function setCreateaccountToken() {
1520 global $wgRequest;
1521 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand::generateHex( 32 ) );
1522 }
1523
1524 /**
1525 * Remove any createaccount token attached to the current session
1526 */
1527 public static function clearCreateaccountToken() {
1528 global $wgRequest;
1529 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1530 }
1531
1532 /**
1533 * Renew the user's session id, using strong entropy
1534 */
1535 private function renewSessionId() {
1536 global $wgSecureLogin, $wgCookieSecure;
1537 if ( $wgSecureLogin && !$this->mStickHTTPS ) {
1538 $wgCookieSecure = false;
1539 }
1540
1541 wfResetSessionID();
1542 }
1543
1544 /**
1545 * @param string $type
1546 * @private
1547 */
1548 function cookieRedirectCheck( $type ) {
1549 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
1550 $query = array( 'wpCookieCheck' => $type );
1551 if ( $this->mReturnTo !== '' ) {
1552 $query['returnto'] = $this->mReturnTo;
1553 $query['returntoquery'] = $this->mReturnToQuery;
1554 }
1555 $check = $titleObj->getFullURL( $query );
1556
1557 $this->getOutput()->redirect( $check );
1558 }
1559
1560 /**
1561 * @param string $type
1562 * @private
1563 */
1564 function onCookieRedirectCheck( $type ) {
1565 if ( !$this->hasSessionCookie() ) {
1566 if ( $type == 'new' ) {
1567 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1568 } elseif ( $type == 'login' ) {
1569 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1570 } else {
1571 # shouldn't happen
1572 $this->mainLoginForm( $this->msg( 'error' )->text() );
1573 }
1574 } else {
1575 $this->successfulLogin();
1576 }
1577 }
1578
1579 /**
1580 * Produce a bar of links which allow the user to select another language
1581 * during login/registration but retain "returnto"
1582 *
1583 * @return string
1584 */
1585 function makeLanguageSelector() {
1586 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1587 if ( !$msg->isBlank() ) {
1588 $langs = explode( "\n", $msg->text() );
1589 $links = array();
1590 foreach ( $langs as $lang ) {
1591 $lang = trim( $lang, '* ' );
1592 $parts = explode( '|', $lang );
1593 if ( count( $parts ) >= 2 ) {
1594 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1595 }
1596 }
1597
1598 return count( $links ) > 0 ? $this->msg( 'loginlanguagelabel' )->rawParams(
1599 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1600 } else {
1601 return '';
1602 }
1603 }
1604
1605 /**
1606 * Create a language selector link for a particular language
1607 * Links back to this page preserving type and returnto
1608 *
1609 * @param string $text Link text
1610 * @param string $lang Language code
1611 * @return string
1612 */
1613 function makeLanguageSelectorLink( $text, $lang ) {
1614 if ( $this->getLanguage()->getCode() == $lang ) {
1615 // no link for currently used language
1616 return htmlspecialchars( $text );
1617 }
1618 $query = array( 'uselang' => $lang );
1619 if ( $this->mType == 'signup' ) {
1620 $query['type'] = 'signup';
1621 }
1622 if ( $this->mReturnTo !== '' ) {
1623 $query['returnto'] = $this->mReturnTo;
1624 $query['returntoquery'] = $this->mReturnToQuery;
1625 }
1626
1627 $attr = array();
1628 $targetLanguage = Language::factory( $lang );
1629 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1630
1631 return Linker::linkKnown(
1632 $this->getPageTitle(),
1633 htmlspecialchars( $text ),
1634 $attr,
1635 $query
1636 );
1637 }
1638
1639 protected function getGroupName() {
1640 return 'login';
1641 }
1642 }