551d9c06e201f724c0acce9d06373e7e918c5883
[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->successfulLogin( 'welcomecreation', $wgUser->getName(), false );
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 $abortError = '';
504 if( !wfRunHooks( 'AbortNewAccount', array( $user->getName(), &$abortError ) ) ) {
505 // Hook point to add extra creation throttles and blocks
506 wfDebug( __METHOD__.": a hook blocked creation\n" );
507 $this->mainLoginForm( $abortError );
508 return self::ABORTED;
509 }
510
511 wfDebug( __METHOD__.": creating account\n" );
512 $user = $this->initUser( $user, true );
513 return self::SUCCESS;
514 }
515
516 function processLogin() {
517 global $wgUser, $wgAuth;
518
519 switch ($this->authenticateUserData())
520 {
521 case self::SUCCESS:
522 # We've verified now, update the real record
523 if( (bool)$this->mRemember != (bool)$wgUser->getOption( 'rememberpassword' ) ) {
524 $wgUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 );
525 $wgUser->saveSettings();
526 } else {
527 $wgUser->invalidateCache();
528 }
529 $wgUser->setCookies();
530
531 if( $this->hasSessionCookie() || $this->mSkipCookieCheck ) {
532 /* Replace the language object to provide user interface in correct
533 * language immediately on this first page load.
534 */
535 global $wgLang, $wgRequest;
536 $code = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
537 $wgLang = Language::factory( $code );
538 return $this->successfulLogin( 'loginsuccess', $wgUser->getName() );
539 } else {
540 return $this->cookieRedirectCheck( 'login' );
541 }
542 break;
543
544 case self::NO_NAME:
545 case self::ILLEGAL:
546 $this->mainLoginForm( wfMsg( 'noname' ) );
547 break;
548 case self::WRONG_PLUGIN_PASS:
549 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
550 break;
551 case self::NOT_EXISTS:
552 if( $wgUser->isAllowed( 'createaccount' ) ){
553 $this->mainLoginForm( wfMsg( 'nosuchuser', htmlspecialchars( $this->mName ) ) );
554 } else {
555 $this->mainLoginForm( wfMsg( 'nosuchusershort', htmlspecialchars( $this->mName ) ) );
556 }
557 break;
558 case self::WRONG_PASS:
559 $this->mainLoginForm( wfMsg( 'wrongpassword' ) );
560 break;
561 case self::EMPTY_PASS:
562 $this->mainLoginForm( wfMsg( 'wrongpasswordempty' ) );
563 break;
564 case self::RESET_PASS:
565 $this->resetLoginForm( wfMsg( 'resetpass_announce' ) );
566 break;
567 case self::CREATE_BLOCKED:
568 $this->userBlockedMessage();
569 break;
570 case self::THROTTLED:
571 $this->mainLoginForm( wfMsg( 'login-throttled' ) );
572 break;
573 default:
574 throw new MWException( "Unhandled case value" );
575 }
576 }
577
578 function resetLoginForm( $error ) {
579 global $wgOut;
580 $wgOut->addWikiText( "<div class=\"errorbox\">$error</div>" );
581 $reset = new PasswordResetForm( $this->mName, $this->mPassword );
582 $reset->execute( null );
583 }
584
585 /**
586 * @private
587 */
588 function mailPassword() {
589 global $wgUser, $wgOut, $wgAuth;
590
591 if( !$wgAuth->allowPasswordChange() ) {
592 $this->mainLoginForm( wfMsg( 'resetpass_forbidden' ) );
593 return;
594 }
595
596 # Check against blocked IPs
597 # fixme -- should we not?
598 if( $wgUser->isBlocked() ) {
599 $this->mainLoginForm( wfMsg( 'blocked-mailpassword' ) );
600 return;
601 }
602
603 # Check against the rate limiter
604 if( $wgUser->pingLimiter( 'mailpassword' ) ) {
605 $wgOut->rateLimited();
606 return;
607 }
608
609 if ( '' == $this->mName ) {
610 $this->mainLoginForm( wfMsg( 'noname' ) );
611 return;
612 }
613 $u = User::newFromName( $this->mName );
614 if( is_null( $u ) ) {
615 $this->mainLoginForm( wfMsg( 'noname' ) );
616 return;
617 }
618 if ( 0 == $u->getID() ) {
619 $this->mainLoginForm( wfMsg( 'nosuchuser', $u->getName() ) );
620 return;
621 }
622
623 # Check against password throttle
624 if ( $u->isPasswordReminderThrottled() ) {
625 global $wgPasswordReminderResendTime;
626 # Round the time in hours to 3 d.p., in case someone is specifying minutes or seconds.
627 $this->mainLoginForm( wfMsgExt( 'throttled-mailpassword', array( 'parsemag' ),
628 round( $wgPasswordReminderResendTime, 3 ) ) );
629 return;
630 }
631
632 $result = $this->mailPasswordInternal( $u, true, 'passwordremindertitle', 'passwordremindertext' );
633 if( WikiError::isError( $result ) ) {
634 $this->mainLoginForm( wfMsg( 'mailerror', $result->getMessage() ) );
635 } else {
636 $this->mainLoginForm( wfMsg( 'passwordsent', $u->getName() ), 'success' );
637 }
638 }
639
640
641 /**
642 * @param object user
643 * @param bool throttle
644 * @param string message name of email title
645 * @param string message name of email text
646 * @return mixed true on success, WikiError on failure
647 * @private
648 */
649 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
650 global $wgCookiePath, $wgCookieDomain, $wgCookiePrefix, $wgCookieSecure;
651 global $wgServer, $wgScript, $wgUser;
652
653 if ( '' == $u->getEmail() ) {
654 return new WikiError( wfMsg( 'noemail', $u->getName() ) );
655 }
656 $ip = wfGetIP();
657 if( !$ip ) {
658 return new WikiError( wfMsg( 'badipaddress' ) );
659 }
660
661 wfRunHooks( 'User::mailPasswordInternal', array(&$wgUser, &$ip, &$u) );
662
663 $np = $u->randomPassword();
664 $u->setNewpassword( $np, $throttle );
665 $u->saveSettings();
666
667 $m = wfMsg( $emailText, $ip, $u->getName(), $np, $wgServer . $wgScript );
668 $result = $u->sendMail( wfMsg( $emailTitle ), $m );
669
670 return $result;
671 }
672
673
674 /**
675 * @param string $msg Message key that will be shown on success
676 * @param $params String: parameters for the above message
677 * @param bool $auto Toggle auto-redirect to main page; default true
678 * @private
679 */
680 function successfulLogin( $msg, $params, $auto = true ) {
681 global $wgUser;
682 global $wgOut;
683
684 # Run any hooks; ignore results
685
686 $injected_html = '';
687 wfRunHooks('UserLoginComplete', array(&$wgUser, &$injected_html));
688
689 $wgOut->setPageTitle( wfMsg( 'loginsuccesstitle' ) );
690 $wgOut->setRobotPolicy( 'noindex,nofollow' );
691 $wgOut->setArticleRelated( false );
692 $wgOut->addWikiMsgArray( $msg, $params );
693 $wgOut->addHtml( $injected_html );
694 if ( !empty( $this->mReturnTo ) ) {
695 $wgOut->returnToMain( $auto, $this->mReturnTo );
696 } else {
697 $wgOut->returnToMain( $auto );
698 }
699 }
700
701 /** */
702 function userNotPrivilegedMessage($errors) {
703 global $wgOut;
704
705 $wgOut->setPageTitle( wfMsg( 'permissionserrors' ) );
706 $wgOut->setRobotPolicy( 'noindex,nofollow' );
707 $wgOut->setArticleRelated( false );
708
709 $wgOut->addWikitext( $wgOut->formatPermissionsErrorMessage( $errors, 'createaccount' ) );
710 // Stuff that might want to be added at the end. For example, instructions if blocked.
711 $wgOut->addWikiMsg( 'cantcreateaccount-nonblock-text' );
712
713 $wgOut->returnToMain( false );
714 }
715
716 /** */
717 function userBlockedMessage() {
718 global $wgOut, $wgUser;
719
720 # Let's be nice about this, it's likely that this feature will be used
721 # for blocking large numbers of innocent people, e.g. range blocks on
722 # schools. Don't blame it on the user. There's a small chance that it
723 # really is the user's fault, i.e. the username is blocked and they
724 # haven't bothered to log out before trying to create an account to
725 # evade it, but we'll leave that to their guilty conscience to figure
726 # out.
727
728 $wgOut->setPageTitle( wfMsg( 'cantcreateaccounttitle' ) );
729 $wgOut->setRobotPolicy( 'noindex,nofollow' );
730 $wgOut->setArticleRelated( false );
731
732 $ip = wfGetIP();
733 $blocker = User::whoIs( $wgUser->mBlock->mBy );
734 $block_reason = $wgUser->mBlock->mReason;
735
736 if ( strval( $block_reason ) === '' ) {
737 $block_reason = wfMsg( 'blockednoreason' );
738 }
739 $wgOut->addWikiMsg( 'cantcreateaccount-text', $ip, $block_reason, $blocker );
740 $wgOut->returnToMain( false );
741 }
742
743 /**
744 * @private
745 */
746 function mainLoginForm( $msg, $msgtype = 'error' ) {
747 global $wgUser, $wgOut, $wgAllowRealName, $wgEnableEmail;
748 global $wgCookiePrefix, $wgAuth, $wgLoginLanguageSelector;
749 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
750
751 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
752
753 if ( $this->mType == 'signup' ) {
754 // Block signup here if in readonly. Keeps user from
755 // going through the process (filling out data, etc)
756 // and being informed later.
757 if ( wfReadOnly() ) {
758 $wgOut->readOnlyPage();
759 return;
760 } elseif ( $wgUser->isBlockedFromCreateAccount() ) {
761 $this->userBlockedMessage();
762 return;
763 } elseif ( count( $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $wgUser, true ) )>0 ) {
764 $wgOut->showPermissionsErrorPage( $permErrors, 'createaccount' );
765 return;
766 }
767 }
768
769 if ( '' == $this->mName ) {
770 if ( $wgUser->isLoggedIn() ) {
771 $this->mName = $wgUser->getName();
772 } else {
773 $this->mName = isset( $_COOKIE[$wgCookiePrefix.'UserName'] ) ? $_COOKIE[$wgCookiePrefix.'UserName'] : null;
774 }
775 }
776
777 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
778
779 if ( $this->mType == 'signup' ) {
780 $template = new UsercreateTemplate();
781 $q = 'action=submitlogin&type=signup';
782 $linkq = 'type=login';
783 $linkmsg = 'gotaccount';
784 } else {
785 $template = new UserloginTemplate();
786 $q = 'action=submitlogin&type=login';
787 $linkq = 'type=signup';
788 $linkmsg = 'nologin';
789 }
790
791 if ( !empty( $this->mReturnTo ) ) {
792 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo );
793 $q .= $returnto;
794 $linkq .= $returnto;
795 }
796
797 # Pass any language selection on to the mode switch link
798 if( $wgLoginLanguageSelector && $this->mLanguage )
799 $linkq .= '&uselang=' . $this->mLanguage;
800
801 $link = '<a href="' . htmlspecialchars ( $titleObj->getLocalUrl( $linkq ) ) . '">';
802 $link .= wfMsgHtml( $linkmsg . 'link' ); # Calling either 'gotaccountlink' or 'nologinlink'
803 $link .= '</a>';
804
805 # Don't show a "create account" link if the user can't
806 if( $this->showCreateOrLoginLink( $wgUser ) )
807 $template->set( 'link', wfMsgHtml( $linkmsg, $link ) );
808 else
809 $template->set( 'link', '' );
810
811 $template->set( 'header', '' );
812 $template->set( 'name', $this->mName );
813 $template->set( 'password', $this->mPassword );
814 $template->set( 'retype', $this->mRetype );
815 $template->set( 'email', $this->mEmail );
816 $template->set( 'realname', $this->mRealName );
817 $template->set( 'domain', $this->mDomain );
818
819 $template->set( 'action', $titleObj->getLocalUrl( $q ) );
820 $template->set( 'message', $msg );
821 $template->set( 'messagetype', $msgtype );
822 $template->set( 'createemail', $wgEnableEmail && $wgUser->isLoggedIn() );
823 $template->set( 'userealname', $wgAllowRealName );
824 $template->set( 'useemail', $wgEnableEmail );
825 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
826 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
827 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
828 $template->set( 'remember', $wgUser->getOption( 'rememberpassword' ) or $this->mRemember );
829
830 # Prepare language selection links as needed
831 if( $wgLoginLanguageSelector ) {
832 $template->set( 'languages', $this->makeLanguageSelector() );
833 if( $this->mLanguage )
834 $template->set( 'uselang', $this->mLanguage );
835 }
836
837 // Give authentication and captcha plugins a chance to modify the form
838 $wgAuth->modifyUITemplate( $template );
839 if ( $this->mType == 'signup' ) {
840 wfRunHooks( 'UserCreateForm', array( &$template ) );
841 } else {
842 wfRunHooks( 'UserLoginForm', array( &$template ) );
843 }
844
845 $wgOut->setPageTitle( wfMsg( 'userlogin' ) );
846 $wgOut->setRobotPolicy( 'noindex,nofollow' );
847 $wgOut->setArticleRelated( false );
848 $wgOut->disallowUserJs(); // just in case...
849 $wgOut->addTemplate( $template );
850 }
851
852 /**
853 * @private
854 */
855 function showCreateOrLoginLink( &$user ) {
856 if( $this->mType == 'signup' ) {
857 return( true );
858 } elseif( $user->isAllowed( 'createaccount' ) ) {
859 return( true );
860 } else {
861 return( false );
862 }
863 }
864
865 /**
866 * Check if a session cookie is present.
867 *
868 * This will not pick up a cookie set during _this_ request, but is
869 * meant to ensure that the client is returning the cookie which was
870 * set on a previous pass through the system.
871 *
872 * @private
873 */
874 function hasSessionCookie() {
875 global $wgDisableCookieCheck, $wgRequest;
876 return $wgDisableCookieCheck ? true : $wgRequest->checkSessionCookie();
877 }
878
879 /**
880 * @private
881 */
882 function cookieRedirectCheck( $type ) {
883 global $wgOut;
884
885 $titleObj = SpecialPage::getTitleFor( 'Userlogin' );
886 $check = $titleObj->getFullURL( 'wpCookieCheck='.$type );
887
888 return $wgOut->redirect( $check );
889 }
890
891 /**
892 * @private
893 */
894 function onCookieRedirectCheck( $type ) {
895 global $wgUser;
896
897 if ( !$this->hasSessionCookie() ) {
898 if ( $type == 'new' ) {
899 return $this->mainLoginForm( wfMsgExt( 'nocookiesnew', array( 'parseinline' ) ) );
900 } else if ( $type == 'login' ) {
901 return $this->mainLoginForm( wfMsgExt( 'nocookieslogin', array( 'parseinline' ) ) );
902 } else {
903 # shouldn't happen
904 return $this->mainLoginForm( wfMsg( 'error' ) );
905 }
906 } else {
907 return $this->successfulLogin( 'loginsuccess', $wgUser->getName() );
908 }
909 }
910
911 /**
912 * @private
913 */
914 function throttleHit( $limit ) {
915 global $wgOut;
916
917 $wgOut->addWikiMsg( 'acct_creation_throttle_hit', $limit );
918 }
919
920 /**
921 * Produce a bar of links which allow the user to select another language
922 * during login/registration but retain "returnto"
923 *
924 * @return string
925 */
926 function makeLanguageSelector() {
927 $msg = wfMsgForContent( 'loginlanguagelinks' );
928 if( $msg != '' && !wfEmptyMsg( 'loginlanguagelinks', $msg ) ) {
929 $langs = explode( "\n", $msg );
930 $links = array();
931 foreach( $langs as $lang ) {
932 $lang = trim( $lang, '* ' );
933 $parts = explode( '|', $lang );
934 if (count($parts) >= 2) {
935 $links[] = $this->makeLanguageSelectorLink( $parts[0], $parts[1] );
936 }
937 }
938 return count( $links ) > 0 ? wfMsgHtml( 'loginlanguagelabel', implode( ' | ', $links ) ) : '';
939 } else {
940 return '';
941 }
942 }
943
944 /**
945 * Create a language selector link for a particular language
946 * Links back to this page preserving type and returnto
947 *
948 * @param $text Link text
949 * @param $lang Language code
950 */
951 function makeLanguageSelectorLink( $text, $lang ) {
952 global $wgUser;
953 $self = SpecialPage::getTitleFor( 'Userlogin' );
954 $attr[] = 'uselang=' . $lang;
955 if( $this->mType == 'signup' )
956 $attr[] = 'type=signup';
957 if( $this->mReturnTo )
958 $attr[] = 'returnto=' . $this->mReturnTo;
959 $skin = $wgUser->getSkin();
960 return $skin->makeKnownLinkObj( $self, htmlspecialchars( $text ), implode( '&', $attr ) );
961 }
962 }