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