* @package MediaWiki
*/
-/**
- *
- */
-require_once( 'WatchedItem.php' );
-
# Number of characters in user_token field
define( 'USER_TOKEN_LENGTH', 32 );
# Serialized record version
-define( 'MW_USER_VERSION', 2 );
+define( 'MW_USER_VERSION', 3 );
/**
*
* @package MediaWiki
*/
class User {
- /**#@+
- * @access private
- */
- var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
- var $mEmailAuthenticated;
- var $mRights, $mOptions;
- var $mDataLoaded, $mNewpassword;
- var $mSkin;
- var $mBlockedby, $mBlockreason;
- var $mTouched;
- var $mToken;
- var $mRealName;
- var $mHash;
- var $mGroups;
- var $mVersion; // serialized version
-
- /** Construct using User:loadDefaults() */
+ /*
+ * When adding a new private variable, dont forget to add it to __sleep()
+ */
+ /**@{{
+ * @private
+ */
+ var $mBlockedby; //!<
+ var $mBlockreason; //!<
+ var $mBlock; //!<
+ var $mDataLoaded; //!<
+ var $mEmail; //!<
+ var $mEmailAuthenticated; //!<
+ var $mGroups; //!<
+ var $mHash; //!<
+ var $mId; //!<
+ var $mName; //!<
+ var $mNewpassword; //!<
+ var $mNewtalk; //!<
+ var $mOptions; //!<
+ var $mPassword; //!<
+ var $mRealName; //!<
+ var $mRegistration; //!<
+ var $mRights; //!<
+ var $mSkin; //!<
+ var $mToken; //!<
+ var $mTouched; //!<
+ var $mDatePreference; // !<
+ var $mVersion; //!< serialized version
+ /**@}} */
+
+ /**
+ * Default user options
+ * To change this array at runtime, use a UserDefaultOptions hook
+ */
+ static public $mDefaultOptions = array(
+ 'quickbar' => 1,
+ 'underline' => 2,
+ 'cols' => 80,
+ 'rows' => 25,
+ 'searchlimit' => 20,
+ 'contextlines' => 5,
+ 'contextchars' => 50,
+ 'skin' => false,
+ 'math' => 1,
+ 'rcdays' => 7,
+ 'rclimit' => 50,
+ 'wllimit' => 250,
+ 'highlightbroken' => 1,
+ 'stubthreshold' => 0,
+ 'previewontop' => 1,
+ 'editsection' => 1,
+ 'editsectiononrightclick'=> 0,
+ 'showtoc' => 1,
+ 'showtoolbar' => 1,
+ 'date' => 'default',
+ 'imagesize' => 2,
+ 'thumbsize' => 2,
+ 'rememberpassword' => 0,
+ 'enotifwatchlistpages' => 0,
+ 'enotifusertalkpages' => 1,
+ 'enotifminoredits' => 0,
+ 'enotifrevealaddr' => 0,
+ 'shownumberswatching' => 1,
+ 'fancysig' => 0,
+ 'externaleditor' => 0,
+ 'externaldiff' => 0,
+ 'showjumplinks' => 1,
+ 'numberheadings' => 0,
+ 'uselivepreview' => 0,
+ 'watchlistdays' => 3.0,
+ );
+
+ static public $mToggles = array(
+ 'highlightbroken',
+ 'justify',
+ 'hideminor',
+ 'extendwatchlist',
+ 'usenewrc',
+ 'numberheadings',
+ 'showtoolbar',
+ 'editondblclick',
+ 'editsection',
+ 'editsectiononrightclick',
+ 'showtoc',
+ 'rememberpassword',
+ 'editwidth',
+ 'watchcreations',
+ 'watchdefault',
+ 'minordefault',
+ 'previewontop',
+ 'previewonfirst',
+ 'nocache',
+ 'enotifwatchlistpages',
+ 'enotifusertalkpages',
+ 'enotifminoredits',
+ 'enotifrevealaddr',
+ 'shownumberswatching',
+ 'fancysig',
+ 'externaleditor',
+ 'externaldiff',
+ 'showjumplinks',
+ 'uselivepreview',
+ 'autopatrol',
+ 'forceeditsummary',
+ 'watchlisthideown',
+ 'watchlisthidebots',
+ );
+
+ /** Constructor using User:loadDefaults() */
function User() {
$this->loadDefaults();
$this->mVersion = MW_USER_VERSION;
/**
* Static factory method
* @param string $name Username, validated by Title:newFromText()
+ * @param bool $validate Validate username
* @return User
* @static
*/
- function newFromName( $name ) {
+ function newFromName( $name, $validate = true ) {
# Force usernames to capital
global $wgContLang;
$name = $wgContLang->ucfirst( $name );
global $wgAuth;
$canonicalName = $wgAuth->getCanonicalName( $t->getText() );
- if( !User::isValidUserName( $canonicalName ) ) {
+ if( $validate && !User::isValidUserName( $canonicalName ) ) {
return null;
}
/**
* Serialze sleep function, for better cache efficiency and avoidance of
- * silly "incomplete type" errors when skins are cached
+ * silly "incomplete type" errors when skins are cached. The array should
+ * contain names of private variables (see at top of User.php).
*/
function __sleep() {
- return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
- 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
- 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
- 'mToken', 'mRealName', 'mHash', 'mGroups' );
+ return array(
+'mDataLoaded',
+'mEmail',
+'mEmailAuthenticated',
+'mGroups',
+'mHash',
+'mId',
+'mName',
+'mNewpassword',
+'mNewtalk',
+'mOptions',
+'mPassword',
+'mRealName',
+'mRegistration',
+'mRights',
+'mToken',
+'mTouched',
+'mVersion',
+);
}
/**
}
/**
- * does the string match an anonymous IPv4 address?
+ * Does the string match an anonymous IPv4 address?
*
- * Note: We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
+ * This function exists for username validation, in order to reject
+ * usernames which are similar in form to IP addresses. Strings such
+ * as 300.300.300.300 will return true because it looks like an IP
+ * address, despite not being strictly valid.
+ *
+ * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
* address because the usemod software would "cloak" anonymous IP
* addresses like this, if we allowed accounts like this to be created
* new users could get the old edits of these anonymous users.
|| strlen( $name ) > $wgMaxNameChars
|| $name != $wgContLang->ucfirst( $name ) )
return false;
-
+
// Ensure that the name can't be misresolved as a different title,
// such as with extra namespace keys at the start.
$parsed = Title::newFromText( $name );
|| $parsed->getNamespace()
|| strcmp( $name, $parsed->getPrefixedText() ) )
return false;
- else
- return true;
+
+ // Check an additional blacklist of troublemaker characters.
+ // Should these be merged into the title char list?
+ $unicodeBlacklist = '/[' .
+ '\x{0080}-\x{009f}' . # iso-8859-1 control chars
+ '\x{00a0}' . # non-breaking space
+ '\x{2000}-\x{200f}' . # various whitespace
+ '\x{2028}-\x{202f}' . # breaks and control chars
+ '\x{3000}' . # ideographic space
+ '\x{e000}-\x{f8ff}' . # private use
+ ']/u';
+ if( preg_match( $unicodeBlacklist, $name ) ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Usernames which fail to pass this function will be blocked
+ * from user login and new account registrations, but may be used
+ * internally by batch processes.
+ *
+ * If an account already exists in this form, login will be blocked
+ * by a failure to pass this function.
+ *
+ * @param string $name
+ * @return bool
+ */
+ static function isUsableName( $name ) {
+ global $wgReservedUsernames;
+ return
+ // Must be a usable username, obviously ;)
+ self::isValidUserName( $name ) &&
+
+ // Certain names may be reserved for batch processes.
+ !in_array( $name, $wgReservedUsernames );
+ }
+
+ /**
+ * Usernames which fail to pass this function will be blocked
+ * from new account registrations, but may be used internally
+ * either by batch processes or by user accounts which have
+ * already been created.
+ *
+ * Additional character blacklisting may be added here
+ * rather than in isValidUserName() to avoid disrupting
+ * existing accounts.
+ *
+ * @param string $name
+ * @return bool
+ */
+ static function isCreatableName( $name ) {
+ return
+ self::isUsableName( $name ) &&
+
+ // Registration-time character blacklisting...
+ strpos( $name, '@' ) === false;
}
/**
$fname = 'User::loadDefaults' . $n;
wfProfileIn( $fname );
- global $wgContLang, $wgDBname;
+ global $wgCookiePrefix;
global $wgNamespacesToBeSearchedDefault;
$this->mId = 0;
$this->mPassword = $this->mNewpassword = '';
$this->mRights = array();
$this->mGroups = array();
- $this->mOptions = User::getDefaultOptions();
+ $this->mOptions = null;
+ $this->mDatePreference = null;
- foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
- $this->mOptions['searchNs'.$nsnum] = $val;
- }
unset( $this->mSkin );
$this->mDataLoaded = false;
$this->mBlockedby = -1; # Unset
$this->setToken(); # Random
$this->mHash = false;
- if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
- $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
+ if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
+ $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
}
else {
$this->mTouched = '0'; # Allow any pages to be cached
}
+ $this->mRegistration = wfTimestamp( TS_MW );
+
wfProfileOut( $fname );
}
*
* @return array
* @static
- * @access private
+ * @private
*/
function getDefaultOptions() {
+ global $wgNamespacesToBeSearchedDefault;
/**
* Site defaults will override the global/language defaults
*/
- global $wgContLang, $wgDefaultUserOptions;
- $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
+ global $wgContLang;
+ $defOpt = self::$mDefaultOptions + $wgContLang->getDefaultUserOptionOverrides();
/**
* default language setting
*/
- $variant = $wgContLang->getPreferredVariant();
+ $variant = $wgContLang->getPreferredVariant( false );
$defOpt['variant'] = $variant;
$defOpt['language'] = $variant;
+ foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
+ $defOpt['searchNs'.$nsnum] = $val;
+ }
return $defOpt;
}
* @param string $opt
* @return string
* @static
- * @access public
+ * @public
*/
function getDefaultOption( $opt ) {
$defOpts = User::getDefaultOptions();
}
}
+ /**
+ * Get a list of user toggle names
+ * @return array
+ */
+ static function getToggles() {
+ global $wgContLang;
+ $extraToggles = array();
+ wfRunHooks( 'UserToggles', array( &$extraToggles ) );
+ return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
+ }
+
+
/**
* Get blocking information
- * @access private
+ * @private
* @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
* non-critical checks are done against slaves. Check when actually saving should be done against
* master.
$ip = wfGetIP();
# User/IP blocking
- $block = new Block();
- $block->fromMaster( !$bFromSlave );
- if ( $block->load( $ip , $this->mId ) ) {
+ $this->mBlock = new Block();
+ $this->mBlock->fromMaster( !$bFromSlave );
+ if ( $this->mBlock->load( $ip , $this->mId ) ) {
wfDebug( "$fname: Found block.\n" );
- $this->mBlockedby = $block->mBy;
- $this->mBlockreason = $block->mReason;
+ $this->mBlockedby = $this->mBlock->mBy;
+ $this->mBlockreason = $this->mBlock->mReason;
if ( $this->isLoggedIn() ) {
$this->spreadBlock();
}
} else {
+ $this->mBlock = null;
wfDebug( "$fname: No block.\n" );
}
# Proxy blocking
- if ( !$this->isSysop() && !in_array( $ip, $wgProxyWhitelist ) ) {
+ if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
# Local list
if ( wfIsLocallyBlockedProxy( $ip ) ) {
$this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
}
- function inOpmBlacklist( $ip ) {
- global $wgEnableOpm;
- return $wgEnableOpm &&
- $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
- }
-
function inDnsBlacklist( $ip, $base ) {
$fname = 'User::inDnsBlacklist';
wfProfileIn( $fname );
* last-hit counters will be shared across wikis.
*
* @return bool true if a rate limiter was tripped
- * @access public
+ * @public
*/
function pingLimiter( $action='edit' ) {
- global $wgRateLimits;
+ global $wgRateLimits, $wgRateLimitsExcludedGroups;
if( !isset( $wgRateLimits[$action] ) ) {
return false;
}
- if( $this->isAllowed( 'delete' ) ) {
- // goddam cabal
- return false;
+
+ # Some groups shouldn't trigger the ping limiter, ever
+ foreach( $this->getGroups() as $group ) {
+ if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
+ return false;
}
-
- global $wgMemc, $wgDBname, $wgRateLimitLog;
+
+ global $wgMemc, $wgRateLimitLog;
$fname = 'User::pingLimiter';
wfProfileIn( $fname );
$ip = wfGetIP();
if( isset( $limits['anon'] ) && $id == 0 ) {
- $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
+ $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
}
if( isset( $limits['user'] ) && $id != 0 ) {
- $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
+ $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
}
if( $this->isNewbie() ) {
if( isset( $limits['newbie'] ) && $id != 0 ) {
- $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
+ $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
}
if( isset( $limits['ip'] ) ) {
$keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
if( $count > $max ) {
wfDebug( "$fname: tripped! $key at $count $summary\n" );
if( $wgRateLimitLog ) {
- @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
+ @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
}
$triggered = true;
} else {
/**
* Initialise php session
+ * @deprecated use wfSetupSession()
*/
function SetupSession() {
- global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
- if( $wgSessionsInMemcached ) {
- require_once( 'MemcachedSessions.php' );
- } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
- # If it's left on 'user' or another setting from another
- # application, it will end up failing. Try to recover.
- ini_set ( 'session.save_handler', 'files' );
- }
- session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
- session_cache_limiter( 'private, must-revalidate' );
- @session_start();
+ wfSetupSession();
}
/**
* @static
*/
function loadFromSession() {
- global $wgMemc, $wgDBname;
+ global $wgMemc, $wgCookiePrefix;
if ( isset( $_SESSION['wsUserID'] ) ) {
if ( 0 != $_SESSION['wsUserID'] ) {
} else {
return new User();
}
- } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
- $sId = intval( $_COOKIE["{$wgDBname}UserID"] );
+ } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
+ $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
$_SESSION['wsUserID'] = $sId;
} else {
return new User();
}
if ( isset( $_SESSION['wsUserName'] ) ) {
$sName = $_SESSION['wsUserName'];
- } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
- $sName = $_COOKIE["{$wgDBname}UserName"];
+ } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
+ $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
$_SESSION['wsUserName'] = $sName;
} else {
return new User();
}
$passwordCorrect = FALSE;
- $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
+ $user = $wgMemc->get( $key = wfMemcKey( 'user', 'id', $sId ) );
if( !is_object( $user ) || $user->mVersion < MW_USER_VERSION ) {
# Expire old serialized objects; they may be corrupt.
$user = false;
$user->loadFromDatabase();
} else {
wfDebug( "User::loadFromSession() got from cache!\n" );
+ # Set block status to unloaded, that should be loaded every time
+ $user->mBlockedby = -1;
}
if ( isset( $_SESSION['wsToken'] ) ) {
$passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
- } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
- $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
+ } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
+ $passwordCorrect = $user->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
} else {
return new User(); # Can't log in from session
}
$dbr =& wfGetDB( DB_SLAVE );
$s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
'user_email_authenticated',
- 'user_real_name','user_options','user_touched', 'user_token' ),
+ 'user_real_name','user_options','user_touched', 'user_token', 'user_registration' ),
array( 'user_id' => $this->mId ), $fname );
if ( $s !== false ) {
$this->decodeOptions( $s->user_options );
$this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
$this->mToken = $s->user_token;
+ $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
$res = $dbr->select( 'user_groups',
array( 'ug_group' ),
while( $row = $dbr->fetchObject( $res ) ) {
$this->mGroups[] = $row->ug_group;
}
- $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
+ $implicitGroups = array( '*', 'user' );
+
+ global $wgAutoConfirmAge;
+ $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
+ if( $accountAge >= $wgAutoConfirmAge ) {
+ $implicitGroups[] = 'autoconfirmed';
+ }
+
+ # Implicit group for users whose email addresses are confirmed
+ global $wgEmailAuthentication;
+ if( $this->isValidEmailAddr( $this->mEmail ) ) {
+ if( $wgEmailAuthentication ) {
+ if( $this->mEmailAuthenticated )
+ $implicitGroups[] = 'emailconfirmed';
+ } else {
+ $implicitGroups[] = 'emailconfirmed';
+ }
+ }
+
+ $effectiveGroups = array_merge( $implicitGroups, $this->mGroups );
$this->mRights = $this->getGroupPermissions( $effectiveGroups );
}
/**
* Return the title dbkey form of the name, for eg user pages.
* @return string
- * @access public
+ * @public
*/
function getTitleKey() {
return str_replace( ' ', '_', $this->getName() );
# Check memcached separately for anons, who have no
# entire User object stored in there.
if( !$this->mId ) {
- global $wgDBname, $wgMemc;
- $key = "$wgDBname:newtalk:ip:" . $this->getName();
+ global $wgMemc;
+ $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
$newtalk = $wgMemc->get( $key );
if( is_integer( $newtalk ) ) {
$this->mNewtalk = (bool)$newtalk;
return (bool)$this->mNewtalk;
}
+ /**
+ * Return the talk page(s) this user has new messages on.
+ */
+ function getNewMessageLinks() {
+ $talks = array();
+ if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
+ return $talks;
+
+ if (!$this->getNewtalk())
+ return array();
+ $up = $this->getUserPage();
+ $utp = $up->getTalkPage();
+ return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
+ }
+
+
/**
* Perform a user_newtalk check on current slaves; if the memcached data
* is funky we don't want newtalk state to get stuck on save, as that's
* @param string $field
* @param mixed $id
* @return bool
- * @access private
+ * @private
*/
function checkNewtalk( $field, $id ) {
$fname = 'User::checkNewtalk';
array( $field => $id ), $fname );
return $ok !== false;
}
-
+
/**
- * Add or update the
+ * Add or update the
* @param string $field
* @param mixed $id
- * @access private
+ * @private
*/
function updateNewtalk( $field, $id ) {
$fname = 'User::updateNewtalk';
wfDebug( "$fname: set on ($field, $id)\n" );
return true;
}
-
+
/**
+ * Clear the new messages flag for the given user
* @param string $field
* @param mixed $id
- * @access private
+ * @private
*/
function deleteNewtalk( $field, $id ) {
$fname = 'User::deleteNewtalk';
wfDebug( "$fname: killed on ($field, $id)\n" );
return true;
}
-
+
/**
* Update the 'You have new messages!' status.
* @param bool $val
if( wfReadOnly() ) {
return;
}
-
+
$this->loadFromDatabase();
$this->mNewtalk = $val;
$fname = 'User::setNewtalk';
-
+
if( $this->isAnon() ) {
$field = 'user_ip';
$id = $this->getName();
$field = 'user_id';
$id = $this->getId();
}
-
+
if( $val ) {
$changed = $this->updateNewtalk( $field, $id );
} else {
$changed = $this->deleteNewtalk( $field, $id );
}
-
+
if( $changed ) {
if( $this->isAnon() ) {
// Anons have a separate memcached space, since
// user records aren't kept for them.
- global $wgDBname, $wgMemc;
- $key = "$wgDBname:newtalk:ip:$value";
+ global $wgMemc;
+ $key = wfMemcKey( 'newtalk', 'ip', $val );
$wgMemc->set( $key, $val ? 1 : 0 );
} else {
if( $val ) {
}
}
$this->invalidateCache();
- $this->saveSettings();
+ }
+ }
+
+ /**
+ * Generate a current or new-future timestamp to be stored in the
+ * user_touched field when we update things.
+ */
+ private static function newTouchedTimestamp() {
+ global $wgClockSkewFudge;
+ return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
+ }
+
+ /**
+ * Clear user data from memcached.
+ * Use after applying fun updates to the database; caller's
+ * responsibility to update user_touched if appropriate.
+ *
+ * Called implicitly from invalidateCache() and saveSettings().
+ */
+ private function clearUserCache() {
+ if( $this->mId ) {
+ global $wgMemc;
+ $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
}
}
+ /**
+ * Immediately touch the user data cache for this account.
+ * Updates user_touched field, and removes account data from memcached
+ * for reload on the next hit.
+ */
function invalidateCache() {
- global $wgClockSkewFudge;
- $this->loadFromDatabase();
- $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
- # Don't forget to save the options after this or
- # it won't take effect!
+ if( $this->mId ) {
+ $this->mTouched = self::newTouchedTimestamp();
+
+ $dbw =& wfGetDB( DB_MASTER );
+ $dbw->update( 'user',
+ array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
+ array( 'user_id' => $this->mId ),
+ __METHOD__ );
+
+ $this->clearUserCache();
+ }
}
function validateCache( $timestamp ) {
# Set the random token (used for persistent authentication)
function setToken( $token = false ) {
- global $wgSecretKey, $wgProxyKey, $wgDBname;
+ global $wgSecretKey, $wgProxyKey;
if ( !$token ) {
if ( $wgSecretKey ) {
$key = $wgSecretKey;
} else {
$key = microtime();
}
- $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
+ $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
} else {
$this->mToken = $token;
}
$this->mRealName = $str;
}
+ /**
+ * @param string $oname The option to check
+ * @return string
+ */
function getOption( $oname ) {
$this->loadFromDatabase();
+ if ( is_null( $this->mOptions ) ) {
+ $this->mOptions = User::getDefaultOptions();
+ }
if ( array_key_exists( $oname, $this->mOptions ) ) {
return trim( $this->mOptions[$oname] );
} else {
}
}
+ /**
+ * Get the user's date preference, including some important migration for
+ * old user rows.
+ */
+ function getDatePreference() {
+ if ( is_null( $this->mDatePreference ) ) {
+ global $wgLang;
+ $value = $this->getOption( 'date' );
+ $map = $wgLang->getDatePreferenceMigrationMap();
+ if ( isset( $map[$value] ) ) {
+ $value = $map[$value];
+ }
+ $this->mDatePreference = $value;
+ }
+ return $this->mDatePreference;
+ }
+
+ /**
+ * @param string $oname The option to check
+ * @return bool False if the option is not selected, true if it is
+ */
+ function getBoolOption( $oname ) {
+ return (bool)$this->getOption( $oname );
+ }
+
+ /**
+ * Get an option as an integer value from the source string.
+ * @param string $oname The option to check
+ * @param int $default Optional value to return if option is unset/blank.
+ * @return int
+ */
+ function getIntOption( $oname, $default=0 ) {
+ $val = $this->getOption( $oname );
+ if( $val == '' ) {
+ $val = $default;
+ }
+ return intval( $val );
+ }
+
function setOption( $oname, $val ) {
$this->loadFromDatabase();
+ if ( is_null( $this->mOptions ) ) {
+ $this->mOptions = User::getDefaultOptions();
+ }
if ( $oname == 'skin' ) {
# Clear cached skin, so the new one displays immediately in Special:Preferences
unset( $this->mSkin );
}
+ // Filter out any newlines that may have passed through input validation.
+ // Newlines are used to separate items in the options blob.
+ $val = str_replace( "\r\n", "\n", $val );
+ $val = str_replace( "\r", "\n", $val );
+ $val = str_replace( "\n", " ", $val );
$this->mOptions[$oname] = $val;
- $this->invalidateCache();
}
function getRights() {
}
/**
- * Remove the user from the given group.
+ * Add the user to the given group.
* This takes immediate effect.
* @string $group
*/
$this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
$this->invalidateCache();
- $this->saveSettings();
}
/**
$this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
$this->invalidateCache();
- $this->saveSettings();
}
return !$this->isLoggedIn();
}
- /**
- * Check if a user is sysop
- * @deprecated
- */
- function isSysop() {
- return $this->isAllowed( 'protect' );
- }
-
- /** @deprecated */
- function isDeveloper() {
- return $this->isAllowed( 'siteadmin' );
- }
-
- /** @deprecated */
- function isBureaucrat() {
- return $this->isAllowed( 'makesysop' );
- }
-
/**
* Whether the user is a bot
- * @todo need to be migrated to the new user level management sytem
+ * @deprecated
*/
function isBot() {
- $this->loadFromDatabase();
- return in_array( 'bot', $this->mRights );
+ return $this->isAllowed( 'bot' );
}
/**
* Check if user is allowed to access a feature / make an action
- * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
+ * @param string $action Action to be checked
* @return boolean True: action is allowed, False: action should not be allowed
*/
function isAllowed($action='') {
$fname = 'User::getSkin';
wfProfileIn( $fname );
- # get all skin names available
- $skinNames = Skin::getSkinNames();
-
# get the user skin
$userSkin = $this->getOption( 'skin' );
$userSkin = $wgRequest->getVal('useskin', $userSkin);
-
+
$this->mSkin =& Skin::newFromKey( $userSkin );
wfProfileOut( $fname );
}
function clearNotification( &$title ) {
global $wgUser, $wgUseEnotif;
+
if ($title->getNamespace() == NS_USER_TALK &&
$title->getText() == $this->getName() ) {
+ if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
+ return;
$this->setNewtalk( false );
}
-
+
if( !$wgUseEnotif ) {
return;
}
* the next change of any watched page.
*
* @param int $currentUser user ID number
- * @access public
+ * @public
*/
function clearAllNotifications( $currentUser ) {
global $wgUseEnotif;
$dbw =& wfGetDB( DB_MASTER );
$success = $dbw->update( 'watchlist',
array( /* SET */
- 'wl_notificationtimestamp' => 0
+ 'wl_notificationtimestamp' => NULL
), array( /* WHERE */
'wl_user' => $currentUser
), 'UserMailer::clearAll'
}
/**
- * @access private
+ * @private
* @return string Encoding options
*/
function encodeOptions() {
+ if ( is_null( $this->mOptions ) ) {
+ $this->mOptions = User::getDefaultOptions();
+ }
$a = array();
foreach ( $this->mOptions as $oname => $oval ) {
array_push( $a, $oname.'='.$oval );
}
/**
- * @access private
+ * @private
*/
function decodeOptions( $str ) {
+ global $wgLang;
+
+ $this->mOptions = array();
$a = explode( "\n", $str );
foreach ( $a as $s ) {
if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
}
function setCookies() {
- global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
+ global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
if ( 0 == $this->mId ) return;
$this->loadFromDatabase();
$exp = time() + $wgCookieExpiration;
$_SESSION['wsUserID'] = $this->mId;
- setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
+ setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
$_SESSION['wsUserName'] = $this->getName();
- setcookie( $wgDBname.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain );
+ setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
$_SESSION['wsToken'] = $this->mToken;
if ( 1 == $this->getOption( 'rememberpassword' ) ) {
- setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
+ setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
} else {
- setcookie( $wgDBname.'Token', '', time() - 3600 );
+ setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
}
}
* It will clean the session cookie
*/
function logout() {
- global $wgCookiePath, $wgCookieDomain, $wgDBname;
+ global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
$this->loadDefaults();
$this->setLoaded( true );
$_SESSION['wsUserID'] = 0;
- setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
- setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
+ setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+ setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
# Remember when user logged out, to prevent seeing cached pages
- setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
+ setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
}
/**
* Save object settings into database
+ * @fixme Only rarely do all these fields need to be set!
*/
function saveSettings() {
- global $wgMemc, $wgDBname, $wgUseEnotif;
$fname = 'User::saveSettings';
if ( wfReadOnly() ) { return; }
if ( 0 == $this->mId ) { return; }
+
+ $this->mTouched = self::newTouchedTimestamp();
$dbw =& wfGetDB( DB_MASTER );
$dbw->update( 'user',
'user_id' => $this->mId
), $fname
);
- $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
+ $this->clearUserCache();
}
'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
'user_real_name' => $this->mRealName,
'user_options' => $this->encodeOptions(),
- 'user_token' => $this->mToken
+ 'user_token' => $this->mToken,
+ 'user_registration' => $dbw->timestamp( $this->mRegistration ),
), $fname
);
$this->mId = $dbw->insertId();
}
$userblock = Block::newFromDB( '', $this->mId );
- if ( !$userblock->isValid() ) {
+ if ( !$userblock ) {
return;
}
# Check if this IP address is already blocked
$ipblock = Block::newFromDB( wfGetIP() );
- if ( $ipblock->isValid() ) {
+ if ( $ipblock ) {
# If the user is already blocked. Then check if the autoblock would
# excede the user block. If it would excede, then do nothing, else
# prolong block time
# Just update the timestamp
$ipblock->updateTimestamp();
return;
+ } else {
+ $ipblock = new Block;
}
# Make a new block object with the desired properties
}
+ /**
+ * Generate a string which will be different for any combination of
+ * user options which would produce different parser output.
+ * This will be used as part of the hash key for the parser cache,
+ * so users will the same options can share the same cached data
+ * safely.
+ *
+ * Extensions which require it should install 'PageRenderingHash' hook,
+ * which will give them a chance to modify this key based on their own
+ * settings.
+ *
+ * @return string
+ */
function getPageRenderingHash() {
- global $wgContLang;
+ global $wgContLang, $wgUseDynamicDates;
if( $this->mHash ){
return $this->mHash;
}
$confstr = $this->getOption( 'math' );
$confstr .= '!' . $this->getOption( 'stubthreshold' );
- $confstr .= '!' . $this->getOption( 'date' );
+ if ( $wgUseDynamicDates ) {
+ $confstr .= '!' . $this->getDatePreference();
+ }
$confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
$confstr .= '!' . $this->getOption( 'language' );
$confstr .= '!' . $this->getOption( 'thumbsize' );
$extra = $wgContLang->getExtraHashOptions();
$confstr .= $extra;
+ // Give a chance for extensions to modify the hash, if they have
+ // extra options or other effects on the parser cache.
+ wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
+
$this->mHash = $confstr;
- return $confstr ;
+ return $confstr;
+ }
+
+ function isBlockedFromCreateAccount() {
+ $this->getBlockedStatus();
+ return $this->mBlock && $this->mBlock->mCreateAccount;
}
function isAllowedToCreateAccount() {
- return $this->isAllowed( 'createaccount' ) && !$this->isBlocked();
+ return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
}
/**
* Get this user's personal page title.
*
* @return Title
- * @access public
+ * @public
*/
function getUserPage() {
return Title::makeTitle( NS_USER, $this->getName() );
* Get this user's talk page title.
*
* @return Title
- * @access public
+ * @public
*/
function getTalkPage() {
$title = $this->getUserPage();
/**
* Determine whether the user is a newbie. Newbies are either
- * anonymous IPs, or the 1% most recently created accounts.
- * Bots and sysops are excluded.
+ * anonymous IPs, or the most recently created accounts.
* @return bool True if it is a newbie.
*/
function isNewbie() {
- return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
+ return !$this->isAllowed( 'autoconfirmed' );
}
/**
} elseif ( function_exists( 'iconv' ) ) {
# Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
# Check for this with iconv
- $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
+ $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
return true;
}
* @param mixed $salt - Optional function-specific data for hash.
* Use a string or an array of strings.
* @return string
- * @access public
+ * @public
*/
function editToken( $salt = '' ) {
if( !isset( $_SESSION['wsEditToken'] ) ) {
* @param string $val - the input value to compare
* @param string $salt - Optional function-specific data for hash
* @return bool
- * @access public
+ * @public
*/
function matchEditToken( $val, $salt = '' ) {
global $wgMemc;
-
-/*
- if ( !isset( $_SESSION['wsEditToken'] ) ) {
- $logfile = '/home/wikipedia/logs/session_debug/session.log';
- $mckey = memsess_key( session_id() );
- $uname = @posix_uname();
- $msg = "wsEditToken not set!\n" .
- 'apache server=' . $uname['nodename'] . "\n" .
- 'session_id = ' . session_id() . "\n" .
- '$_SESSION=' . var_export( $_SESSION, true ) . "\n" .
- '$_COOKIE=' . var_export( $_COOKIE, true ) . "\n" .
- "mc get($mckey) = " . var_export( $wgMemc->get( $mckey ), true ) . "\n\n\n";
-
- @error_log( $msg, 3, $logfile );
+ $sessionToken = $this->editToken( $salt );
+ if ( $val != $sessionToken ) {
+ wfDebug( "User::matchEditToken: broken session data\n" );
}
-*/
- return ( $val == $this->editToken( $salt ) );
+ return $val == $sessionToken;
}
/**
* A hash (unsalted since it's used as a key) is stored.
* @param &$expiration mixed output: accepts the expiration time
* @return string
- * @access private
+ * @private
*/
function confirmationToken( &$expiration ) {
$fname = 'User::confirmationToken';
* the URL the user can use to confirm.
* @param &$expiration mixed output: accepts the expiration time
* @return string
- * @access private
+ * @private
*/
function confirmationTokenUrl( &$expiration ) {
$token = $this->confirmationToken( $expiration );
function isEmailConfirmed() {
global $wgEmailAuthentication;
$this->loadFromDatabase();
- if( $this->isAnon() )
- return false;
- if( !$this->isValidEmailAddr( $this->mEmail ) )
- return false;
- if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
- return false;
- return true;
+ $confirmed = true;
+ if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
+ if( $this->isAnon() )
+ return false;
+ if( !$this->isValidEmailAddr( $this->mEmail ) )
+ return false;
+ if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
+ return false;
+ return true;
+ } else {
+ return $confirmed;
+ }
}
/**
* @return array list of permission key names for given groups combined
* @static
*/
- function getGroupPermissions( $groups ) {
+ static function getGroupPermissions( $groups ) {
global $wgGroupPermissions;
$rights = array();
foreach( $groups as $group ) {
/**
* @param string $group key name
- * @return string localized descriptive name, if provided
+ * @return string localized descriptive name for group, if provided
+ * @static
+ */
+ static function getGroupName( $group ) {
+ $key = "group-$group";
+ $name = wfMsg( $key );
+ if( $name == '' || wfEmptyMsg( $key, $name ) ) {
+ return $group;
+ } else {
+ return $name;
+ }
+ }
+
+ /**
+ * @param string $group key name
+ * @return string localized descriptive name for member of a group, if provided
* @static
*/
- function getGroupName( $group ) {
- $key = "group-$group-name";
+ static function getGroupMember( $group ) {
+ $key = "group-$group-member";
$name = wfMsg( $key );
- if( $name == '' || $name == "<$key>" ) {
+ if( $name == '' || wfEmptyMsg( $key, $name ) ) {
return $group;
} else {
return $name;
/**
* Return the set of defined explicit groups.
- * The * and 'user' groups are not included.
+ * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
+ * groups are not included, as they are defined
+ * automatically, not in the database.
* @return array
* @static
*/
- function getAllGroups() {
+ static function getAllGroups() {
global $wgGroupPermissions;
return array_diff(
array_keys( $wgGroupPermissions ),
- array( '*', 'user' ) );
+ array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
+ }
+
+ /**
+ * Get the title of a page describing a particular group
+ *
+ * @param $group Name of the group
+ * @return mixed
+ */
+ static function getGroupPage( $group ) {
+ $page = wfMsgForContent( 'grouppage-' . $group );
+ if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
+ $title = Title::newFromText( $page );
+ if( is_object( $title ) )
+ return $title;
+ }
+ return false;
+ }
+
+ /**
+ * Create a link to the group in HTML, if available
+ *
+ * @param $group Name of the group
+ * @param $text The text of the link
+ * @return mixed
+ */
+ static function makeGroupLinkHTML( $group, $text = '' ) {
+ if( $text == '' ) {
+ $text = self::getGroupName( $group );
+ }
+ $title = self::getGroupPage( $group );
+ if( $title ) {
+ global $wgUser;
+ $sk = $wgUser->getSkin();
+ return $sk->makeLinkObj( $title, $text );
+ } else {
+ return $text;
+ }
}
+ /**
+ * Create a link to the group in Wikitext, if available
+ *
+ * @param $group Name of the group
+ * @param $text The text of the link (by default, the name of the group)
+ * @return mixed
+ */
+ static function makeGroupLinkWiki( $group, $text = '' ) {
+ if( $text == '' ) {
+ $text = self::getGroupName( $group );
+ }
+ $title = self::getGroupPage( $group );
+ if( $title ) {
+ $page = $title->getPrefixedText();
+ return "[[$page|$text]]";
+ } else {
+ return $text;
+ }
+ }
}
?>