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