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