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