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