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