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