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