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