11 require_once( 'WatchedItem.php' );
21 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
22 var $mRights, $mOptions;
23 var $mDataLoaded, $mNewpassword;
25 var $mBlockedby, $mBlockreason;
32 /** Construct using User:loadDefaults() */
34 $this->loadDefaults();
38 * Static factory method
40 * @param string $name Username, validated by Title:newFromText()
42 function newFromName( $name ) {
45 # Clean up name according to title rules
47 $t = Title
::newFromText( $name );
48 $u->setName( $t->getText() );
53 * Get username given an id.
54 * @param integer $id Database user id
55 * @return string Nickname of a user
58 function whoIs( $id ) {
59 $dbr =& wfGetDB( DB_SLAVE
);
60 return $dbr->getField( 'user', 'user_name', array( 'user_id' => $id ) );
64 * Get real username given an id.
65 * @param integer $id Database user id
66 * @return string Realname of a user
69 function whoIsReal( $id ) {
70 $dbr =& wfGetDB( DB_SLAVE
);
71 return $dbr->getField( 'user', 'user_real_name', array( 'user_id' => $id ) );
75 * Get database id given a user name
76 * @param string $name Nickname of a user
77 * @return integer|null Database user id (null: if non existent
80 function idFromName( $name ) {
81 $fname = "User::idFromName";
83 $nt = Title
::newFromText( $name );
84 if( is_null( $nt ) ) {
88 $dbr =& wfGetDB( DB_SLAVE
);
89 $s = $dbr->getArray( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
99 * does the string match an anonymous user IP address?
100 * @param string $name Nickname of a user
103 function isIP( $name ) {
104 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
108 * probably return a random password
109 * @return string probably a random password
111 * @todo Check what is doing really [AV]
113 function randomPassword() {
114 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
115 $l = strlen( $pwchars ) - 1;
117 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
118 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
119 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
120 $pwchars{mt_rand( 0, $l )};
125 * Set properties to default
126 * Used at construction.
128 function loadDefaults() {
129 global $wgLang, $wgIP;
130 global $wgNamespacesToBeSearchedDefault;
132 $this->mId
= $this->mNewtalk
= 0;
133 $this->mName
= $wgIP;
134 $this->mRealName
= $this->mEmail
= '';
135 $this->mPassword
= $this->mNewpassword
= '';
136 $this->mRights
= array();
137 $defOpt = $wgLang->getDefaultUserOptions() ;
138 foreach ( $defOpt as $oname => $val ) {
139 $this->mOptions
[$oname] = $val;
141 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
142 $this->mOptions
['searchNs'.$nsnum] = $val;
144 unset( $this->mSkin
);
145 $this->mDataLoaded
= false;
146 $this->mBlockedby
= -1; # Unset
147 $this->mTouched
= '0'; # Allow any pages to be cached
148 $this->cookiePassword
= '';
149 $this->mHash
= false;
153 * Get blocking information
156 function getBlockedStatus() {
157 global $wgIP, $wgBlockCache, $wgProxyList;
159 if ( -1 != $this->mBlockedby
) { return; }
161 $this->mBlockedby
= 0;
165 $block = new Block();
166 if ( $block->load( $wgIP , $this->mId
) ) {
167 $this->mBlockedby
= $block->mBy
;
168 $this->mBlockreason
= $block->mReason
;
173 if ( !$this->mBlockedby
) {
174 $block = $wgBlockCache->get( $wgIP );
175 if ( $block !== false ) {
176 $this->mBlockedby
= $block->mBy
;
177 $this->mBlockreason
= $block->mReason
;
182 if ( !$this->mBlockedby
) {
183 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
184 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
185 $this->mBlockedby
= "Proxy blocker";
191 * Check if user is blocked
192 * @return bool True if blocked, false otherwise
194 function isBlocked() {
195 $this->getBlockedStatus();
196 if ( 0 === $this->mBlockedby
) { return false; }
201 * Get name of blocker
202 * @return string name of blocker
204 function blockedBy() {
205 $this->getBlockedStatus();
206 return $this->mBlockedby
;
210 * Get blocking reason
211 * @return string Blocking reason
213 function blockedFor() {
214 $this->getBlockedStatus();
215 return $this->mBlockreason
;
219 * Initialise php session
221 function SetupSession() {
222 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
223 if( $wgSessionsInMemcached ) {
224 require_once( 'MemcachedSessions.php' );
225 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
226 # If it's left on 'user' or another setting from another
227 # application, it will end up failing. Try to recover.
228 ini_set ( 'session.save_handler', 'files' );
230 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
231 session_cache_limiter( 'private, must-revalidate' );
236 * Read datas from session
239 function loadFromSession() {
240 global $wgMemc, $wgDBname;
242 if ( isset( $_SESSION['wsUserID'] ) ) {
243 if ( 0 != $_SESSION['wsUserID'] ) {
244 $sId = $_SESSION['wsUserID'];
248 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
249 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
250 $_SESSION['wsUserID'] = $sId;
254 if ( isset( $_SESSION['wsUserName'] ) ) {
255 $sName = $_SESSION['wsUserName'];
256 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
257 $sName = $_COOKIE["{$wgDBname}UserName"];
258 $_SESSION['wsUserName'] = $sName;
263 $passwordCorrect = FALSE;
264 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
265 if($makenew = !$user) {
266 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
269 $user->loadFromDatabase();
271 wfDebug( "User::loadFromSession() got from cache!\n" );
274 if ( isset( $_SESSION['wsUserPassword'] ) ) {
275 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
276 } else if ( isset( $_COOKIE["{$wgDBname}Password"] ) ) {
277 $user->mCookiePassword
= $_COOKIE["{$wgDBname}Password"];
278 $_SESSION['wsUserPassword'] = $user->addSalt( $user->mCookiePassword
);
279 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
281 return new User(); # Can't log in from session
284 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
286 if($wgMemc->set( $key, $user ))
287 wfDebug( "User::loadFromSession() successfully saved user\n" );
289 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
291 $user->spreadBlock();
294 return new User(); # Can't log in from session
298 * Load a user from the database
300 function loadFromDatabase() {
301 global $wgCommandLineMode;
302 $fname = "User::loadFromDatabase";
303 if ( $this->mDataLoaded ||
$wgCommandLineMode ) {
308 $this->mId
= IntVal( $this->mId
);
310 # check in separate table if there are changes to the talk page
311 $this->mNewtalk
=0; # reset talk page status
312 $dbr =& wfGetDB( DB_SLAVE
);
314 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId
), $fname );
316 if ( $dbr->numRows($res)>0 ) {
319 $dbr->freeResult( $res );
321 global $wgDBname, $wgMemc;
322 $key = "$wgDBname:newtalk:ip:{$this->mName}";
323 $newtalk = $wgMemc->get( $key );
324 if( ! is_integer( $newtalk ) ){
325 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName
), $fname );
327 $this->mNewtalk
= $dbr->numRows( $res ) > 0 ?
1 : 0;
328 $dbr->freeResult( $res );
330 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
332 $this->mNewtalk
= $newtalk ?
1 : 0;
336 $this->mDataLoaded
= true;
338 } # the following stuff is for non-anonymous users only
340 $s = $dbr->getArray( 'user', array( 'user_name','user_password','user_newpassword','user_email',
341 'user_real_name','user_options','user_touched' ),
342 array( 'user_id' => $this->mId
), $fname );
344 if ( $s !== false ) {
345 $this->mName
= $s->user_name
;
346 $this->mEmail
= $s->user_email
;
347 $this->mRealName
= $s->user_real_name
;
348 $this->mPassword
= $s->user_password
;
349 $this->mNewpassword
= $s->user_newpassword
;
350 $this->decodeOptions( $s->user_options
);
351 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
352 $this->mRights
= explode( ",", strtolower(
353 $dbr->getField( 'user_rights', 'user_rights', array( 'user_id' => $this->mId
) )
357 $this->mDataLoaded
= true;
360 function getID() { return $this->mId
; }
361 function setID( $v ) {
363 $this->mDataLoaded
= false;
367 $this->loadFromDatabase();
371 function setName( $str ) {
372 $this->loadFromDatabase();
376 function getNewtalk() {
377 $this->loadFromDatabase();
378 return ( 0 != $this->mNewtalk
);
381 function setNewtalk( $val )
383 $this->loadFromDatabase();
384 $this->mNewtalk
= $val;
385 $this->invalidateCache();
388 function invalidateCache() {
389 $this->loadFromDatabase();
390 $this->mTouched
= wfTimestampNow();
391 # Don't forget to save the options after this or
392 # it won't take effect!
395 function validateCache( $timestamp ) {
396 $this->loadFromDatabase();
397 return ($timestamp >= $this->mTouched
);
402 * Will only be salted if $wgPasswordSalt is true
403 * @param string Password.
404 * @return string Salted password or clear password.
406 function addSalt( $p ) {
407 global $wgPasswordSalt;
409 return md5( "{$this->mId}-{$p}" );
415 * Encrypt a password.
416 * It can eventuall salt a password @see User::addSalt()
417 * @param string $p clear Password.
418 * @param string Encrypted password.
420 function encryptPassword( $p ) {
421 return $this->addSalt( md5( $p ) );
424 function setPassword( $str ) {
425 $this->loadFromDatabase();
426 $this->setCookiePassword( $str );
427 $this->mPassword
= $this->encryptPassword( $str );
428 $this->mNewpassword
= '';
431 function setCookiePassword( $str ) {
432 $this->loadFromDatabase();
433 $this->mCookiePassword
= md5( $str );
436 function setNewpassword( $str ) {
437 $this->loadFromDatabase();
438 $this->mNewpassword
= $this->encryptPassword( $str );
441 function getEmail() {
442 $this->loadFromDatabase();
443 return $this->mEmail
;
446 function setEmail( $str ) {
447 $this->loadFromDatabase();
448 $this->mEmail
= $str;
451 function getRealName() {
452 $this->loadFromDatabase();
453 return $this->mRealName
;
456 function setRealName( $str ) {
457 $this->loadFromDatabase();
458 $this->mRealName
= $str;
461 function getOption( $oname ) {
462 $this->loadFromDatabase();
463 if ( array_key_exists( $oname, $this->mOptions
) ) {
464 return $this->mOptions
[$oname];
470 function setOption( $oname, $val ) {
471 $this->loadFromDatabase();
472 if ( $oname == 'skin' ) {
473 # Clear cached skin, so the new one displays immediately in Special:Preferences
474 unset( $this->mSkin
);
476 $this->mOptions
[$oname] = $val;
477 $this->invalidateCache();
480 function getRights() {
481 $this->loadFromDatabase();
482 return $this->mRights
;
485 function addRight( $rname ) {
486 $this->loadFromDatabase();
487 array_push( $this->mRights
, $rname );
488 $this->invalidateCache();
492 $this->loadFromDatabase();
493 if ( 0 == $this->mId
) { return false; }
495 return in_array( 'sysop', $this->mRights
);
498 function isDeveloper() {
499 $this->loadFromDatabase();
500 if ( 0 == $this->mId
) { return false; }
502 return in_array( 'developer', $this->mRights
);
505 function isBureaucrat() {
506 $this->loadFromDatabase();
507 if ( 0 == $this->mId
) { return false; }
509 return in_array( 'bureaucrat', $this->mRights
);
513 * Whether the user is a bot
516 $this->loadFromDatabase();
518 # Why was this here? I need a UID=0 conversion script [TS]
519 # if ( 0 == $this->mId ) { return false; }
521 return in_array( 'bot', $this->mRights
);
525 * Load a skin if it doesn't exist or return it
526 * @todo FIXME : need to check the old failback system [AV]
528 function &getSkin() {
529 global $IP, $wgUsePHPTal;
530 if ( ! isset( $this->mSkin
) ) {
531 # get all skin names available
532 $skinNames = Skin
::getSkinNames();
534 $userSkin = $this->getOption( 'skin' );
535 if ( $userSkin == '' ) { $userSkin = 'standard'; }
537 if ( !isset( $skinNames[$userSkin] ) ) {
538 # in case the user skin could not be found find a replacement
543 # if phptal is enabled we should have monobook skin that
544 # superseed the good old SkinStandard.
545 if ( isset( $skinNames['monobook'] ) ) {
546 $fallback[0] = 'MonoBook';
549 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
550 $sn = $fallback[$userSkin];
555 # The user skin is available
556 $sn = $skinNames[$userSkin];
559 # Grab the skin class and initialise it. Each skin checks for PHPTal
560 # and will not load if it's not enabled.
561 require_once( $IP.'/skins/'.$sn.'.php' );
563 # Check if we got if not failback to default skin
565 if(!class_exists($sn)) {
566 #FIXME : should we print an error message instead of loading
568 $sn = 'SkinStandard';
569 require_once( $IP.'/skins/Standard.php' );
571 $this->mSkin
= new $sn;
577 * @param string $title Article title to look at
581 * Check watched status of an article
582 * @return bool True if article is watched
584 function isWatched( $title ) {
585 $wl = WatchedItem
::fromUserTitle( $this, $title );
586 return $wl->isWatched();
592 function addWatch( $title ) {
593 $wl = WatchedItem
::fromUserTitle( $this, $title );
595 $this->invalidateCache();
599 * Stop watching an article
601 function removeWatch( $title ) {
602 $wl = WatchedItem
::fromUserTitle( $this, $title );
604 $this->invalidateCache();
610 * @return string Encoding options
612 function encodeOptions() {
614 foreach ( $this->mOptions
as $oname => $oval ) {
615 array_push( $a, $oname.'='.$oval );
617 $s = implode( "\n", $a );
624 function decodeOptions( $str ) {
625 $a = explode( "\n", $str );
626 foreach ( $a as $s ) {
627 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
628 $this->mOptions
[$m[1]] = $m[2];
633 function setCookies() {
634 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
635 if ( 0 == $this->mId
) return;
636 $this->loadFromDatabase();
637 $exp = time() +
$wgCookieExpiration;
639 $_SESSION['wsUserID'] = $this->mId
;
640 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
642 $_SESSION['wsUserName'] = $this->mName
;
643 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
645 $_SESSION['wsUserPassword'] = $this->mPassword
;
646 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
647 setcookie( $wgDBname.'Password', $this->mCookiePassword
, $exp, $wgCookiePath, $wgCookieDomain );
649 setcookie( $wgDBname.'Password', '', time() - 3600 );
655 * It will clean the session cookie
658 global $wgCookiePath, $wgCookieDomain, $wgDBname;
661 $_SESSION['wsUserID'] = 0;
663 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
664 setcookie( $wgDBname.'Password', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
668 * Save object settings into database
670 function saveSettings() {
671 global $wgMemc, $wgDBname;
672 $fname = 'User::saveSettings';
674 $dbw =& wfGetDB( DB_MASTER
);
675 if ( ! $this->mNewtalk
) {
676 # Delete user_newtalk row
678 $dbw->delete( 'user_newtalk', array( 'user_id' => $this->mId
), $fname );
680 $dbw->delete( 'user_newtalk', array( 'user_ip' => $this->mName
), $fname );
681 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
684 if ( 0 == $this->mId
) { return; }
686 $dbw->update( 'user',
688 'user_name' => $this->mName
,
689 'user_password' => $this->mPassword
,
690 'user_newpassword' => $this->mNewpassword
,
691 'user_real_name' => $this->mRealName
,
692 'user_email' => $this->mEmail
,
693 'user_options' => $this->encodeOptions(),
694 'user_touched' => $dbw->timestamp($this->mTouched
)
695 ), array( /* WHERE */
696 'user_id' => $this->mId
699 $dbw->set( 'user_rights', 'user_rights', implode( ",", $this->mRights
),
700 'user_id='. $this->mId
, $fname );
701 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
705 * Checks if a user with the given name exists, returns the ID
707 function idForName() {
708 $fname = 'User::idForName';
711 $s = trim( $this->mName
);
712 if ( 0 == strcmp( '', $s ) ) return 0;
714 $dbr =& wfGetDB( DB_SLAVE
);
715 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
716 if ( $id === false ) {
723 * Add user object to the database
725 function addToDatabase() {
726 $fname = 'User::addToDatabase';
727 $dbw =& wfGetDB( DB_MASTER
);
728 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
729 $dbw->insert( 'user',
731 'user_id' => $seqVal,
732 'user_name' => $this->mName
,
733 'user_password' => $this->mPassword
,
734 'user_newpassword' => $this->mNewpassword
,
735 'user_email' => $this->mEmail
,
736 'user_real_name' => $this->mRealName
,
737 'user_options' => $this->encodeOptions()
740 $this->mId
= $dbw->insertId();
741 $dbw->insert( 'user_rights',
743 'user_id' => $this->mId
,
744 'user_rights' => implode( ',', $this->mRights
)
750 function spreadBlock() {
752 # If the (non-anonymous) user is blocked, this function will block any IP address
753 # that they successfully log on from.
754 $fname = 'User::spreadBlock';
756 wfDebug( "User:spreadBlock()\n" );
757 if ( $this->mId
== 0 ) {
761 $userblock = Block
::newFromDB( '', $this->mId
);
762 if ( !$userblock->isValid() ) {
766 # Check if this IP address is already blocked
767 $ipblock = Block
::newFromDB( $wgIP );
768 if ( $ipblock->isValid() ) {
769 # Just update the timestamp
770 $ipblock->updateTimestamp();
774 # Make a new block object with the desired properties
775 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
776 $ipblock->mAddress
= $wgIP;
778 $ipblock->mBy
= $userblock->mBy
;
779 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
780 $ipblock->mTimestamp
= wfTimestampNow();
782 # If the user is already blocked with an expiry date, we don't
783 # want to pile on top of that!
784 if($userblock->mExpiry
) {
785 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
787 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
795 function getPageRenderingHash() {
800 // stubthreshold is only included below for completeness,
801 // it will always be 0 when this function is called by parsercache.
803 $confstr = $this->getOption( 'math' );
804 $confstr .= '!' . $this->getOption( 'highlightbroken' );
805 $confstr .= '!' . $this->getOption( 'stubthreshold' );
806 $confstr .= '!' . $this->getOption( 'editsection' );
807 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
808 $confstr .= '!' . $this->getOption( 'showtoc' );
809 $confstr .= '!' . $this->getOption( 'date' );
810 $confstr .= '!' . $this->getOption( 'numberheadings' );
812 $this->mHash
= $confstr;
816 function isAllowedToCreateAccount() {
817 global $wgWhitelistAccount;
820 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
821 foreach ($wgWhitelistAccount as $right => $ok) {
822 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
823 $allowed |
= ($ok && $userHasRight);
829 * Set mDataLoaded, return previous value
830 * Use this to prevent DB access in command-line scripts or similar situations
832 function setLoaded( $loaded ) {
833 return wfSetVar( $this->mDataLoaded
, $loaded );
836 function getUserPage() {
837 return Title
::makeTitle( NS_USER
, $this->mName
);
843 function getMaxID() {
844 $dbr =& wfGetDB( DB_SLAVE
);
845 return $dbr->selectField( 'user', 'max(user_id)', false );
849 * Determine whether the user is a newbie. Newbies are either
850 * anonymous IPs, or the 1% most recently created accounts.
851 * Bots and sysops are excluded.
852 * @return bool True if it is a newbie.
854 function isNewbie() {
855 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
859 * Check to see if the given clear-text password is one of the accepted passwords
860 * @param string $password User password.
861 * @return bool True if the given password is correct otherwise False.
863 function checkPassword( $password ) {
864 $this->loadFromDatabase();
865 $ep = $this->encryptPassword( $password );
866 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
868 } elseif ( 0 == strcmp( $ep, $this->mNewpassword
) ) {
870 } elseif ( function_exists( 'iconv' ) ) {
871 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
872 # Check for this with iconv
873 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
874 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {