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