d16c6c6522e275fa30e172cb921ebcae6738160f
[lhc/web/wiklou.git] / includes / specials / SpecialUserlogin.php
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 */
6
7 /**
8 * constructor
9 */
10 function wfSpecialUserlogin( $par = '' ) {
11 global $wgRequest;
12 if( session_id() == '' ) {
13 wfSetupSession();
14 }
15
16 $form = new LoginForm( $wgRequest, $par );
17 $form->execute();
18 }
19
20 /**
21 * implements Special:Login
22 * @ingroup SpecialPage
23 */
24 class LoginForm {
25
26 const SUCCESS = 0;
27 const NO_NAME = 1;
28 const ILLEGAL = 2;
29 const WRONG_PLUGIN_PASS = 3;
30 const NOT_EXISTS = 4;
31 const WRONG_PASS = 5;
32 const EMPTY_PASS = 6;
33 const RESET_PASS = 7;
34 const ABORTED = 8;
35 const CREATE_BLOCKED = 9;
36 const THROTTLED = 10;
37
38 var $mName, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
39 var $mAction, $mCreateaccount, $mCreateaccountMail, $mMailmypassword;
40 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
41 var $mSkipCookieCheck, $mReturnToQuery;
42
43 private $mExtUser = null;
44
45 /**
46 * Constructor
47 * @param WebRequest $request A WebRequest object passed by reference
48 */
49 function LoginForm( &$request, $par = '' ) {
50 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail, $wgRedirectOnLogin;
51
52 $this->mType = ( $par == 'signup' ) ? $par : $request->getText( 'type' ); # Check for [[Special:Userlogin/signup]]
53 $this->mName = $request->getText( 'wpName' );
54 $this->mPassword = $request->getText( 'wpPassword' );
55 $this->mRetype = $request->getText( 'wpRetype' );
56 $this->mDomain = $request->getText( 'wpDomain' );
57 $this->mReturnTo = $request->getVal( 'returnto' );
58 $this->mReturnToQuery = $request->getVal( 'returntoquery' );
59 $this->mCookieCheck = $request->getVal( 'wpCookieCheck' );
60 $this->mPosted = $request->wasPosted();
61 $this->mCreateaccount = $request->getCheck( 'wpCreateaccount' );
62 $this->mCreateaccountMail = $request->getCheck( 'wpCreateaccountMail' )
63 && $wgEnableEmail;
64 $this->mMailmypassword = $request->getCheck( 'wpMailmypassword' )
65 && $wgEnableEmail;
66 $this->mLoginattempt = $request->getCheck( 'wpLoginattempt' );
67 $this->mAction = $request->getVal( 'action' );
68 $this->mRemember = $request->getCheck( 'wpRemember' );
69 $this->mLanguage = $request->getText( 'uselang' );
70 $this->mSkipCookieCheck = $request->getCheck( 'wpSkipCookieCheck' );
71
72 if ( $wgRedirectOnLogin ) {
73 $this->mReturnTo = $wgRedirectOnLogin;
74 $this->mReturnToQuery = '';
75 }
76
77 if( $wgEnableEmail ) {
78 $this->mEmail = $request->getText( 'wpEmail' );
79 } else {
80 $this->mEmail = '';
81 }
82 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
83 $this->mRealName = $request->getText( 'wpRealName' );
84 } else {
85 $this->mRealName = '';
86 }
87
88 if( !$wgAuth->validDomain( $this->mDomain ) ) {
89 $this->mDomain = 'invaliddomain';
90 }
91 $wgAuth->setDomain( $this->mDomain );
92
93 # When switching accounts, it sucks to get automatically logged out
94 $returnToTitle = Title::newFromText( $this->mReturnTo );
95 if( is_object( $returnToTitle ) && $returnToTitle->isSpecial( 'Userlogout' ) ) {
96 $this->mReturnTo = '';
97 $this->mReturnToQuery = '';
98 }
99 }
100
101 function execute() {
102 if ( !is_null( $this->mCookieCheck ) ) {
103 $this->onCookieRedirectCheck( $this->mCookieCheck );
104 return;
105 } else if( $this->mPosted ) {
106 if( $this->mCreateaccount ) {
107 return $this->addNewAccount();
108 } else if ( $this->mCreateaccountMail ) {
109 return $this->addNewAccountMailPassword();
110 } else if ( $this->mMailmypassword ) {
111 return $this->mailPassword();
112 } else if ( ( 'submitlogin' == $this->mAction ) || $this->mLoginattempt ) {
113 return $this->processLogin();
114 }
115 }
116 $this->mainLoginForm( '' );
117 }
118
119 /**
120 * @private
121 */
122 function addNewAccountMailPassword() {
123 global $wgOut;
124
125 if ('' == $this->mEmail) {
126 $this->mainLoginForm( wfMsg( 'noemail', htmlspecialchars( $this->mName ) ) );
127 return;
128 }
129
130 $u = $this->addNewaccountInternal();
131
132 if ($u == null) {
133 return;
134 }
135
136 // Wipe the initial password and mail a temporary one
137 $u->setPassword( null );
138 $u->saveSettings();
139 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
140
141 wfRunHooks( 'AddNewAccount', array( $u, true ) );
142 $u->addNewUserLogEntry();
143
144 $wgOut->setPageTitle( wfMsg( 'accmailtitle' ) );
145 $wgOut->setRobotPolicy( 'noindex,nofollow' );
146 $wgOut->setArticleRelated( false );
147
148 if( WikiError::isError( $result ) ) {
149 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
150 } else {
151 $wgOut->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
152 $wgOut->returnToMain( false );
153 }
154 $u = 0;
155 }
156
157
158 /**
159 * @private
160 */
161 function addNewAccount() {
162 global $wgUser, $wgEmailAuthentication;
163
164 # Create the account and abort if there's a problem doing so
165 $u = $this->addNewAccountInternal();
166 if( $u == null )
167 return;
168
169 # If we showed up language selection links, and one was in use, be
170 # smart (and sensible) and save that language as the user's preference
171 global $wgLoginLanguageSelector;
172 if( $wgLoginLanguageSelector && $this->mLanguage )
173 $u->setOption( 'language', $this->mLanguage );
174
175 # Send out an email authentication message if needed
176 if( $wgEmailAuthentication && User::isValidEmailAddr( $u->getEmail() ) ) {
177 global $wgOut;
178 $error = $u->sendConfirmationMail();
179 if( WikiError::isError( $error ) ) {
180 $wgOut->addWikiMsg( 'confirmemail_sendfailed', $error->getMessage() );
181 } else {
182 $wgOut->addWikiMsg( 'confirmemail_oncreate' );
183 }
184 }
185
186 # Save settings (including confirmation token)
187 $u->saveSettings();
188
189 # If not logged in, assume the new account as the current one and set
190 # session cookies then show a "welcome" message or a "need cookies"
191 # message as needed
192 if( $wgUser->isAnon() ) {
193 $wgUser = $u;
194 $wgUser->setCookies();
195 wfRunHooks( 'AddNewAccount', array( $wgUser, false ) );
196 $wgUser->addNewUserLogEntry();
197 if( $this->hasSessionCookie() ) {
198 return $this->successfulCreation();
199 } else {
200 return $this->cookieRedirectCheck( 'new' );
201 }
202 } else {
203 # Confirm that the account was created
204 global $wgOut;
205 $self = SpecialPage::getTitleFor( 'Userlogin' );
206 $wgOut->setPageTitle( wfMsgHtml( 'accountcreated' ) );
207 $wgOut->setArticleRelated( false );
208 $wgOut->setRobotPolicy( 'noindex,nofollow' );
209 $wgOut->addHTML( wfMsgWikiHtml( 'accountcreatedtext', $u->getName() ) );
210 $wgOut->returnToMain( false, $self );
211 wfRunHooks( 'AddNewAccount', array( $u, false ) );
212 $u->addNewUserLogEntry();
213 return true;
214 }
215 }
216
217 /**
218 * @private
219 */
220 function addNewAccountInternal() {
221 global $wgUser, $wgOut;
222 global $wgEnableSorbs, $wgProxyWhitelist;
223 global $wgMemc, $wgAccountCreationThrottle;
224 global $wgAuth, $wgMinimalPasswordLength;
225 global $wgEmailConfirmToEdit;
226
227 // If the user passes an invalid domain, something is fishy
228 if( !$wgAuth->validDomain( $this->mDomain ) ) {
229 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
230 return false;
231 }
232
233 // If we are not allowing users to login locally, we should be checking
234 // to see if the user is actually able to authenticate to the authenti-
235 // cation server before they create an account (otherwise, they can
236 // create a local account and login as any domain user). We only need
237 // to check this for domains that aren't local.
238 if( 'local' != $this->mDomain && '' != $this->mDomain ) {
239 if( !$wgAuth->canCreateAccounts() && ( !$wgAuth->userExists( $this->mName ) || !$wgAuth->authenticate( $this->mName, $this->mPassword ) ) ) {
240 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
241 return false;
242 }
243 }
244
245 if ( wfReadOnly() ) {
246 $wgOut->readOnlyPage();
247 return false;
248 }
249
250 # Check permissions
251 if ( !$wgUser->isAllowed( 'createaccount' ) ) {
252 $this->userNotPrivilegedMessage();
253 return false;
254 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
255 $this->userBlockedMessage();
256 return false;
257 }
258
259 $ip = wfGetIP();
260 if ( $wgEnableSorbs && !in_array( $ip, $wgProxyWhitelist ) &&
261 $wgUser->inSorbsBlacklist( $ip ) )
262 {
263 $this->mainLoginForm( wfMsg( 'sorbs_create_account_reason' ) . ' (' . htmlspecialchars( $ip ) . ')' );
264 return;
265 }
266
267 # Now create a dummy user ($u) and check if it is valid
268 $name = trim( $this->mName );
269 $u = User::newFromName( $name, 'creatable' );
270 if ( WikiError::isError( $u ) ) {
271 $this->mainLoginForm( wfMsg( $u->getMessage() ) );
272 return false;
273 }
274
275 if ( !is_object( $u ) ) {
276 $this->mainLoginForm( wfMsg( 'noname' ) );
277 return false;
278 }
279
280 if ( 0 != $u->idForName() ) {
281 $this->mainLoginForm( wfMsg( 'userexists' ) );
282 return false;
283 }
284
285 if ( 0 != strcmp( $this->mPassword, $this->mRetype ) ) {
286 $this->mainLoginForm( wfMsg( 'badretype' ) );
287 return false;
288 }
289
290 # check for minimal password length
291 $valid = $u->getPasswordValidity( $this->mPassword );
292 if ( $valid !== true ) {
293 if ( !$this->mCreateaccountMail ) {
294 $this->mainLoginForm( wfMsgExt( $valid, array( 'parsemag' ), $wgMinimalPasswordLength ) );
295 return false;
296 } else {
297 # do not force a password for account creation by email
298 # set invalid password, it will be replaced later by a random generated password
299 $this->mPassword = null;
300 }
301 }
302
303 # if you need a confirmed email address to edit, then obviously you
304 # need an email address.
305 if ( $wgEmailConfirmToEdit && empty( $this->mEmail ) ) {
306 $this->mainLoginForm( wfMsg( 'noemailtitle' ) );
307 return false;
308 }
309
310 if( !empty( $this->mEmail ) && !User::isValidEmailAddr( $this->mEmail ) ) {
311 $this->mainLoginForm( wfMsg( 'invalidemailaddress' ) );
312 return false;
313 }
314
315 # Set some additional data so the AbortNewAccount hook can be used for
316 # more than just username validation
317 $u->setEmail( $this->mEmail );
318 $u->setRealName( $this->mRealName );
319
320 $abortError = '';
321 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
322 // Hook point to add extra creation throttles and blocks
323 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
324 $this->mainLoginForm( $abortError );
325 return false;
326 }
327
328 if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) {
329 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
330 $value = $wgMemc->get( $key );
331 if ( !$value ) {
332 $wgMemc->set( $key, 0, 86400 );
333 }
334 if ( $value >= $wgAccountCreationThrottle ) {
335 $this->throttleHit( $wgAccountCreationThrottle );
336 return false;
337 }
338 $wgMemc->incr( $key );
339 }
340
341 if( !$wgAuth->addUser( $u, $this->mPassword, $this->mEmail, $this->mRealName ) ) {
342 $this->mainLoginForm( wfMsg( 'externaldberror' ) );
343 return false;
344 }
345
346 return $this->initUser( $u, false );
347 }
348
349 /**
350 * Actually add a user to the database.
351 * Give it a User object that has been initialised with a name.
352 *
353 * @param $u User object.
354 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
355 * @return User object.
356 * @private
357 */
358 function initUser( $u, $autocreate ) {
359 global $wgAuth;
360
361 $u->addToDatabase();
362
363 if ( $wgAuth->allowPasswordChange() ) {
364 $u->setPassword( $this->mPassword );
365 }
366
367 $u->setEmail( $this->mEmail );
368 $u->setRealName( $this->mRealName );
369 $u->setToken();
370
371 $wgAuth->initUser( $u, $autocreate );
372
373 if ( $this->mExtUser ) {
374 $this->mExtUser->linkToLocal( $u->getId() );
375 $email = $this->mExtUser->getPref( 'emailaddress' );
376 if ( $email && !$this->mEmail ) {
377 $u->setEmail( $email );
378 }
379 }
380
381 $u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
382 $u->saveSettings();
383
384 # Update user count
385 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
386 $ssUpdate->doUpdate();
387
388 return $u;
389 }
390
391 /**
392 * Internally authenticate the login request.
393 *
394 * This may create a local account as a side effect if the
395 * authentication plugin allows transparent local account
396 * creation.
397 *
398 * @public
399 */
400 function authenticateUserData() {
401 global $wgUser, $wgAuth;
402 if ( '' == $this->mName ) {
403 return self::NO_NAME;
404 }
405
406 global $wgPasswordAttemptThrottle;
407
408 $throttleCount = 0;
409 if ( is_array( $wgPasswordAttemptThrottle ) ) {
410 $throttleKey = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
411 $count = $wgPasswordAttemptThrottle['count'];
412 $period = $wgPasswordAttemptThrottle['seconds'];
413
414 global $wgMemc;
415 $throttleCount = $wgMemc->get( $throttleKey );
416 if ( !$throttleCount ) {
417 $wgMemc->add( $throttleKey, 1, $period ); // start counter
418 } else if ( $throttleCount < $count ) {
419 $wgMemc->incr($throttleKey);
420 } else if ( $throttleCount >= $count ) {
421 return self::THROTTLED;
422 }
423 }
424
425 // Load $wgUser now, and check to see if we're logging in as the same
426 // name. This is necessary because loading $wgUser (say by calling
427 // getName()) calls the UserLoadFromSession hook, which potentially
428 // creates the user in the database. Until we load $wgUser, checking
429 // for user existence using User::newFromName($name)->getId() below
430 // will effectively be using stale data.
431 if ( $wgUser->getName() === $this->mName ) {
432 wfDebug( __METHOD__.": already logged in as {$this->mName}\n" );
433 return self::SUCCESS;
434 }
435
436 $this->mExtUser = ExternalUser::newFromName( $this->mName );
437
438 # TODO: Allow some magic here for invalid external names, e.g., let the
439 # user choose a different wiki name.
440 $u = User::newFromName( $this->mName );
441 if( is_null( $u ) || !User::isUsableName( $u->getName() ) ) {
442 return self::ILLEGAL;
443 }
444
445 $isAutoCreated = false;
446 if ( 0 == $u->getID() ) {
447 $status = $this->attemptAutoCreate( $u );
448 if ( $status !== self::SUCCESS ) {
449 return $status;
450 } else {
451 $isAutoCreated = true;
452 }
453 } else {
454 $u->load();
455 }
456
457 // Give general extensions, such as a captcha, a chance to abort logins
458 $abort = self::ABORTED;
459 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword, &$abort ) ) ) {
460 return $abort;
461 }
462
463 if (!$u->checkPassword( $this->mPassword )) {
464 if( $u->checkTemporaryPassword( $this->mPassword ) ) {
465 // The e-mailed temporary password should not be used for actu-
466 // al logins; that's a very sloppy habit, and insecure if an
467 // attacker has a few seconds to click "search" on someone's o-
468 // pen mail reader.
469 //
470 // Allow it to be used only to reset the password a single time
471 // to a new value, which won't be in the user's e-mail ar-
472 // chives.
473 //
474 // For backwards compatibility, we'll still recognize it at the
475 // login form to minimize surprises for people who have been
476 // logging in with a temporary password for some time.
477 //
478 // As a side-effect, we can authenticate the user's e-mail ad-
479 // dress if it's not already done, since the temporary password
480 // was sent via e-mail.
481 if( !$u->isEmailConfirmed() ) {
482 $u->confirmEmail();
483 $u->saveSettings();
484 }
485
486 // At this point we just return an appropriate code/ indicating
487 // that the UI should show a password reset form; bot inter-
488 // faces etc will probably just fail cleanly here.
489 $retval = self::RESET_PASS;
490 } else {
491 $retval = '' == $this->mPassword ? self::EMPTY_PASS : self::WRONG_PASS;
492 }
493 } else {
494 $wgAuth->updateUser( $u );
495 $wgUser = $u;
496
497 // Please reset throttle for successful logins, thanks!
498 if($throttleCount) {
499 $wgMemc->delete($throttleKey);
500 }
501
502 if ( $isAutoCreated ) {
503 // Must be run after $wgUser is set, for correct new user log
504 wfRunHooks( 'AuthPluginAutoCreate', array( $wgUser ) );
505 }
506
507 $retval = self::SUCCESS;
508 }
509 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword, $retval ) );
510 return $retval;
511 }
512
513 /**
514 * Attempt to automatically create a user on login. Only succeeds if there
515 * is an external authentication method which allows it.
516 * @return integer Status code
517 */
518 function attemptAutoCreate( $user ) {
519 global $wgAuth, $wgUser, $wgAutocreatePolicy;
520
521 if ( $wgUser->isBlockedFromCreateAccount() ) {
522 wfDebug( __METHOD__.": user is blocked from account creation\n" );
523 return self::CREATE_BLOCKED;
524 }
525
526 /**
527 * If the external authentication plugin allows it, automatically cre-
528 * ate a new account for users that are externally defined but have not
529 * yet logged in.
530 */
531 if ( $this->mExtUser ) {
532 # mExtUser is neither null nor false, so use the new ExternalAuth
533 # system.
534 if ( $wgAutocreatePolicy == 'never' ) {
535 return self::NOT_EXISTS;
536 }
537 if ( !$this->mExtUser->authenticate( $this->mPassword ) ) {
538 return self::WRONG_PLUGIN_PASS;
539 }
540 } else {
541 # Old AuthPlugin.
542 if ( !$wgAuth->autoCreate() ) {
543 return self::NOT_EXISTS;
544 }
545 if ( !$wgAuth->userExists( $user->getName() ) ) {
546 wfDebug( __METHOD__.": user does not exist\n" );
547 return self::NOT_EXISTS;
548 }
549 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword ) ) {
550 wfDebug( __METHOD__.": \$wgAuth->authenticate() returned false, aborting\n" );
551 return self::WRONG_PLUGIN_PASS;
552 }
553 }
554
555 wfDebug( __METHOD__.": creating account\n" );
556 $user = $this->initUser( $user, true );
557 return self::SUCCESS;
558 }
559
560 function processLogin() {
561 global $wgUser, $wgAuth;
562
563 switch ( $this->authenticateUserData() ) {
564 case self::SUCCESS:
565 # We've verified now, update the real record
566 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
567 $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
568 $wgUser->saveSettings();
569 } else {
570 $wgUser->invalidateCache();
571 }
572 $wgUser->setCookies();
573
574 // Reset the throttle
575 $key = wfMemcKey( 'password-throttle', wfGetIP(), md5( $this->mName ) );
576 global $wgMemc;
577 $wgMemc->delete( $key );
578
579 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
580 /* Replace the language object to provide user interface in
581 * correct language immediately on this first page load.
582 */
583 global $wgLang, $wgRequest;
584 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
585 $wgLang = Language::factory( $code );
586 return $this->successfulLogin();
587 } else {
588 return $this->cookieRedirectCheck( 'login' );
589 }
590 break;
591
592 case self::NO_NAME:
593 case self::ILLEGAL:
594 $this->mainLoginForm( wfMsg( 'noname' ) );
595 break;
596 case self::WRONG_PLUGIN_PASS:
597 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
598 break;
599 case self::NOT_EXISTS:
600 if( $wgUser->isAllowed( 'createaccount' ) ){
601 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
602 } else {
603 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName ) ) );
604 }
605 break;
606 case self::WRONG_PASS:
607 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
608 break;
609 case self::EMPTY_PASS:
610 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
611 break;
612 case self::RESET_PASS:
613 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
614 break;
615 case self::CREATE_BLOCKED:
616 $this->userBlockedMessage();
617 break;
618 case self::THROTTLED:
619 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
620 break;
621 default:
622 throw new MWException( "Unhandled case value" );
623 }
624 }
625
626 function resetLoginForm( $error ) {
627 global $wgOut;
628 $wgOut->addHTML( Xml::element('p', array( 'class' => 'error' ), $error ) );
629 $reset = new SpecialResetpass();
630 $reset->execute( null );
631 }
632
633 /**
634 * @private
635 */
636 function mailPassword() {
637 global $wgUser, $wgOut, $wgAuth;
638
639 if ( wfReadOnly() ) {
640 $wgOut->readOnlyPage();
641 return false;
642 }
643
644 if( !$wgAuth->allowPasswordChange() ) {
645 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
646 return;
647 }
648
649 # Check against blocked IPs
650 # fixme -- should we not?
651 if( $wgUser->isBlocked() ) {
652 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
653 return;
654 }
655
656 // Check for hooks
657 $error = null;
658 if ( ! wfRunHooks( 'UserLoginMailPassword', array( $this->mName, &$error ) ) ) {
659 $this->mainLoginForm( $error );
660 return;
661 }
662
663 # Check against the rate limiter
664 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
665 $wgOut->rateLimited();
666 return;
667 }
668
669 if ( '' == $this->mName ) {
670 $this->mainLoginForm( wfMsg( 'noname' ) );
671 return;
672 }
673 $u = User::newFromName( $this->mName );
674 if( is_null( $u ) ) {
675 $this->mainLoginForm( wfMsg( 'noname' ) );
676 return;
677 }
678 if ( 0 == $u->getID() ) {
679 $this->mainLoginForm( wfMsgWikiHtml( 'nosuchuser', htmlspecialchars( $u->getName() ) ) );
680 return;
681 }
682
683 # Check against password throttle
684 if ( $u->isPasswordReminderThrottled() ) {
685 global $wgPasswordReminderResendTime;
686 # Round the time in hours to 3 d.p., in case someone is specifying
687 # minutes or seconds.
688 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
689 round( $wgPasswordReminderResendTime, 3 ) ) );
690 return;
691 }
692
693 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
694 if( WikiError::isError( $result ) ) {
695 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
696 } else {
697 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
698 }
699 }
700
701
702 /**
703 * @param object user
704 * @param bool throttle
705 * @param string message name of email title
706 * @param string message name of email text
707 * @return mixed true on success, WikiError on failure
708 * @private
709 */
710 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
711 global $wgServer, $wgScript, $wgUser, $wgNewPasswordExpiry;
712
713 if ( '' == $u->getEmail() ) {
714 return new WikiError( wfMsg( 'noemail', $u->getName() ) );
715 }
716 $ip = wfGetIP();
717 if( !$ip ) {
718 return new WikiError( wfMsg( 'badipaddress' ) );
719 }
720
721 wfRunHooks( 'User::mailPasswordInternal', array(&$wgUser, &$ip, &$u) );
722
723 $np = $u->randomPassword();
724 $u->setNewpassword( $np, $throttle );
725 $u->saveSettings();
726
727 $m = wfMsgExt( $emailText, array( 'parsemag' ), $ip, $u->getName(), $np,
728 $wgServer . $wgScript, round( $wgNewPasswordExpiry / 86400 ) );
729 $result = $u->sendMail( wfMsg( $emailTitle ), $m );
730
731 return $result;
732 }
733
734
735 /**
736 * Run any hooks registered for logins, then HTTP redirect to
737 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
738 * nice message here, but that's really not as useful as just being sent to
739 * wherever you logged in from. It should be clear that the action was
740 * successful, given the lack of error messages plus the appearance of your
741 * name in the upper right.
742 *
743 * @private
744 */
745 function successfulLogin() {
746 global $wgUser, $wgOut;
747
748 # Run any hooks; display injected HTML if any, else redirect
749 $injected_html = '';
750 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
751
752 if( $injected_html !== '' ) {
753 $this->displaySuccessfulLogin( 'loginsuccess', $injected_html );
754 } else {
755 $titleObj = Title::newFromText( $this->mReturnTo );
756 if ( !$titleObj instanceof Title ) {
757 $titleObj = Title::newMainPage();
758 }
759 $wgOut->redirect( $titleObj->getFullURL( $this->mReturnToQuery ) );
760 }
761 }
762
763 /**
764 * Run any hooks registered for logins, then display a message welcoming
765 * the user.
766 *
767 * @private
768 */
769 function successfulCreation() {
770 global $wgUser, $wgOut;
771
772 # Run any hooks; display injected HTML
773 $injected_html = '';
774 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
775
776 $this->displaySuccessfulLogin( 'welcomecreation', $injected_html );
777 }
778
779 /**
780 * Display a "login successful" page.
781 */
782 private function displaySuccessfulLogin( $msgname, $injected_html ) {
783 global $wgOut, $wgUser;
784
785 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
786 $wgOut->setRobotPolicy( 'noindex,nofollow' );
787 $wgOut->setArticleRelated( false );
788 $wgOut->addWikiMsg( $msgname, $wgUser->getName() );
789 $wgOut->addHTML( $injected_html );
790
791 if ( !empty( $this->mReturnTo ) ) {
792 $wgOut->returnToMain( null, $this->mReturnTo, $this->mReturnToQuery );
793 } else {
794 $wgOut->returnToMain( null );
795 }
796 }
797
798 /** */
799 function userNotPrivilegedMessage($errors) {
800 global $wgOut;
801
802 $wgOut->setPageTitle( wfMsg( 'permissionserrors' ) );
803 $wgOut->setRobotPolicy( 'noindex,nofollow' );
804 $wgOut->setArticleRelated( false );
805
806 $wgOut->addWikitext( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
807 // Stuff that might want to be added at the end. For example, instruc-
808 // tions if blocked.
809 $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
810
811 $wgOut->returnToMain( false );
812 }
813
814 /** */
815 function userBlockedMessage() {
816 global $wgOut, $wgUser;
817
818 # Let's be nice about this, it's likely that this feature will be used
819 # for blocking large numbers of innocent people, e.g. range blocks on
820 # schools. Don't blame it on the user. There's a small chance that it
821 # really is the user's fault, i.e. the username is blocked and they
822 # haven't bothered to log out before trying to create an account to
823 # evade it, but we'll leave that to their guilty conscience to figure
824 # out.
825
826 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
827 $wgOut->setRobotPolicy( 'noindex,nofollow' );
828 $wgOut->setArticleRelated( false );
829
830 $ip = wfGetIP();
831 $blocker = User::whoIs( $wgUser->mBlock->mBy );
832 $block_reason = $wgUser->mBlock->mReason;
833
834 if ( strval( $block_reason ) === '' ) {
835 $block_reason = wfMsg( 'blockednoreason' );
836 }
837 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
838 $wgOut->returnToMain( false );
839 }
840
841 /**
842 * @private
843 */
844 function mainLoginForm( $msg, $msgtype = 'error' ) {
845 global $wgUser, $wgOut, $wgHiddenPrefs, $wgEnableEmail;
846 global $wgCookiePrefix, $wgLoginLanguageSelector;
847 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
848
849 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
850
851 if ( $this->mType == 'signup' ) {
852 // Block signup here if in readonly. Keeps user from
853 // going through the process (filling out data, etc)
854 // and being informed later.
855 if ( wfReadOnly() ) {
856 $wgOut->readOnlyPage();
857 return;
858 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
859 $this->userBlockedMessage();
860 return;
861 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
862 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
863 return;
864 }
865 }
866
867 if ( '' == $this->mName ) {
868 if ( $wgUser->isLoggedIn() ) {
869 $this->mName = $wgUser->getName();
870 } else {
871 $this->mName = isset( $_COOKIE[$wgCookiePrefix.'UserName'] ) ? $_COOKIE[$wgCookiePrefix.'UserName'] : null;
872 }
873 }
874
875 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
876
877 if ( $this->mType == 'signup' ) {
878 $template = new UsercreateTemplate();
879 $q = 'action=submitlogin&type=signup';
880 $linkq = 'type=login';
881 $linkmsg = 'gotaccount';
882 } else {
883 $template = new UserloginTemplate();
884 $q = 'action=submitlogin&type=login';
885 $linkq = 'type=signup';
886 $linkmsg = 'nologin';
887 }
888
889 if ( !empty( $this->mReturnTo ) ) {
890 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
891 if ( !empty( $this->mReturnToQuery ) )
892 $returnto .= '&returntoquery=' .
893 wfUrlencode( $this->mReturnToQuery );
894 $q .= $returnto;
895 $linkq .= $returnto;
896 }
897
898 # Pass any language selection on to the mode switch link
899 if( $wgLoginLanguageSelector && $this->mLanguage )
900 $linkq .= '&uselang=' . $this->mLanguage;
901
902 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalUrl( $linkq ) ) . '">';
903 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
904 $link .= '</a>';
905
906 # Don't show a "create account" link if the user can't
907 if( $this->showCreateOrLoginLink( $wgUser ) )
908 $template->set( 'link', wfMsgWikiHtml( $linkmsg, $link ) );
909 else
910 $template->set( 'link', '' );
911
912 $template->set( 'header', '' );
913 $template->set( 'name', $this->mName );
914 $template->set( 'password', $this->mPassword );
915 $template->set( 'retype', $this->mRetype );
916 $template->set( 'email', $this->mEmail );
917 $template->set( 'realname', $this->mRealName );
918 $template->set( 'domain', $this->mDomain );
919
920 $template->set( 'action', $titleObj->getLocalUrl( $q ) );
921 $template->set( 'message', $msg );
922 $template->set( 'messagetype', $msgtype );
923 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
924 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
925 $template->set( 'useemail', $wgEnableEmail );
926 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
927 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
928 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
929 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) or $this->mRemember );
930
931 # Prepare language selection links as needed
932 if( $wgLoginLanguageSelector ) {
933 $template->set( 'languages', $this->makeLanguageSelector() );
934 if( $this->mLanguage )
935 $template->set( 'uselang', $this->mLanguage );
936 }
937
938 // Give authentication and captcha plugins a chance to modify the form
939 $wgAuth->modifyUITemplate( $template, $this->mType );
940 if ( $this->mType == 'signup' ) {
941 wfRunHooks( 'UserCreateForm', array( &$template ) );
942 } else {
943 wfRunHooks( 'UserLoginForm', array( &$template ) );
944 }
945
946 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
947 $wgOut->setRobotPolicy( 'noindex,nofollow' );
948 $wgOut->setArticleRelated( false );
949 $wgOut->disallowUserJs(); // just in case...
950 $wgOut->addTemplate( $template );
951 }
952
953 /**
954 * @private
955 */
956 function showCreateOrLoginLink( &$user ) {
957 if( $this->mType == 'signup' ) {
958 return( true );
959 } elseif( $user->isAllowed( 'createaccount' ) ) {
960 return( true );
961 } else {
962 return( false );
963 }
964 }
965
966 /**
967 * Check if a session cookie is present.
968 *
969 * This will not pick up a cookie set during _this_ request, but is meant
970 * to ensure that the client is returning the cookie which was set on a
971 * previous pass through the system.
972 *
973 * @private
974 */
975 function hasSessionCookie() {
976 global $wgDisableCookieCheck, $wgRequest;
977 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
978 }
979
980 /**
981 * @private
982 */
983 function cookieRedirectCheck( $type ) {
984 global $wgOut;
985
986 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
987 $query = array( 'wpCookieCheck' => $type );
988 if ( $this->mReturnTo ) $query['returnto'] = $this->mReturnTo;
989 $check = $titleObj->getFullURL( $query );
990
991 return $wgOut->redirect( $check );
992 }
993
994 /**
995 * @private
996 */
997 function onCookieRedirectCheck( $type ) {
998 if ( !$this->hasSessionCookie() ) {
999 if ( $type == 'new' ) {
1000 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
1001 } else if ( $type == 'login' ) {
1002 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
1003 } else {
1004 # shouldn't happen
1005 return $this->mainLoginForm( wfMsg( 'error' ) );
1006 }
1007 } else {
1008 return $this->successfulLogin();
1009 }
1010 }
1011
1012 /**
1013 * @private
1014 */
1015 function throttleHit( $limit ) {
1016 $this->mainLoginForm( wfMsgExt( 'acct_creation_throttle_hit', array( 'parseinline' ), $limit ) );
1017 }
1018
1019 /**
1020 * Produce a bar of links which allow the user to select another language
1021 * during login/registration but retain "returnto"
1022 *
1023 * @return string
1024 */
1025 function makeLanguageSelector() {
1026 global $wgLang;
1027
1028 $msg = wfMsgForContent( 'loginlanguagelinks' );
1029 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
1030 $langs = explode( "\n", $msg );
1031 $links = array();
1032 foreach( $langs as $lang ) {
1033 $lang = trim( $lang, '* ' );
1034 $parts = explode( '|', $lang );
1035 if (count($parts) >= 2) {
1036 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
1037 }
1038 }
1039 return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', $wgLang->pipeList( $links ) ) : '';
1040 } else {
1041 return '';
1042 }
1043 }
1044
1045 /**
1046 * Create a language selector link for a particular language
1047 * Links back to this page preserving type and returnto
1048 *
1049 * @param $text Link text
1050 * @param $lang Language code
1051 */
1052 function makeLanguageSelectorLink( $text, $lang ) {
1053 global $wgUser;
1054 $self = SpecialPage::getTitleFor( 'Userlogin' );
1055 $attr = array( 'uselang' => $lang );
1056 if( $this->mType == 'signup' )
1057 $attr['type'] = 'signup';
1058 if( $this->mReturnTo )
1059 $attr['returnto'] = $this->mReturnTo;
1060 $skin = $wgUser->getSkin();
1061 return $skin->linkKnown(
1062 $self,
1063 htmlspecialchars( $text ),
1064 array(),
1065 $attr
1066 );
1067 }
1068 }