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