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 );
51 $u->setName( $t->getText() );
57 * Get username given an id.
58 * @param integer $id Database user id
59 * @return string Nickname of a user
62 function whoIs( $id ) {
63 $dbr =& wfGetDB( DB_SLAVE
);
64 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
68 * Get real username given an id.
69 * @param integer $id Database user id
70 * @return string Realname of a user
73 function whoIsReal( $id ) {
74 $dbr =& wfGetDB( DB_SLAVE
);
75 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
79 * Get database id given a user name
80 * @param string $name Nickname of a user
81 * @return integer|null Database user id (null: if non existent
84 function idFromName( $name ) {
85 $fname = "User::idFromName";
87 $nt = Title
::newFromText( $name );
88 if( is_null( $nt ) ) {
92 $dbr =& wfGetDB( DB_SLAVE
);
93 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
103 * does the string match an anonymous user IP address?
104 * @param string $name Nickname of a user
107 function isIP( $name ) {
108 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
112 * probably return a random password
113 * @return string probably a random password
115 * @todo Check what is doing really [AV]
117 function randomPassword() {
118 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
119 $l = strlen( $pwchars ) - 1;
121 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
122 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
123 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
124 $pwchars{mt_rand( 0, $l )};
129 * Set properties to default
130 * Used at construction. It will load per language default settings only
131 * if we have an available language object.
133 function loadDefaults() {
134 global $wgLang, $wgIP;
135 global $wgNamespacesToBeSearchedDefault;
137 $this->mId
= $this->mNewtalk
= 0;
138 $this->mName
= $wgIP;
139 $this->mRealName
= $this->mEmail
= '';
140 $this->mPassword
= $this->mNewpassword
= '';
141 $this->mRights
= array();
142 // Getting user defaults only if we have an available language
143 if(isset($wgLang)) { $this->loadDefaultFromLanguage(); }
145 foreach ($wgNamespacesToBeSearchedDefault as $nsnum => $val) {
146 $this->mOptions
['searchNs'.$nsnum] = $val;
148 unset( $this->mSkin
);
149 $this->mDataLoaded
= false;
150 $this->mBlockedby
= -1; # Unset
151 $this->mTouched
= '0'; # Allow any pages to be cached
152 $this->cookiePassword
= '';
153 $this->mHash
= false;
157 * Used to load user options from a language.
158 * This is not in loadDefault() cause we sometime create user before having
161 function loadDefaultFromLanguage(){
163 $defOpt = $wgLang->getDefaultUserOptions() ;
164 foreach ( $defOpt as $oname => $val ) {
165 $this->mOptions
[$oname] = $val;
170 * Get blocking information
173 function getBlockedStatus() {
174 global $wgIP, $wgBlockCache, $wgProxyList;
176 if ( -1 != $this->mBlockedby
) { return; }
178 $this->mBlockedby
= 0;
182 $block = new Block();
183 if ( $block->load( $wgIP , $this->mId
) ) {
184 $this->mBlockedby
= $block->mBy
;
185 $this->mBlockreason
= $block->mReason
;
190 if ( !$this->mBlockedby
) {
191 $block = $wgBlockCache->get( $wgIP );
192 if ( $block !== false ) {
193 $this->mBlockedby
= $block->mBy
;
194 $this->mBlockreason
= $block->mReason
;
199 if ( !$this->mBlockedby
) {
200 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
201 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
202 $this->mBlockedby
= "Proxy blocker";
208 * Check if user is blocked
209 * @return bool True if blocked, false otherwise
211 function isBlocked() {
212 $this->getBlockedStatus();
213 if ( 0 === $this->mBlockedby
) { return false; }
218 * Get name of blocker
219 * @return string name of blocker
221 function blockedBy() {
222 $this->getBlockedStatus();
223 return $this->mBlockedby
;
227 * Get blocking reason
228 * @return string Blocking reason
230 function blockedFor() {
231 $this->getBlockedStatus();
232 return $this->mBlockreason
;
236 * Initialise php session
238 function SetupSession() {
239 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
240 if( $wgSessionsInMemcached ) {
241 require_once( 'MemcachedSessions.php' );
242 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
243 # If it's left on 'user' or another setting from another
244 # application, it will end up failing. Try to recover.
245 ini_set ( 'session.save_handler', 'files' );
247 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
248 session_cache_limiter( 'private, must-revalidate' );
253 * Read datas from session
256 function loadFromSession() {
257 global $wgMemc, $wgDBname;
259 if ( isset( $_SESSION['wsUserID'] ) ) {
260 if ( 0 != $_SESSION['wsUserID'] ) {
261 $sId = $_SESSION['wsUserID'];
265 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
266 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
267 $_SESSION['wsUserID'] = $sId;
271 if ( isset( $_SESSION['wsUserName'] ) ) {
272 $sName = $_SESSION['wsUserName'];
273 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
274 $sName = $_COOKIE["{$wgDBname}UserName"];
275 $_SESSION['wsUserName'] = $sName;
280 $passwordCorrect = FALSE;
281 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
282 if($makenew = !$user) {
283 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
286 $user->loadFromDatabase();
288 wfDebug( "User::loadFromSession() got from cache!\n" );
291 if ( isset( $_SESSION['wsUserPassword'] ) ) {
292 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
293 } else if ( isset( $_COOKIE["{$wgDBname}Password"] ) ) {
294 $user->mCookiePassword
= $_COOKIE["{$wgDBname}Password"];
295 $_SESSION['wsUserPassword'] = $user->addSalt( $user->mCookiePassword
);
296 $passwordCorrect = $_SESSION['wsUserPassword'] == $user->mPassword
;
298 return new User(); # Can't log in from session
301 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
303 if($wgMemc->set( $key, $user ))
304 wfDebug( "User::loadFromSession() successfully saved user\n" );
306 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
308 $user->spreadBlock();
311 return new User(); # Can't log in from session
315 * Load a user from the database
317 function loadFromDatabase() {
318 global $wgCommandLineMode;
319 $fname = "User::loadFromDatabase";
320 if ( $this->mDataLoaded ||
$wgCommandLineMode ) {
325 $this->mId
= IntVal( $this->mId
);
327 # check in separate table if there are changes to the talk page
328 $this->mNewtalk
=0; # reset talk page status
329 $dbr =& wfGetDB( DB_SLAVE
);
331 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId
), $fname );
333 if ( $dbr->numRows($res)>0 ) {
336 $dbr->freeResult( $res );
338 global $wgDBname, $wgMemc;
339 $key = "$wgDBname:newtalk:ip:{$this->mName}";
340 $newtalk = $wgMemc->get( $key );
341 if( ! is_integer( $newtalk ) ){
342 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName
), $fname );
344 $this->mNewtalk
= $dbr->numRows( $res ) > 0 ?
1 : 0;
345 $dbr->freeResult( $res );
347 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
349 $this->mNewtalk
= $newtalk ?
1 : 0;
353 $this->mDataLoaded
= true;
355 } # the following stuff is for non-anonymous users only
357 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
358 'user_real_name','user_options','user_touched' ),
359 array( 'user_id' => $this->mId
), $fname );
361 if ( $s !== false ) {
362 $this->mName
= $s->user_name
;
363 $this->mEmail
= $s->user_email
;
364 $this->mRealName
= $s->user_real_name
;
365 $this->mPassword
= $s->user_password
;
366 $this->mNewpassword
= $s->user_newpassword
;
367 $this->decodeOptions( $s->user_options
);
368 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
369 $this->mRights
= explode( ",", strtolower(
370 $dbr->selectField( 'user_rights', 'user_rights', array( 'user_id' => $this->mId
) )
374 $this->mDataLoaded
= true;
377 function getID() { return $this->mId
; }
378 function setID( $v ) {
380 $this->mDataLoaded
= false;
384 $this->loadFromDatabase();
388 function setName( $str ) {
389 $this->loadFromDatabase();
393 function getNewtalk() {
394 $this->loadFromDatabase();
395 return ( 0 != $this->mNewtalk
);
398 function setNewtalk( $val ) {
399 $this->loadFromDatabase();
400 $this->mNewtalk
= $val;
401 $this->invalidateCache();
404 function invalidateCache() {
405 $this->loadFromDatabase();
406 $this->mTouched
= wfTimestampNow();
407 # Don't forget to save the options after this or
408 # it won't take effect!
411 function validateCache( $timestamp ) {
412 $this->loadFromDatabase();
413 return ($timestamp >= $this->mTouched
);
418 * Will only be salted if $wgPasswordSalt is true
419 * @param string Password.
420 * @return string Salted password or clear password.
422 function addSalt( $p ) {
423 global $wgPasswordSalt;
425 return md5( "{$this->mId}-{$p}" );
431 * Encrypt a password.
432 * It can eventuall salt a password @see User::addSalt()
433 * @param string $p clear Password.
434 * @param string Encrypted password.
436 function encryptPassword( $p ) {
437 return $this->addSalt( md5( $p ) );
440 function setPassword( $str ) {
441 $this->loadFromDatabase();
442 $this->setCookiePassword( $str );
443 $this->mPassword
= $this->encryptPassword( $str );
444 $this->mNewpassword
= '';
447 function setCookiePassword( $str ) {
448 $this->loadFromDatabase();
449 $this->mCookiePassword
= md5( $str );
452 function setNewpassword( $str ) {
453 $this->loadFromDatabase();
454 $this->mNewpassword
= $this->encryptPassword( $str );
457 function getEmail() {
458 $this->loadFromDatabase();
459 return $this->mEmail
;
462 function setEmail( $str ) {
463 $this->loadFromDatabase();
464 $this->mEmail
= $str;
467 function getRealName() {
468 $this->loadFromDatabase();
469 return $this->mRealName
;
472 function setRealName( $str ) {
473 $this->loadFromDatabase();
474 $this->mRealName
= $str;
477 function getOption( $oname ) {
478 $this->loadFromDatabase();
479 if ( array_key_exists( $oname, $this->mOptions
) ) {
480 return $this->mOptions
[$oname];
486 function setOption( $oname, $val ) {
487 $this->loadFromDatabase();
488 if ( $oname == 'skin' ) {
489 # Clear cached skin, so the new one displays immediately in Special:Preferences
490 unset( $this->mSkin
);
492 $this->mOptions
[$oname] = $val;
493 $this->invalidateCache();
496 function getRights() {
497 $this->loadFromDatabase();
498 return $this->mRights
;
501 function addRight( $rname ) {
502 $this->loadFromDatabase();
503 array_push( $this->mRights
, $rname );
504 $this->invalidateCache();
508 $this->loadFromDatabase();
509 if ( 0 == $this->mId
) { return false; }
511 return in_array( 'sysop', $this->mRights
);
514 function isDeveloper() {
515 $this->loadFromDatabase();
516 if ( 0 == $this->mId
) { return false; }
518 return in_array( 'developer', $this->mRights
);
521 function isBureaucrat() {
522 $this->loadFromDatabase();
523 if ( 0 == $this->mId
) { return false; }
525 return in_array( 'bureaucrat', $this->mRights
);
529 * Whether the user is a bot
532 $this->loadFromDatabase();
534 # Why was this here? I need a UID=0 conversion script [TS]
535 # if ( 0 == $this->mId ) { return false; }
537 return in_array( 'bot', $this->mRights
);
541 * Load a skin if it doesn't exist or return it
542 * @todo FIXME : need to check the old failback system [AV]
544 function &getSkin() {
545 global $IP, $wgUsePHPTal;
546 if ( ! isset( $this->mSkin
) ) {
547 # get all skin names available
548 $skinNames = Skin
::getSkinNames();
550 $userSkin = $this->getOption( 'skin' );
551 if ( $userSkin == '' ) { $userSkin = 'standard'; }
553 if ( !isset( $skinNames[$userSkin] ) ) {
554 # in case the user skin could not be found find a replacement
559 # if phptal is enabled we should have monobook skin that
560 # superseed the good old SkinStandard.
561 if ( isset( $skinNames['monobook'] ) ) {
562 $fallback[0] = 'MonoBook';
565 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
566 $sn = $fallback[$userSkin];
571 # The user skin is available
572 $sn = $skinNames[$userSkin];
575 # Grab the skin class and initialise it. Each skin checks for PHPTal
576 # and will not load if it's not enabled.
577 require_once( $IP.'/skins/'.$sn.'.php' );
579 # Check if we got if not failback to default skin
581 if(!class_exists($sn)) {
582 #FIXME : should we print an error message instead of loading
584 $sn = 'SkinStandard';
585 require_once( $IP.'/skins/Standard.php' );
587 $this->mSkin
= new $sn;
593 * @param string $title Article title to look at
597 * Check watched status of an article
598 * @return bool True if article is watched
600 function isWatched( $title ) {
601 $wl = WatchedItem
::fromUserTitle( $this, $title );
602 return $wl->isWatched();
608 function addWatch( $title ) {
609 $wl = WatchedItem
::fromUserTitle( $this, $title );
611 $this->invalidateCache();
615 * Stop watching an article
617 function removeWatch( $title ) {
618 $wl = WatchedItem
::fromUserTitle( $this, $title );
620 $this->invalidateCache();
626 * @return string Encoding options
628 function encodeOptions() {
630 foreach ( $this->mOptions
as $oname => $oval ) {
631 array_push( $a, $oname.'='.$oval );
633 $s = implode( "\n", $a );
640 function decodeOptions( $str ) {
641 $a = explode( "\n", $str );
642 foreach ( $a as $s ) {
643 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
644 $this->mOptions
[$m[1]] = $m[2];
649 function setCookies() {
650 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
651 if ( 0 == $this->mId
) return;
652 $this->loadFromDatabase();
653 $exp = time() +
$wgCookieExpiration;
655 $_SESSION['wsUserID'] = $this->mId
;
656 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
658 $_SESSION['wsUserName'] = $this->mName
;
659 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
661 $_SESSION['wsUserPassword'] = $this->mPassword
;
662 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
663 setcookie( $wgDBname.'Password', $this->mCookiePassword
, $exp, $wgCookiePath, $wgCookieDomain );
665 setcookie( $wgDBname.'Password', '', time() - 3600 );
671 * It will clean the session cookie
674 global $wgCookiePath, $wgCookieDomain, $wgDBname;
677 $_SESSION['wsUserID'] = 0;
679 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
680 setcookie( $wgDBname.'Password', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
684 * Save object settings into database
686 function saveSettings() {
687 global $wgMemc, $wgDBname;
688 $fname = 'User::saveSettings';
690 $dbw =& wfGetDB( DB_MASTER
);
691 if ( ! $this->mNewtalk
) {
692 # Delete user_newtalk row
694 $dbw->delete( 'user_newtalk', array( 'user_id' => $this->mId
), $fname );
696 $dbw->delete( 'user_newtalk', array( 'user_ip' => $this->mName
), $fname );
697 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
700 if ( 0 == $this->mId
) { return; }
702 $dbw->update( 'user',
704 'user_name' => $this->mName
,
705 'user_password' => $this->mPassword
,
706 'user_newpassword' => $this->mNewpassword
,
707 'user_real_name' => $this->mRealName
,
708 'user_email' => $this->mEmail
,
709 'user_options' => $this->encodeOptions(),
710 'user_touched' => $dbw->timestamp($this->mTouched
)
711 ), array( /* WHERE */
712 'user_id' => $this->mId
715 $dbw->set( 'user_rights', 'user_rights', implode( ",", $this->mRights
),
716 'user_id='. $this->mId
, $fname );
717 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
721 * Checks if a user with the given name exists, returns the ID
723 function idForName() {
724 $fname = 'User::idForName';
727 $s = trim( $this->mName
);
728 if ( 0 == strcmp( '', $s ) ) return 0;
730 $dbr =& wfGetDB( DB_SLAVE
);
731 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
732 if ( $id === false ) {
739 * Add user object to the database
741 function addToDatabase() {
742 $fname = 'User::addToDatabase';
743 $dbw =& wfGetDB( DB_MASTER
);
744 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
745 $dbw->insert( 'user',
747 'user_id' => $seqVal,
748 'user_name' => $this->mName
,
749 'user_password' => $this->mPassword
,
750 'user_newpassword' => $this->mNewpassword
,
751 'user_email' => $this->mEmail
,
752 'user_real_name' => $this->mRealName
,
753 'user_options' => $this->encodeOptions()
756 $this->mId
= $dbw->insertId();
757 $dbw->insert( 'user_rights',
759 'user_id' => $this->mId
,
760 'user_rights' => implode( ',', $this->mRights
)
766 function spreadBlock() {
768 # If the (non-anonymous) user is blocked, this function will block any IP address
769 # that they successfully log on from.
770 $fname = 'User::spreadBlock';
772 wfDebug( "User:spreadBlock()\n" );
773 if ( $this->mId
== 0 ) {
777 $userblock = Block
::newFromDB( '', $this->mId
);
778 if ( !$userblock->isValid() ) {
782 # Check if this IP address is already blocked
783 $ipblock = Block
::newFromDB( $wgIP );
784 if ( $ipblock->isValid() ) {
785 # Just update the timestamp
786 $ipblock->updateTimestamp();
790 # Make a new block object with the desired properties
791 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
792 $ipblock->mAddress
= $wgIP;
794 $ipblock->mBy
= $userblock->mBy
;
795 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
796 $ipblock->mTimestamp
= wfTimestampNow();
798 # If the user is already blocked with an expiry date, we don't
799 # want to pile on top of that!
800 if($userblock->mExpiry
) {
801 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
803 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
811 function getPageRenderingHash() {
816 // stubthreshold is only included below for completeness,
817 // it will always be 0 when this function is called by parsercache.
819 $confstr = $this->getOption( 'math' );
820 $confstr .= '!' . $this->getOption( 'highlightbroken' );
821 $confstr .= '!' . $this->getOption( 'stubthreshold' );
822 $confstr .= '!' . $this->getOption( 'editsection' );
823 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
824 $confstr .= '!' . $this->getOption( 'showtoc' );
825 $confstr .= '!' . $this->getOption( 'date' );
826 $confstr .= '!' . $this->getOption( 'numberheadings' );
828 $this->mHash
= $confstr;
832 function isAllowedToCreateAccount() {
833 global $wgWhitelistAccount;
836 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
837 foreach ($wgWhitelistAccount as $right => $ok) {
838 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
839 $allowed |
= ($ok && $userHasRight);
845 * Set mDataLoaded, return previous value
846 * Use this to prevent DB access in command-line scripts or similar situations
848 function setLoaded( $loaded ) {
849 return wfSetVar( $this->mDataLoaded
, $loaded );
852 function getUserPage() {
853 return Title
::makeTitle( NS_USER
, $this->mName
);
859 function getMaxID() {
860 $dbr =& wfGetDB( DB_SLAVE
);
861 return $dbr->selectField( 'user', 'max(user_id)', false );
865 * Determine whether the user is a newbie. Newbies are either
866 * anonymous IPs, or the 1% most recently created accounts.
867 * Bots and sysops are excluded.
868 * @return bool True if it is a newbie.
870 function isNewbie() {
871 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
875 * Check to see if the given clear-text password is one of the accepted passwords
876 * @param string $password User password.
877 * @return bool True if the given password is correct otherwise False.
879 function checkPassword( $password ) {
880 $this->loadFromDatabase();
881 $ep = $this->encryptPassword( $password );
882 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
884 } elseif ( 0 == strcmp( $ep, $this->mNewpassword
) ) {
886 } elseif ( function_exists( 'iconv' ) ) {
887 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
888 # Check for this with iconv
889 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
890 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {