Added per page support for inhibiting editsection links via the __NOEDITSECTION__...
[mediawiki.git] / includes / User.php
blobdba54884248c99801420d3971a4c8498e1300336
1 <?
2 # See user.doc
4 class User {
5 /* private */ var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
6 /* private */ var $mRights, $mOptions;
7 /* private */ var $mDataLoaded, $mNewpassword;
8 /* private */ var $mSkin;
9 /* private */ var $mBlockedby, $mBlockreason;
10 /* private */ var $mTouched;
11 /* private */ var $mCookiePassword;
13 function User()
15 $this->loadDefaults();
18 # Static factory method
20 function newFromName( $name )
22 $u = new User();
24 # Clean up name according to title rules
26 $t = Title::newFromText( $name );
27 $u->setName( $t->getText() );
28 return $u;
31 /* static */ function whoIs( $id )
33 return wfGetSQL( "user", "user_name", "user_id=$id" );
36 /* static */ function idFromName( $name )
38 $nt = Title::newFromText( $name );
39 $sql = "SELECT user_id FROM user WHERE user_name='" .
40 wfStrencode( $nt->getText() ) . "'";
41 $res = wfQuery( $sql, DB_READ, "User::idFromName" );
43 if ( 0 == wfNumRows( $res ) ) { return 0; }
44 else {
45 $s = wfFetchObject( $res );
46 return $s->user_id;
50 # does the string match an anonymous user IP address?
51 /* static */ function isIP( $name ) {
52 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
56 /* static */ function randomPassword()
58 $pwchars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
59 $l = strlen( $pwchars ) - 1;
61 wfSeedRandom();
62 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
63 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
64 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
65 $pwchars{mt_rand( 0, $l )};
66 return $np;
69 function loadDefaults()
71 global $wgLang ;
72 global $wgNamespacesToBeSearchedDefault;
74 $this->mId = $this->mNewtalk = 0;
75 $this->mName = getenv( "REMOTE_ADDR" );
76 $this->mEmail = "";
77 $this->mPassword = $this->mNewpassword = "";
78 $this->mRights = array();
79 $defOpt = $wgLang->getDefaultUserOptions() ;
80 foreach ( $defOpt as $oname => $val ) {
81 $this->mOptions[$oname] = $val;
83 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
84 $this->mOptions["searchNs".$nsnum] = $val;
86 unset( $this->mSkin );
87 $this->mDataLoaded = false;
88 $this->mBlockedby = -1; # Unset
89 $this->mTouched = '0'; # Allow any pages to be cached
90 $this->cookiePassword = "";
93 /* private */ function getBlockedStatus()
95 if ( -1 != $this->mBlockedby ) { return; }
97 $block = new Block();
98 if ( !$block->load( getenv( "REMOTE_ADDR" ), $this->mId ) ) {
99 wfDebug( getenv( "REMOTE_ADDR" ) ." is not blocked\n" );
100 $this->mBlockedby = 0;
101 return;
104 $this->mBlockedby = $block->mBy;
105 $this->mBlockreason = $block->mReason;
108 function isBlocked()
110 $this->getBlockedStatus();
111 if ( 0 == $this->mBlockedby ) { return false; }
112 return true;
115 function blockedBy() {
116 $this->getBlockedStatus();
117 return $this->mBlockedby;
120 function blockedFor() {
121 $this->getBlockedStatus();
122 return $this->mBlockreason;
125 /* static */ function loadFromSession()
127 global $HTTP_COOKIE_VARS, $wsUserID, $wsUserName, $wsUserPassword;
128 global $wgMemc, $wgDBname;
130 if ( isset( $wsUserID ) ) {
131 if ( 0 != $wsUserID ) {
132 $sId = $wsUserID;
133 } else {
134 return new User();
136 } else if ( isset( $HTTP_COOKIE_VARS["wcUserID"] ) ) {
137 $sId = $HTTP_COOKIE_VARS["wcUserID"];
138 $wsUserID = $sId;
139 } else {
140 return new User();
142 if ( isset( $wsUserName ) ) {
143 $sName = $wsUserName;
144 } else if ( isset( $HTTP_COOKIE_VARS["wcUserName"] ) ) {
145 $sName = $HTTP_COOKIE_VARS["wcUserName"];
146 $wsUserName = $sName;
147 } else {
148 return new User();
151 $passwordCorrect = FALSE;
152 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
153 if($makenew = !$user) {
154 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
155 $user = new User();
156 $user->mId = $sId;
157 $user->loadFromDatabase();
158 } else {
159 wfDebug( "User::loadFromSession() got from cache!\n" );
162 if ( isset( $wsUserPassword ) ) {
163 $passwordCorrect = $wsUserPassword == $user->mPassword;
164 } else if ( isset( $HTTP_COOKIE_VARS["wcUserPassword"] ) ) {
165 $user->mCookiePassword = $HTTP_COOKIE_VARS["wcUserPassword"];
166 $wsUserPassword = $user->addSalt( $user->mCookiePassword );
167 $passwordCorrect = $wsUserPassword == $user->mPassword;
168 } else {
169 return new User(); # Can't log in from session
172 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
173 if($makenew) {
174 if($wgMemc->set( $key, $user ))
175 wfDebug( "User::loadFromSession() successfully saved user\n" );
176 else
177 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
179 $user->spreadBlock();
180 return $user;
182 return new User(); # Can't log in from session
185 function loadFromDatabase()
187 if ( $this->mDataLoaded ) { return; }
188 # check in separate table if there are changes to the talk page
189 $this->mNewtalk=0; # reset talk page status
190 if($this->mId) {
191 $sql = "SELECT 1 FROM user_newtalk WHERE user_id={$this->mId}";
192 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
194 if (wfNumRows($res)>0) {
195 $this->mNewtalk= 1;
197 wfFreeResult( $res );
198 } else {
199 global $wgDBname, $wgMemc;
200 $key = "$wgDBname:newtalk:ip:{$this->mName}";
201 $newtalk = $wgMemc->get( $key );
202 if($newtalk === false) {
203 $sql = "SELECT 1 FROM user_newtalk WHERE user_ip='{$this->mName}'";
204 $res = wfQuery ($sql, DB_READ, "User::loadFromDatabase" );
206 $this->mNewtalk = (wfNumRows($res)>0) ? 1 : 0;
207 wfFreeResult( $res );
209 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
210 } else {
211 $this->mNewtalk = $newtalk ? 1 : 0;
214 if(!$this->mId) {
215 $this->mDataLoaded = true;
216 return;
217 } # the following stuff is for non-anonymous users only
219 $sql = "SELECT user_name,user_password,user_newpassword,user_email," .
220 "user_options,user_rights,user_touched FROM user WHERE user_id=" .
221 "{$this->mId}";
222 $res = wfQuery( $sql, DB_READ, "User::loadFromDatabase" );
224 if ( wfNumRows( $res ) > 0 ) {
225 $s = wfFetchObject( $res );
226 $this->mName = $s->user_name;
227 $this->mEmail = $s->user_email;
228 $this->mPassword = $s->user_password;
229 $this->mNewpassword = $s->user_newpassword;
230 $this->decodeOptions( $s->user_options );
231 $this->mRights = explode( ",", strtolower( $s->user_rights ) );
232 $this->mTouched = $s->user_touched;
235 wfFreeResult( $res );
236 $this->mDataLoaded = true;
239 function getID() { return $this->mId; }
240 function setID( $v ) {
241 $this->mId = $v;
242 $this->mDataLoaded = false;
245 function getName() {
246 $this->loadFromDatabase();
247 return $this->mName;
250 function setName( $str )
252 $this->loadFromDatabase();
253 $this->mName = $str;
256 function getNewtalk()
258 $this->loadFromDatabase();
259 return ( 0 != $this->mNewtalk );
262 function setNewtalk( $val )
264 $this->loadFromDatabase();
265 $this->mNewtalk = $val;
266 $this->invalidateCache();
269 function invalidateCache() {
270 $this->loadFromDatabase();
271 $this->mTouched = wfTimestampNow();
272 # Don't forget to save the options after this or
273 # it won't take effect!
276 function validateCache( $timestamp ) {
277 $this->loadFromDatabase();
278 return ($timestamp >= $this->mTouched);
281 function getPassword()
283 $this->loadFromDatabase();
284 return $this->mPassword;
287 function getNewpassword()
289 $this->loadFromDatabase();
290 return $this->mNewpassword;
293 function addSalt( $p )
295 global $wgPasswordSalt;
296 if($wgPasswordSalt)
297 return md5( "{$this->mId}-{$p}" );
298 else
299 return $p;
302 function encryptPassword( $p )
304 return $this->addSalt( md5( $p ) );
307 function setPassword( $str )
309 $this->loadFromDatabase();
310 $this->setCookiePassword( $str );
311 $this->mPassword = $this->encryptPassword( $str );
312 $this->mNewpassword = "";
315 function setCookiePassword( $str )
317 $this->loadFromDatabase();
318 $this->mCookiePassword = md5( $str );
321 function setNewpassword( $str )
323 $this->loadFromDatabase();
324 $this->mNewpassword = $this->encryptPassword( $str );
327 function getEmail()
329 $this->loadFromDatabase();
330 return $this->mEmail;
333 function setEmail( $str )
335 $this->loadFromDatabase();
336 $this->mEmail = $str;
339 function getOption( $oname )
341 $this->loadFromDatabase();
342 if ( array_key_exists( $oname, $this->mOptions ) ) {
343 return $this->mOptions[$oname];
344 } else {
345 return "";
349 function setOption( $oname, $val )
351 $this->loadFromDatabase();
352 $this->mOptions[$oname] = $val;
353 $this->invalidateCache();
356 function getRights()
358 $this->loadFromDatabase();
359 return $this->mRights;
362 function addRight( $rname )
364 $this->loadFromDatabase();
365 array_push( $this->mRights, $rname );
366 $this->invalidateCache();
369 function isSysop()
371 $this->loadFromDatabase();
372 if ( 0 == $this->mId ) { return false; }
374 return in_array( "sysop", $this->mRights );
377 function isDeveloper()
379 $this->loadFromDatabase();
380 if ( 0 == $this->mId ) { return false; }
382 return in_array( "developer", $this->mRights );
385 function isBot()
387 $this->loadFromDatabase();
388 if ( 0 == $this->mId ) { return false; }
390 return in_array( "bot", $this->mRights );
393 function &getSkin()
395 if ( ! isset( $this->mSkin ) ) {
396 $skinNames = Skin::getSkinNames();
397 $s = $this->getOption( "skin" );
398 if ( "" == $s ) { $s = 0; }
400 if ( $s >= count( $skinNames ) ) { $sn = "SkinStandard"; }
401 else $sn = "Skin" . $skinNames[$s];
402 $this->mSkin = new $sn;
404 return $this->mSkin;
407 function isWatched( $title )
409 # Note - $title should be a Title _object_
410 # Pages and their talk pages are considered equivalent for watching;
411 # remember that talk namespaces are numbered as page namespace+1.
412 if( $this->mId ) {
413 $sql = "SELECT 1 FROM watchlist
414 WHERE wl_user={$this->mId} AND
415 wl_namespace = " . ($title->getNamespace() & ~1) . " AND
416 wl_title='" . wfStrencode( $title->getDBkey() ) . "'";
417 $res = wfQuery( $sql, DB_READ );
418 return (wfNumRows( $res ) > 0);
419 } else {
420 return false;
424 function addWatch( $title )
426 if( $this->mId ) {
427 # REPLACE instead of INSERT because occasionally someone
428 # accidentally reloads a watch-add operation.
429 $sql = "REPLACE INTO watchlist (wl_user, wl_namespace,wl_title)
430 VALUES ({$this->mId}," . (($title->getNamespace() | 1) - 1) .
431 ",'" . wfStrencode( $title->getDBkey() ) . "')";
432 wfQuery( $sql, DB_WRITE );
433 $this->invalidateCache();
437 function removeWatch( $title )
439 if( $this->mId ) {
440 $sql = "DELETE FROM watchlist WHERE wl_user={$this->mId} AND
441 wl_namespace=" . (($title->getNamespace() | 1) - 1) .
442 " AND wl_title='" . wfStrencode( $title->getDBkey() ) . "'";
443 wfQuery( $sql, DB_WRITE );
444 $this->invalidateCache();
449 /* private */ function encodeOptions()
451 $a = array();
452 foreach ( $this->mOptions as $oname => $oval ) {
453 array_push( $a, "{$oname}={$oval}" );
455 $s = implode( "\n", $a );
456 return wfStrencode( $s );
459 /* private */ function decodeOptions( $str )
461 $a = explode( "\n", $str );
462 foreach ( $a as $s ) {
463 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
464 $this->mOptions[$m[1]] = $m[2];
469 function setCookies()
471 global $wsUserID, $wsUserName, $wsUserPassword;
472 global $wgCookieExpiration;
473 if ( 0 == $this->mId ) return;
474 $this->loadFromDatabase();
475 $exp = time() + $wgCookieExpiration;
477 $wsUserID = $this->mId;
478 setcookie( "wcUserID", $this->mId, $exp, "/" );
480 $wsUserName = $this->mName;
481 setcookie( "wcUserName", $this->mName, $exp, "/" );
483 $wsUserPassword = $this->mPassword;
484 if ( 1 == $this->getOption( "rememberpassword" ) ) {
485 setcookie( "wcUserPassword", $this->mCookiePassword, $exp, "/" );
486 } else {
487 setcookie( "wcUserPassword", "", time() - 3600 );
491 function logout()
493 global $wsUserID;
494 $this->mId = 0;
496 $wsUserID = 0;
498 setcookie( "wcUserID", "", time() - 3600 );
499 setcookie( "wcUserPassword", "", time() - 3600 );
502 function saveSettings()
504 global $wgMemc, $wgDBname;
506 if ( ! $this->mNewtalk ) {
507 if( $this->mId ) {
508 $sql="DELETE FROM user_newtalk WHERE user_id={$this->mId}";
509 wfQuery ($sql, DB_WRITE, "User::saveSettings");
510 } else {
511 $sql="DELETE FROM user_newtalk WHERE user_ip='{$this->mName}'";
512 wfQuery ($sql, DB_WRITE, "User::saveSettings");
513 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
516 if ( 0 == $this->mId ) { return; }
518 $sql = "UPDATE user SET " .
519 "user_name= '" . wfStrencode( $this->mName ) . "', " .
520 "user_password= '" . wfStrencode( $this->mPassword ) . "', " .
521 "user_newpassword= '" . wfStrencode( $this->mNewpassword ) . "', " .
522 "user_email= '" . wfStrencode( $this->mEmail ) . "', " .
523 "user_options= '" . $this->encodeOptions() . "', " .
524 "user_rights= '" . wfStrencode( implode( ",", $this->mRights ) ) . "', " .
525 "user_touched= '" . wfStrencode( $this->mTouched ) .
526 "' WHERE user_id={$this->mId}";
527 wfQuery( $sql, DB_WRITE, "User::saveSettings" );
528 #$wgMemc->replace( "$wgDBname:user:id:$this->mId", $this );
529 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
532 # Checks if a user with the given name exists
534 function idForName()
536 $gotid = 0;
537 $s = trim( $this->mName );
538 if ( 0 == strcmp( "", $s ) ) return 0;
540 $sql = "SELECT user_id FROM user WHERE user_name='" .
541 wfStrencode( $s ) . "'";
542 $res = wfQuery( $sql, DB_READ, "User::idForName" );
543 if ( 0 == wfNumRows( $res ) ) { return 0; }
545 $s = wfFetchObject( $res );
546 if ( "" == $s ) return 0;
548 $gotid = $s->user_id;
549 wfFreeResult( $res );
550 return $gotid;
553 function addToDatabase()
555 $sql = "INSERT INTO user (user_name,user_password,user_newpassword," .
556 "user_email, user_rights, user_options) " .
557 " VALUES ('" . wfStrencode( $this->mName ) . "', '" .
558 wfStrencode( $this->mPassword ) . "', '" .
559 wfStrencode( $this->mNewpassword ) . "', '" .
560 wfStrencode( $this->mEmail ) . "', '" .
561 wfStrencode( implode( ",", $this->mRights ) ) . "', '" .
562 $this->encodeOptions() . "')";
563 wfQuery( $sql, DB_WRITE, "User::addToDatabase" );
564 $this->mId = $this->idForName();
567 function spreadBlock()
569 # If the (non-anonymous) user is blocked, this function will block any IP address
570 # that they successfully log on from.
571 $fname = "User::spreadBlock";
573 wfDebug( "User:spreadBlock()\n" );
574 if ( $this->mId == 0 ) {
575 return;
578 $userblock = Block::newFromDB( "", $this->mId );
579 if ( !$userblock->isValid() ) {
580 return;
583 # Check if this IP address is already blocked
584 $addr = getenv( "REMOTE_ADDR" );
585 $ipblock = Block::newFromDB( $addr );
586 if ( $ipblock->isValid() ) {
587 # Just update the timestamp
588 $ipblock->updateTimestamp();
589 return;
592 # Make a new block object with the desired properties
593 wfDebug( "Autoblocking {$this->mUserName}@{$addr}\n" );
594 $ipblock->mAddress = $addr;
595 $ipblock->mUser = 0;
596 $ipblock->mBy = $userblock->mBy;
597 $ipblock->mReason = str_replace( "$1", $this->getName(), wfMsg( "autoblocker" ) );
598 $ipblock->mReason = str_replace( "$2", $userblock->mReason, $ipblock->mReason );
599 $ipblock->mTimestamp = wfTimestampNow();
600 $ipblock->mAuto = 1;
602 # Insert it
603 $ipblock->insert();
608 function isAllowedToCreateAccount()
610 global $wgWhitelistAccount;
611 $allowed = false;
613 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
614 foreach ($wgWhitelistAccount as $right => $ok) {
615 $userHasRight = (!strcmp($right, "user") || in_array($right, $this->getRights()));
616 $allowed |= ($ok && $userHasRight);
618 return $allowed;