Special developer powers in SpecialMakesysop, different defaults for anons and logged...
[mediawiki.git] / includes / User.php
blobd53e30c012f940b765a2431d7531cf1d27913b71
1 <?php
2 # See user.doc
4 include_once( "WatchedItem.php" );
6 class User {
7 /* private */ var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
8 /* private */ var $mRights, $mOptions;
9 /* private */ var $mDataLoaded, $mNewpassword;
10 /* private */ var $mSkin;
11 /* private */ var $mBlockedby, $mBlockreason;
12 /* private */ var $mTouched;
13 /* private */ var $mCookiePassword;
15 function User()
17 $this->loadDefaults();
20 # Static factory method
22 function newFromName( $name )
24 $u = new User();
26 # Clean up name according to title rules
28 $t = Title::newFromText( $name );
29 $u->setName( $t->getText() );
30 return $u;
33 /* static */ function whoIs( $id )
35 return wfGetSQL( "user", "user_name", "user_id=$id" );
38 /* static */ function idFromName( $name )
40 $nt = Title::newFromText( $name );
41 $sql = "SELECT user_id FROM user WHERE user_name='" .
42 wfStrencode( $nt->getText() ) . "'";
43 $res = wfQuery( $sql, DB_READ, "User::idFromName" );
45 if ( 0 == wfNumRows( $res ) ) { return 0; }
46 else {
47 $s = wfFetchObject( $res );
48 return $s->user_id;
52 # does the string match an anonymous user IP address?
53 /* static */ function isIP( $name ) {
54 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
58 /* static */ function randomPassword()
60 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
61 $l = strlen( $pwchars ) - 1;
63 wfSeedRandom();
64 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
65 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
66 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
67 $pwchars{mt_rand( 0, $l )};
68 return $np;
71 function loadDefaults()
73 global $wgLang, $wgIP;
74 global $wgNamespacesToBeSearchedDefault;
76 $this->mId = $this->mNewtalk = 0;
77 $this->mName = $wgIP;
78 $this->mEmail = "";
79 $this->mPassword = $this->mNewpassword = "";
80 $this->mRights = array();
81 $defOpt = $wgLang->getDefaultAnonOptions() ;
82 foreach ( $defOpt as $oname => $val ) {
83 $this->mOptions[$oname] = $val;
85 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
86 $this->mOptions["searchNs".$nsnum] = $val;
88 unset( $this->mSkin );
89 $this->mDataLoaded = false;
90 $this->mBlockedby = -1; # Unset
91 $this->mTouched = '0'; # Allow any pages to be cached
92 $this->cookiePassword = "";
95 function loadDefaultUserOptions()
97 global $wgLang;
98 $this->mOptions = $wgLang->getDefaultUserOptions();
101 /* private */ function getBlockedStatus()
103 global $wgIP, $wgBlockCache;
105 if ( -1 != $this->mBlockedby ) { return; }
107 $this->mBlockedby = 0;
109 # User blocking
110 if ( $this->mId ) {
111 $block = new Block();
112 if ( $block->load( $wgIP , $this->mId ) ) {
113 $this->mBlockedby = $block->mBy;
114 $this->mBlockreason = $block->mReason;
118 # IP/range blocking
119 if ( !$this->mBlockedby ) {
120 $block = $wgBlockCache->get( $wgIP );
121 if ( $block !== false ) {
122 $this->mBlockedby = $block->mBy;
123 $this->mBlockreason = $block->mReason;
128 function isBlocked()
130 $this->getBlockedStatus();
131 if ( 0 == $this->mBlockedby ) { return false; }
132 return true;
135 function blockedBy() {
136 $this->getBlockedStatus();
137 return $this->mBlockedby;
140 function blockedFor() {
141 $this->getBlockedStatus();
142 return $this->mBlockreason;
145 function SetupSession() {
146 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
147 global $wsUserID, $wsUserName, $wsUserPassword, $wsUploadFiles;
148 if( $wgSessionsInMemcached ) {
149 include_once( "MemcachedSessions.php" );
151 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
152 session_cache_limiter( "private, must-revalidate" );
153 session_start();
154 session_register( "wsUserID" );
155 session_register( "wsUserName" );
156 session_register( "wsUserPassword" );
157 session_register( "wsUploadFiles" );
160 /* static */ function loadFromSession()
162 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
163 global $wgMemc, $wgDBname;
165 if ( isset( $wsUserID ) ) {
166 if ( 0 != $wsUserID ) {
167 $sId = $wsUserID;
168 } else {
169 return new User();
171 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserID"] ) ) {
172 $sId = IntVal( $HTTP_COOKIE_VARS["{$wgDBname}UserID"] );
173 $wsUserID = $sId;
174 } else {
175 return new User();
177 if ( isset( $wsUserName ) ) {
178 $sName = $wsUserName;
179 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}UserName"] ) ) {
180 $sName = $HTTP_COOKIE_VARS["{$wgDBname}UserName"];
181 $wsUserName = $sName;
182 } else {
183 return new User();
186 $passwordCorrect = FALSE;
187 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
188 if($makenew = !$user) {
189 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
190 $user = new User();
191 $user->mId = $sId;
192 $user->loadFromDatabase();
193 } else {
194 wfDebug( "User::loadFromSession() got from cache!\n" );
197 if ( isset( $wsUserPassword ) ) {
198 $passwordCorrect = $wsUserPassword == $user->mPassword;
199 } else if ( isset( $HTTP_COOKIE_VARS["{$wgDBname}Password"] ) ) {
200 $user->mCookiePassword = $HTTP_COOKIE_VARS["{$wgDBname}Password"];
201 $wsUserPassword = $user->addSalt( $user->mCookiePassword );
202 $passwordCorrect = $wsUserPassword == $user->mPassword;
203 } else {
204 return new User(); # Can't log in from session
207 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
208 if($makenew) {
209 if($wgMemc->set( $key, $user ))
210 wfDebug( "User::loadFromSession() successfully saved user\n" );
211 else
212 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
214 $user->spreadBlock();
215 return $user;
217 return new User(); # Can't log in from session
220 function loadFromDatabase()
222 if ( $this->mDataLoaded ) { return; }
224 # Paranoia
225 $this->mId = IntVal( $this->mId );
227 # check in separate table if there are changes to the talk page
228 $this->mNewtalk=0; # reset talk page status
229 if($this->mId) {
230 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
231 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
233 if (wfNumRows($res)>0) {
234 $this->mNewtalk= 1;
236 wfFreeResult( $res );
237 } else {
238 # TEST THIS @@@
239 global $wgDBname, $wgMemc;
240 $key = "$wgDBname:newtalk:ip:{$this->mName}";
241 $newtalk = $wgMemc->get( $key );
242 if( ! is_integer( $newtalk ) ){
243 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
244 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
246 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
247 wfFreeResult( $res );
249 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
250 } else {
251 $this->mNewtalk = $newtalk ? 1 : 0;
254 if(!$this->mId) {
255 $this->mDataLoaded = true;
256 return;
257 } # the following stuff is for non-anonymous users only
259 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
260 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
261 "{$this->mId}";
262 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
264 if ( wfNumRows( $res ) > 0 ) {
265 $s = wfFetchObject( $res );
266 $this->mName = $s->user_name;
267 $this->mEmail = $s->user_email;
268 $this->mPassword = $s->user_password;
269 $this->mNewpassword = $s->user_newpassword;
270 $this->decodeOptions( $s->user_options );
271 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
272 $this->mTouched = $s->user_touched;
275 wfFreeResult( $res );
276 $this->mDataLoaded = true;
279 function getID() { return $this->mId; }
280 function setID( $v ) {
281 $this->mId = $v;
282 $this->mDataLoaded = false;
285 function getName() {
286 $this->loadFromDatabase();
287 return $this->mName;
290 function setName( $str )
292 $this->loadFromDatabase();
293 $this->mName = $str;
296 function getNewtalk()
298 $this->loadFromDatabase();
299 return ( 0 != $this->mNewtalk );
302 function setNewtalk( $val )
304 $this->loadFromDatabase();
305 $this->mNewtalk = $val;
306 $this->invalidateCache();
309 function invalidateCache() {
310 $this->loadFromDatabase();
311 $this->mTouched = wfTimestampNow();
312 # Don't forget to save the options after this or
313 # it won't take effect!
316 function validateCache( $timestamp ) {
317 $this->loadFromDatabase();
318 return ($timestamp >= $this->mTouched);
321 function getPassword()
323 $this->loadFromDatabase();
324 return $this->mPassword;
327 function getNewpassword()
329 $this->loadFromDatabase();
330 return $this->mNewpassword;
333 function addSalt( $p )
335 global $wgPasswordSalt;
336 if($wgPasswordSalt)
337 return md5( "{$this->mId}-{$p}" );
338 else
339 return $p;
342 function encryptPassword( $p )
344 return $this->addSalt( md5( $p ) );
347 function setPassword( $str )
349 $this->loadFromDatabase();
350 $this->setCookiePassword( $str );
351 $this->mPassword = $this->encryptPassword( $str );
352 $this->mNewpassword = "";
355 function setCookiePassword( $str )
357 $this->loadFromDatabase();
358 $this->mCookiePassword = md5( $str );
361 function setNewpassword( $str )
363 $this->loadFromDatabase();
364 $this->mNewpassword = $this->encryptPassword( $str );
367 function getEmail()
369 $this->loadFromDatabase();
370 return $this->mEmail;
373 function setEmail( $str )
375 $this->loadFromDatabase();
376 $this->mEmail = $str;
379 function getOption( $oname )
381 $this->loadFromDatabase();
382 if ( array_key_exists( $oname, $this->mOptions ) ) {
383 return $this->mOptions[$oname];
384 } else {
385 return "";
389 function setOption( $oname, $val )
391 $this->loadFromDatabase();
392 $this->mOptions[$oname] = $val;
393 $this->invalidateCache();
396 function getRights()
398 $this->loadFromDatabase();
399 return $this->mRights;
402 function addRight( $rname )
404 $this->loadFromDatabase();
405 array_push( $this->mRights, $rname );
406 $this->invalidateCache();
409 function isSysop()
411 $this->loadFromDatabase();
412 if ( 0 == $this->mId ) { return false; }
414 return in_array( "sysop", $this->mRights );
417 function isDeveloper()
419 $this->loadFromDatabase();
420 if ( 0 == $this->mId ) { return false; }
422 return in_array( "developer", $this->mRights );
425 function isBureaucrat()
427 $this->loadFromDatabase();
428 if ( 0 == $this->mId ) { return false; }
430 return in_array( "bureaucrat", $this->mRights );
433 function isBot()
435 $this->loadFromDatabase();
436 if ( 0 == $this->mId ) { return false; }
438 return in_array( "bot", $this->mRights );
441 function &getSkin()
443 if ( ! isset( $this->mSkin ) ) {
444 $skinNames = Skin::getSkinNames();
445 $s = $this->getOption( "skin" );
446 if ( "" == $s ) { $s = 0; }
448 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
449 else $sn = "Skin" . $skinNames[$s];
450 $this->mSkin = new $sn;
452 return $this->mSkin;
455 function isWatched( $title ) {
456 $wl = WatchedItem::fromUserTitle( $this, $title );
457 return $wl->isWatched();
460 function addWatch( $title ) {
461 $wl = WatchedItem::fromUserTitle( $this, $title );
462 $wl->addWatch();
463 $this->invalidateCache();
466 function removeWatch( $title ) {
467 $wl = WatchedItem::fromUserTitle( $this, $title );
468 $wl->removeWatch();
469 $this->invalidateCache();
473 /* private */ function encodeOptions()
475 $a = array();
476 foreach ( $this->mOptions as $oname => $oval ) {
477 array_push( $a, "{$oname}={$oval}" );
479 $s = implode( "\n", $a );
480 return wfStrencode( $s );
483 /* private */ function decodeOptions( $str )
485 $a = explode( "\n", $str );
486 foreach ( $a as $s ) {
487 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
488 $this->mOptions[$m[1]] = $m[2];
493 function setCookies()
495 global $wsUserID, $wsUserName, $wsUserPassword;
496 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
497 if ( 0 == $this->mId ) return;
498 $this->loadFromDatabase();
499 $exp = time() + $wgCookieExpiration;
501 $wsUserID = $this->mId;
502 setcookie( "{$wgDBname}UserID", $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
504 $wsUserName = $this->mName;
505 setcookie( "{$wgDBname}UserName", $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
507 $wsUserPassword = $this->mPassword;
508 if ( 1 == $this->getOption( "rememberpassword" ) ) {
509 setcookie( "{$wgDBname}Password", $this->mCookiePassword, $exp, $wgCookiePath, $wgCookieDomain );
510 } else {
511 setcookie( "{$wgDBname}Password", "", time() - 3600 );
515 function logout()
517 global $wsUserID, $wgCookiePath, $wgCookieDomain, $wgDBname;
518 $this->mId = 0;
520 $wsUserID = 0;
522 setcookie( "{$wgDBname}UserID", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
523 setcookie( "{$wgDBname}Password", "", time() - 3600, $wgCookiePath, $wgCookieDomain );
526 function saveSettings()
528 global $wgMemc, $wgDBname;
530 if ( ! $this->mNewtalk ) {
531 if( $this->mId ) {
532 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
533 wfQuery ($sql, DB_WRITE, "User::saveSettings");
534 } else {
535 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
536 wfQuery ($sql, DB_WRITE, "User::saveSettings");
537 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
540 if ( 0 == $this->mId ) { return; }
542 $sql = "UPDATE user SET " .
543 "user_name= '" . wfStrencode( $this->mName ) . "', " .
544 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
545 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
546 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
547 "user_options= '" . $this->encodeOptions() . "', " .
548 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
549 "user_touched= '" . wfStrencode( $this->mTouched ) .
550 "' WHERE user_id={$this->mId}";
551 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
552 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
555 # Checks if a user with the given name exists
557 function idForName()
559 $gotid = 0;
560 $s = trim( $this->mName );
561 if ( 0 == strcmp( "", $s ) ) return 0;
563 $sql = "SELECT user_id FROM user WHERE user_name='" .
564 wfStrencode( $s ) . "'";
565 $res = wfQuery( $sql, DB_READ, "User::idForName" );
566 if ( 0 == wfNumRows( $res ) ) { return 0; }
568 $s = wfFetchObject( $res );
569 if ( "" == $s ) return 0;
571 $gotid = $s->user_id;
572 wfFreeResult( $res );
573 return $gotid;
576 function addToDatabase()
578 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
579 "user_email, user_rights, user_options) " .
580 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
581 wfStrencode( $this->mPassword ) . "', '" .
582 wfStrencode( $this->mNewpassword ) . "', '" .
583 wfStrencode( $this->mEmail ) . "', '" .
584 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
585 $this->encodeOptions() . "')";
586 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
587 $this->mId = $this->idForName();
590 function spreadBlock()
592 global $wgIP;
593 # If the (non-anonymous) user is blocked, this function will block any IP address
594 # that they successfully log on from.
595 $fname = "User::spreadBlock";
597 wfDebug( "User:spreadBlock()\n" );
598 if ( $this->mId == 0 ) {
599 return;
602 $userblock = Block::newFromDB( "", $this->mId );
603 if ( !$userblock->isValid() ) {
604 return;
607 # Check if this IP address is already blocked
608 $ipblock = Block::newFromDB( $wgIP );
609 if ( $ipblock->isValid() ) {
610 # Just update the timestamp
611 $ipblock->updateTimestamp();
612 return;
615 # Make a new block object with the desired properties
616 wfDebug( "Autoblocking {$this->mUserName}@{$wgIP}\n" );
617 $ipblock->mAddress = $wgIP;
618 $ipblock->mUser = 0;
619 $ipblock->mBy = $userblock->mBy;
620 $ipblock->mReason = wfMsg( "autoblocker", $this->getName(), $userblock->mReason );
621 $ipblock->mTimestamp = wfTimestampNow();
622 $ipblock->mAuto = 1;
623 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
625 # Insert it
626 $ipblock->insert();
630 function getPageRenderingHash(){
631 static $hash = false;
632 if( $hash ){
633 return $hash;
636 // stubthreshold is only included below for completeness,
637 // it will always be 0 when this function is called by parsercache.
639 $confstr = $this->getOption( "quickbar" );
640 $confstr .= "!" . $this->getOption( "underline" );
641 $confstr .= "!" . $this->getOption( "hover" );
642 $confstr .= "!" . $this->getOption( "skin" );
643 $confstr .= "!" . $this->getOption( "math" );
644 $confstr .= "!" . $this->getOption( "highlightbroken" );
645 $confstr .= "!" . $this->getOption( "stubthreshold" );
646 $confstr .= "!" . $this->getOption( "editsection" );
647 $confstr .= "!" . $this->getOption( "editsectiononrightclick" );
648 $confstr .= "!" . $this->getOption( "showtoc" );
649 $confstr .= "!" . $this->getOption( "date" );
651 if(strlen($confstr) > 32)
652 $hash = md5($confstr);
653 else
654 $hash = $confstr;
655 return $hash;
658 function isAllowedToCreateAccount()
660 global $wgWhitelistAccount;
661 $allowed = false;
663 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
664 foreach ($wgWhitelistAccount as $right => $ok) {
665 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
666 $allowed |= ($ok && $userHasRight);
668 return $allowed;