11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mEmailAuthenticationtimestamp;
27 var $mRights, $mOptions;
28 var $mDataLoaded, $mNewpassword;
30 var $mBlockedby, $mBlockreason;
35 /** Array of group id the user belong to */
39 /** Construct using User:loadDefaults() */
41 $this->loadDefaults();
45 * Static factory method
47 * @param string $name Username, validated by Title:newFromText()
49 function newFromName( $name ) {
52 # Clean up name according to title rules
54 $t = Title
::newFromText( $name );
58 $u->setName( $t->getText() );
59 $u->setId( $u->idFromName( $t->getText() ) );
65 * Get username given an id.
66 * @param integer $id Database user id
67 * @return string Nickname of a user
70 function whoIs( $id ) {
71 $dbr =& wfGetDB( DB_SLAVE
);
72 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
76 * Get real username given an id.
77 * @param integer $id Database user id
78 * @return string Realname of a user
81 function whoIsReal( $id ) {
82 $dbr =& wfGetDB( DB_SLAVE
);
83 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
87 * Get database id given a user name
88 * @param string $name Nickname of a user
89 * @return integer|null Database user id (null: if non existent
92 function idFromName( $name ) {
93 $fname = "User::idFromName";
95 $nt = Title
::newFromText( $name );
96 if( is_null( $nt ) ) {
100 $dbr =& wfGetDB( DB_SLAVE
);
101 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
103 if ( $s === false ) {
111 * does the string match an anonymous user IP address?
112 * @param string $name Nickname of a user
115 function isIP( $name ) {
116 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
120 * does the string match roughly an email address ?
121 * @param string $addr email address
124 function isValidEmailAddr ( $addr ) {
125 return preg_match( '/^([a-z0-9_.-]+([a-z0-9_.-]+)*\@[a-z0-9_-]+([a-z0-9_.-]+)*([a-z.]{2,})+)$/', strtolower($addr));
129 * probably return a random password
130 * @return string probably a random password
132 * @todo Check what is doing really [AV]
134 function randomPassword() {
135 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
136 $l = strlen( $pwchars ) - 1;
138 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
139 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
140 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
141 $pwchars{mt_rand( 0, $l )};
146 * Set properties to default
147 * Used at construction. It will load per language default settings only
148 * if we have an available language object.
150 function loadDefaults() {
153 $fname = 'User::loadDefaults' . $n;
154 wfProfileIn( $fname );
156 global $wgContLang, $wgIP;
157 global $wgNamespacesToBeSearchedDefault;
160 $this->mNewtalk
= -1;
161 $this->mName
= $wgIP;
162 $this->mRealName
= $this->mEmail
= '';
163 $this->mEmailAuthenticationtimestamp
= 0;
164 $this->mPassword
= $this->mNewpassword
= '';
165 $this->mRights
= array();
166 $this->mGroups
= array();
167 // Getting user defaults only if we have an available language
168 if( isset( $wgContLang ) ) {
169 $this->loadDefaultFromLanguage();
172 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
173 $this->mOptions
['searchNs'.$nsnum] = $val;
175 unset( $this->mSkin
);
176 $this->mDataLoaded
= false;
177 $this->mBlockedby
= -1; # Unset
178 $this->mTouched
= '0'; # Allow any pages to be cached
179 $this->setToken(); # Random
180 $this->mHash
= false;
181 wfProfileOut( $fname );
185 * Used to load user options from a language.
186 * This is not in loadDefault() cause we sometime create user before having
189 function loadDefaultFromLanguage(){
190 $this->mOptions
= User
::getDefaultOptions();
194 * Combine the language default options with any site-specific options
195 * and add the default language variants.
201 function getDefaultOptions() {
203 * Site defaults will override the global/language defaults
205 global $wgContLang, $wgDefaultUserOptions;
206 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
209 * default language setting
211 $variant = $wgContLang->getPreferredVariant();
212 $defOpt['variant'] = $variant;
213 $defOpt['language'] = $variant;
219 * Get a given default option value.
226 function getDefaultOption( $opt ) {
227 $defOpts = User
::getDefaultOptions();
228 if( isset( $defOpts[$opt] ) ) {
229 return $defOpts[$opt];
236 * Get blocking information
239 function getBlockedStatus() {
240 global $wgIP, $wgBlockCache, $wgProxyList;
242 if ( -1 != $this->mBlockedby
) { return; }
244 $this->mBlockedby
= 0;
248 $block = new Block();
249 if ( $block->load( $wgIP , $this->mId
) ) {
250 $this->mBlockedby
= $block->mBy
;
251 $this->mBlockreason
= $block->mReason
;
256 if ( !$this->mBlockedby
) {
257 $block = $wgBlockCache->get( $wgIP );
258 if ( $block !== false ) {
259 $this->mBlockedby
= $block->mBy
;
260 $this->mBlockreason
= $block->mReason
;
265 if ( !$this->mBlockedby
) {
266 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
267 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
268 $this->mBlockedby
= "Proxy blocker";
274 * Check if user is blocked
275 * @return bool True if blocked, false otherwise
277 function isBlocked() {
278 $this->getBlockedStatus();
279 if ( 0 === $this->mBlockedby
) { return false; }
284 * Get name of blocker
285 * @return string name of blocker
287 function blockedBy() {
288 $this->getBlockedStatus();
289 return $this->mBlockedby
;
293 * Get blocking reason
294 * @return string Blocking reason
296 function blockedFor() {
297 $this->getBlockedStatus();
298 return $this->mBlockreason
;
302 * Initialise php session
304 function SetupSession() {
305 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
306 if( $wgSessionsInMemcached ) {
307 require_once( 'MemcachedSessions.php' );
308 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
309 # If it's left on 'user' or another setting from another
310 # application, it will end up failing. Try to recover.
311 ini_set ( 'session.save_handler', 'files' );
313 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
314 session_cache_limiter( 'private, must-revalidate' );
319 * Read datas from session
322 function loadFromSession() {
323 global $wgMemc, $wgDBname;
325 if ( isset( $_SESSION['wsUserID'] ) ) {
326 if ( 0 != $_SESSION['wsUserID'] ) {
327 $sId = $_SESSION['wsUserID'];
331 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
332 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
333 $_SESSION['wsUserID'] = $sId;
337 if ( isset( $_SESSION['wsUserName'] ) ) {
338 $sName = $_SESSION['wsUserName'];
339 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
340 $sName = $_COOKIE["{$wgDBname}UserName"];
341 $_SESSION['wsUserName'] = $sName;
346 $passwordCorrect = FALSE;
347 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
348 if($makenew = !$user) {
349 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
352 $user->loadFromDatabase();
354 wfDebug( "User::loadFromSession() got from cache!\n" );
357 if ( isset( $_SESSION['wsToken'] ) ) {
358 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
359 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
360 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
362 return new User(); # Can't log in from session
365 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
367 if($wgMemc->set( $key, $user ))
368 wfDebug( "User::loadFromSession() successfully saved user\n" );
370 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
372 $user->spreadBlock();
375 return new User(); # Can't log in from session
379 * Load a user from the database
381 function loadFromDatabase() {
382 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
383 $fname = "User::loadFromDatabase";
385 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
386 # loading in a command line script, don't assume all command line scripts need it like this
387 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
388 if ( $this->mDataLoaded
) {
393 $this->mId
= IntVal( $this->mId
);
395 /** Anonymous user */
398 $anong = Group
::newFromId($wgAnonGroupId);
400 wfDebugDieBacktrace("Please update your database schema "
401 ."and populate initial group data from "
402 ."maintenance/archives patches");
403 $anong->loadFromDatabase();
404 $this->mRights
= explode(',', $anong->getRights());
405 $this->mDataLoaded
= true;
407 } # the following stuff is for non-anonymous users only
409 $dbr =& wfGetDB( DB_SLAVE
);
410 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
411 'user_emailauthenticationtimestamp',
412 'user_real_name','user_options','user_touched', 'user_token' ),
413 array( 'user_id' => $this->mId
), $fname );
415 if ( $s !== false ) {
416 $this->mName
= $s->user_name
;
417 $this->mEmail
= $s->user_email
;
418 $this->mEmailAuthenticationtimestamp
= wfTimestamp(TS_MW
,$s->user_emailauthenticationtimestamp
);
419 $this->mRealName
= $s->user_real_name
;
420 $this->mPassword
= $s->user_password
;
421 $this->mNewpassword
= $s->user_newpassword
;
422 $this->decodeOptions( $s->user_options
);
423 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
424 $this->mToken
= $s->user_token
;
427 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
429 while($group = $dbr->fetchRow($res)) {
430 $this->mGroups
[] = $group[0];
433 // add the default group for logged in user
434 $this->mGroups
[] = $wgLoggedInGroupId;
436 $this->mRights
= array();
437 // now we merge groups rights to get this user rights
438 foreach($this->mGroups
as $aGroupId) {
439 $g = Group
::newFromId($aGroupId);
440 $g->loadFromDatabase();
441 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
444 // array merge duplicate rights which are part of several groups
445 $this->mRights
= array_unique($this->mRights
);
447 $dbr->freeResult($res);
450 $this->mDataLoaded
= true;
453 function getID() { return $this->mId
; }
454 function setID( $v ) {
456 $this->mDataLoaded
= false;
460 $this->loadFromDatabase();
464 function setName( $str ) {
465 $this->loadFromDatabase();
471 * Return the title dbkey form of the name, for eg user pages.
475 function getTitleKey() {
476 return str_replace( ' ', '_', $this->getName() );
479 function getNewtalk() {
480 $fname = 'User::getNewtalk';
481 $this->loadFromDatabase();
483 # Load the newtalk status if it is unloaded (mNewtalk=-1)
484 if( $this->mNewtalk
== -1 ) {
485 $this->mNewtalk
= 0; # reset talk page status
487 # Check memcached separately for anons, who have no
488 # entire User object stored in there.
490 global $wgDBname, $wgMemc;
491 $key = "$wgDBname:newtalk:ip:{$this->mName}";
492 $newtalk = $wgMemc->get( $key );
493 if( is_integer( $newtalk ) ) {
494 $this->mNewtalk
= $newtalk ?
1 : 0;
495 return (bool)$this->mNewtalk
;
499 $dbr =& wfGetDB( DB_SLAVE
);
500 $res = $dbr->select( 'watchlist',
502 array( 'wl_title' => $this->getTitleKey(),
503 'wl_namespace' => NS_USER_TALK
,
504 'wl_user' => $this->mId
,
505 'wl_notificationtimestamp != 0' ),
506 'User::getNewtalk' );
507 if( $dbr->numRows($res) > 0 ) {
510 $dbr->freeResult( $res );
513 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
517 return ( 0 != $this->mNewtalk
);
520 function setNewtalk( $val ) {
521 $this->loadFromDatabase();
522 $this->mNewtalk
= $val;
523 $this->invalidateCache();
526 function invalidateCache() {
527 $this->loadFromDatabase();
528 $this->mTouched
= wfTimestampNow();
529 # Don't forget to save the options after this or
530 # it won't take effect!
533 function validateCache( $timestamp ) {
534 $this->loadFromDatabase();
535 return ($timestamp >= $this->mTouched
);
540 * Will only be salted if $wgPasswordSalt is true
541 * @param string Password.
542 * @return string Salted password or clear password.
544 function addSalt( $p ) {
545 global $wgPasswordSalt;
547 return md5( "{$this->mId}-{$p}" );
553 * Encrypt a password.
554 * It can eventuall salt a password @see User::addSalt()
555 * @param string $p clear Password.
556 * @param string Encrypted password.
558 function encryptPassword( $p ) {
559 return $this->addSalt( md5( $p ) );
562 # Set the password and reset the random token
563 function setPassword( $str ) {
564 $this->loadFromDatabase();
566 $this->mPassword
= $this->encryptPassword( $str );
567 $this->mNewpassword
= '';
570 # Set the random token (used for persistent authentication)
571 function setToken( $token = false ) {
574 # Take random data from PRNG
575 # This is reasonably secure if the PRNG has been seeded correctly
576 for ($i = 0; $i<USER_TOKEN_LENGTH
/ 4; $i++
) {
577 $this->mToken
.= sprintf( "%04X", mt_rand( 0, 65535 ) );
580 $this->mToken
= $token;
585 function setCookiePassword( $str ) {
586 $this->loadFromDatabase();
587 $this->mCookiePassword
= md5( $str );
590 function setNewpassword( $str ) {
591 $this->loadFromDatabase();
592 $this->mNewpassword
= $this->encryptPassword( $str );
595 function getEmail() {
596 $this->loadFromDatabase();
597 return $this->mEmail
;
600 function getEmailAuthenticationtimestamp() {
601 $this->loadFromDatabase();
602 return $this->mEmailAuthenticationtimestamp
;
605 function setEmail( $str ) {
606 $this->loadFromDatabase();
607 $this->mEmail
= $str;
610 function getRealName() {
611 $this->loadFromDatabase();
612 return $this->mRealName
;
615 function setRealName( $str ) {
616 $this->loadFromDatabase();
617 $this->mRealName
= $str;
620 function getOption( $oname ) {
621 $this->loadFromDatabase();
622 if ( array_key_exists( $oname, $this->mOptions
) ) {
623 return $this->mOptions
[$oname];
629 function setOption( $oname, $val ) {
630 $this->loadFromDatabase();
631 if ( $oname == 'skin' ) {
632 # Clear cached skin, so the new one displays immediately in Special:Preferences
633 unset( $this->mSkin
);
635 $this->mOptions
[$oname] = $val;
636 $this->invalidateCache();
639 function getRights() {
640 $this->loadFromDatabase();
641 return $this->mRights
;
644 function addRight( $rname ) {
645 $this->loadFromDatabase();
646 array_push( $this->mRights
, $rname );
647 $this->invalidateCache();
650 function getGroups() {
651 $this->loadFromDatabase();
652 return $this->mGroups
;
655 function setGroups($groups) {
656 $this->loadFromDatabase();
657 $this->mGroups
= $groups;
658 $this->invalidateCache();
662 * Check if a user is sysop
663 * Die with backtrace. Use User:isAllowed() instead.
668 $this->loadFromDatabase();
669 if ( 0 == $this->mId ) { return false; }
671 return in_array( 'sysop', $this->mRights );
673 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
677 function isDeveloper() {
679 $this->loadFromDatabase();
680 if ( 0 == $this->mId ) { return false; }
682 return in_array( 'developer', $this->mRights );
684 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
688 function isBureaucrat() {
690 $this->loadFromDatabase();
691 if ( 0 == $this->mId ) { return false; }
693 return in_array( 'bureaucrat', $this->mRights );
695 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
699 * Whether the user is a bot
700 * @todo need to be migrated to the new user level management sytem
703 $this->loadFromDatabase();
705 # Why was this here? I need a UID=0 conversion script [TS]
706 # if ( 0 == $this->mId ) { return false; }
708 return in_array( 'bot', $this->mRights
);
712 * Check if user is allowed to access a feature / make an action
713 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
714 * @return boolean True: action is allowed, False: action should not be allowed
716 function isAllowed($action='') {
717 $this->loadFromDatabase();
718 return in_array( $action , $this->mRights
);
722 * Load a skin if it doesn't exist or return it
723 * @todo FIXME : need to check the old failback system [AV]
725 function &getSkin() {
727 if ( ! isset( $this->mSkin
) ) {
728 $fname = 'User::getSkin';
729 wfProfileIn( $fname );
731 # get all skin names available
732 $skinNames = Skin
::getSkinNames();
735 $userSkin = $this->getOption( 'skin' );
736 if ( $userSkin == '' ) { $userSkin = 'standard'; }
738 if ( !isset( $skinNames[$userSkin] ) ) {
739 # in case the user skin could not be found find a replacement
744 # if phptal is enabled we should have monobook skin that
745 # superseed the good old SkinStandard.
746 if ( isset( $skinNames['monobook'] ) ) {
747 $fallback[0] = 'MonoBook';
750 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
751 $sn = $fallback[$userSkin];
756 # The user skin is available
757 $sn = $skinNames[$userSkin];
760 # Grab the skin class and initialise it. Each skin checks for PHPTal
761 # and will not load if it's not enabled.
762 require_once( $IP.'/skins/'.$sn.'.php' );
764 # Check if we got if not failback to default skin
765 $className = 'Skin'.$sn;
766 if( !class_exists( $className ) ) {
767 # DO NOT die if the class isn't found. This breaks maintenance
768 # scripts and can cause a user account to be unrecoverable
769 # except by SQL manipulation if a previously valid skin name
770 # is no longer valid.
771 $className = 'SkinStandard';
772 require_once( $IP.'/skins/Standard.php' );
774 $this->mSkin
=& new $className;
775 wfProfileOut( $fname );
781 * @param string $title Article title to look at
785 * Check watched status of an article
786 * @return bool True if article is watched
788 function isWatched( $title ) {
789 $wl = WatchedItem
::fromUserTitle( $this, $title );
790 return $wl->isWatched();
796 function addWatch( $title ) {
797 $wl = WatchedItem
::fromUserTitle( $this, $title );
799 $this->invalidateCache();
803 * Stop watching an article
805 function removeWatch( $title ) {
806 $wl = WatchedItem
::fromUserTitle( $this, $title );
808 $this->invalidateCache();
812 * Clear the user's notification timestamp for the given title.
813 * If e-notif e-mails are on, they will receive notification mails on
814 * the next change of the page if it's watched etc.
816 function clearNotification( $title ) {
817 $userid = $this->getId();
820 $dbw =& wfGetDB( DB_MASTER
);
821 $success = $dbw->update( 'watchlist',
823 'wl_notificationtimestamp' => $dbw->timestamp(0)
824 ), array( /* WHERE */
825 'wl_title' => $title->getDBkey(),
826 'wl_namespace' => $title->getNamespace(),
827 'wl_user' => $this->getId()
828 ), 'User::clearLastVisited'
835 * Resets all of the given user's page-change notification timestamps.
836 * If e-notif e-mails are on, they will receive notification mails on
837 * the next change of any watched page.
839 * @param int $currentUser user ID number
842 function clearAllNotifications( $currentUser ) {
843 if( $currentUser != 0 ) {
845 $dbw =& wfGetDB( DB_MASTER
);
846 $success = $dbw->update( 'watchlist',
848 'wl_notificationtimestamp' => 0
849 ), array( /* WHERE */
850 'wl_user' => $currentUser
851 ), 'UserMailer::clearAll'
854 # we also need to clear here the "you have new message" notification for the own user_talk page
855 # This is cleared one page view later in Article::viewUpdates();
861 * @return string Encoding options
863 function encodeOptions() {
865 foreach ( $this->mOptions
as $oname => $oval ) {
866 array_push( $a, $oname.'='.$oval );
868 $s = implode( "\n", $a );
875 function decodeOptions( $str ) {
876 $a = explode( "\n", $str );
877 foreach ( $a as $s ) {
878 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
879 $this->mOptions
[$m[1]] = $m[2];
884 function setCookies() {
885 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
886 if ( 0 == $this->mId
) return;
887 $this->loadFromDatabase();
888 $exp = time() +
$wgCookieExpiration;
890 $_SESSION['wsUserID'] = $this->mId
;
891 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
893 $_SESSION['wsUserName'] = $this->mName
;
894 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
896 $_SESSION['wsToken'] = $this->mToken
;
897 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
898 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
900 setcookie( $wgDBname.'Token', '', time() - 3600 );
906 * It will clean the session cookie
909 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
910 $this->loadDefaults();
911 $this->setLoaded( true );
913 $_SESSION['wsUserID'] = 0;
915 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
916 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
920 * Save object settings into database
922 function saveSettings() {
923 global $wgMemc, $wgDBname;
924 $fname = 'User::saveSettings';
926 $dbw =& wfGetDB( DB_MASTER
);
927 if ( ! $this->getNewtalk() ) {
928 # Delete the watchlist entry for user_talk page X watched by user X
929 $dbw->delete( 'watchlist',
930 array( 'wl_user' => $this->mId
,
931 'wl_title' => $this->getTitleKey(),
932 'wl_namespace' => NS_USER_TALK
),
935 # Anon users have a separate memcache space for newtalk
936 # since they don't store their own info. Trim...
937 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
941 if ( 0 == $this->mId
) { return; }
943 $dbw->update( 'user',
945 'user_name' => $this->mName
,
946 'user_password' => $this->mPassword
,
947 'user_newpassword' => $this->mNewpassword
,
948 'user_real_name' => $this->mRealName
,
949 'user_email' => $this->mEmail
,
950 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
951 'user_options' => $this->encodeOptions(),
952 'user_touched' => $dbw->timestamp($this->mTouched
),
953 'user_token' => $this->mToken
954 ), array( /* WHERE */
955 'user_id' => $this->mId
958 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
959 'ur_user='. $this->mId
, $fname );
960 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
963 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
966 foreach ($this->mGroups
as $group) {
967 $dbw->replace( 'user_groups',
968 array(array('ug_user','ug_group')),
970 'ug_user' => $this->mId
,
979 * Checks if a user with the given name exists, returns the ID
981 function idForName() {
982 $fname = 'User::idForName';
985 $s = trim( $this->mName
);
986 if ( 0 == strcmp( '', $s ) ) return 0;
988 $dbr =& wfGetDB( DB_SLAVE
);
989 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
990 if ( $id === false ) {
997 * Add user object to the database
999 function addToDatabase() {
1000 $fname = 'User::addToDatabase';
1001 $dbw =& wfGetDB( DB_MASTER
);
1002 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1003 $dbw->insert( 'user',
1005 'user_id' => $seqVal,
1006 'user_name' => $this->mName
,
1007 'user_password' => $this->mPassword
,
1008 'user_newpassword' => $this->mNewpassword
,
1009 'user_email' => $this->mEmail
,
1010 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
1011 'user_real_name' => $this->mRealName
,
1012 'user_options' => $this->encodeOptions(),
1013 'user_token' => $this->mToken
1016 $this->mId
= $dbw->insertId();
1017 $dbw->insert( 'user_rights',
1019 'ur_user' => $this->mId
,
1020 'ur_rights' => implode( ',', $this->mRights
)
1024 foreach ($this->mGroups
as $group) {
1025 $dbw->insert( 'user_groups',
1027 'ug_user' => $this->mId
,
1028 'ug_group' => $group
1034 function spreadBlock() {
1036 # If the (non-anonymous) user is blocked, this function will block any IP address
1037 # that they successfully log on from.
1038 $fname = 'User::spreadBlock';
1040 wfDebug( "User:spreadBlock()\n" );
1041 if ( $this->mId
== 0 ) {
1045 $userblock = Block
::newFromDB( '', $this->mId
);
1046 if ( !$userblock->isValid() ) {
1050 # Check if this IP address is already blocked
1051 $ipblock = Block
::newFromDB( $wgIP );
1052 if ( $ipblock->isValid() ) {
1053 # Just update the timestamp
1054 $ipblock->updateTimestamp();
1058 # Make a new block object with the desired properties
1059 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1060 $ipblock->mAddress
= $wgIP;
1061 $ipblock->mUser
= 0;
1062 $ipblock->mBy
= $userblock->mBy
;
1063 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1064 $ipblock->mTimestamp
= wfTimestampNow();
1065 $ipblock->mAuto
= 1;
1066 # If the user is already blocked with an expiry date, we don't
1067 # want to pile on top of that!
1068 if($userblock->mExpiry
) {
1069 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1071 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1079 function getPageRenderingHash() {
1082 return $this->mHash
;
1085 // stubthreshold is only included below for completeness,
1086 // it will always be 0 when this function is called by parsercache.
1088 $confstr = $this->getOption( 'math' );
1089 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1090 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1091 $confstr .= '!' . $this->getOption( 'editsection' );
1092 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1093 $confstr .= '!' . $this->getOption( 'showtoc' );
1094 $confstr .= '!' . $this->getOption( 'date' );
1095 $confstr .= '!' . $this->getOption( 'numberheadings' );
1096 $confstr .= '!' . $this->getOption( 'language' );
1097 // add in language specific options, if any
1098 $extra = $wgContLang->getExtraHashOptions();
1101 $this->mHash
= $confstr;
1105 function isAllowedToCreateAccount() {
1106 global $wgWhitelistAccount;
1109 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1110 foreach ($wgWhitelistAccount as $right => $ok) {
1111 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1112 $allowed |
= ($ok && $userHasRight);
1118 * Set mDataLoaded, return previous value
1119 * Use this to prevent DB access in command-line scripts or similar situations
1121 function setLoaded( $loaded ) {
1122 return wfSetVar( $this->mDataLoaded
, $loaded );
1125 function getUserPage() {
1126 return Title
::makeTitle( NS_USER
, $this->mName
);
1132 function getMaxID() {
1133 $dbr =& wfGetDB( DB_SLAVE
);
1134 return $dbr->selectField( 'user', 'max(user_id)', false );
1138 * Determine whether the user is a newbie. Newbies are either
1139 * anonymous IPs, or the 1% most recently created accounts.
1140 * Bots and sysops are excluded.
1141 * @return bool True if it is a newbie.
1143 function isNewbie() {
1144 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
1148 * Check to see if the given clear-text password is one of the accepted passwords
1149 * @param string $password User password.
1150 * @return bool True if the given password is correct otherwise False.
1152 function checkPassword( $password ) {
1154 $this->loadFromDatabase();
1156 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1158 } elseif( $wgAuth->strict() ) {
1159 /* Auth plugin doesn't allow local authentication */
1162 $ep = $this->encryptPassword( $password );
1163 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1165 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1166 $this->mEmailAuthenticationtimestamp
= wfTimestampNow();
1167 $this->mNewpassword
= ''; # use the temporary one-time password only once: clear it now !
1168 $this->saveSettings();
1170 } elseif ( function_exists( 'iconv' ) ) {
1171 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1172 # Check for this with iconv
1173 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1174 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {