<?php
/**
* See user.txt
- *
+ * @file
*/
# Number of characters in user_token field
define( 'USER_TOKEN_LENGTH', 32 );
# Serialized record version
-define( 'MW_USER_VERSION', 5 );
+define( 'MW_USER_VERSION', 6 );
# Some punctuation to prevent editing from broken text-mangling proxies.
-# FIXME: this is embedded unescaped into HTML attributes in various
-# places, so we can't safely include ' or " even though we really should.
-define( 'EDIT_TOKEN_SUFFIX', '\\' );
+define( 'EDIT_TOKEN_SUFFIX', '+\\' );
/**
* Thrown by User::setPassword() on error
- * @addtogroup Exception
+ * @ingroup Exception
*/
class PasswordError extends MWException {
// NOP
}
/**
- *
+ * The User object encapsulates all of the user-specific settings (user_id,
+ * name, rights, password, email address, options, last login time). Client
+ * classes use the getXXX() functions to access these fields. These functions
+ * do all the work of determining whether the user is logged in,
+ * whether the requested option can be satisfied from cookies or
+ * whether a database query is needed. Most of the settings needed
+ * for rendering normal pages are set in the cookie to minimize use
+ * of the database.
*/
class User {
/**
- * A list of default user toggles, i.e. boolean user preferences that are
- * displayed by Special:Preferences as checkboxes. This list can be
+ * A list of default user toggles, i.e. boolean user preferences that are
+ * displayed by Special:Preferences as checkboxes. This list can be
* extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
*/
static public $mToggles = array(
'watchlisthideminor',
'ccmeonemails',
'diffonly',
+ 'showhiddencats',
);
/**
* List of member variables which are saved to the shared cache (memcached).
- * Any operation which changes the corresponding database fields must
+ * Any operation which changes the corresponding database fields must
* call a cache-clearing function.
*/
static $mCacheVars = array(
'mGroups',
);
+ /**
+ * Core rights
+ * Each of these should have a corresponding message of the form "right-$right"
+ */
+ static $mCoreRights = array(
+ 'apihighlimits',
+ 'autoconfirmed',
+ 'autopatrol',
+ 'bigdelete',
+ 'block',
+ 'blockemail',
+ 'bot',
+ 'browsearchive',
+ 'createaccount',
+ 'createpage',
+ 'createtalk',
+ 'delete',
+ 'deletedhistory',
+ 'edit',
+ 'editinterface',
+ 'editusercssjs',
+ 'import',
+ 'importupload',
+ 'ipblock-exempt',
+ 'markbotedits',
+ 'minoredit',
+ 'move',
+ 'nominornewtalk',
+ 'patrol',
+ 'protect',
+ 'proxyunbannable',
+ 'purge',
+ 'read',
+ 'reupload',
+ 'reupload-shared',
+ 'rollback',
+ 'suppressredirect',
+ 'trackback',
+ 'undelete',
+ 'unwatchedpages',
+ 'upload',
+ 'upload_by_url',
+ 'userrights',
+ );
+ static $mAllRights = false;
+
/**
* The cache variable declarations
*/
- var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
- $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
+ var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
+ $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
$mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
/**
var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
$mBlockreason, $mBlock, $mEffectiveGroups;
- /**
+ /**
* Lightweight constructor for anonymous user
* Use the User::newFrom* factory functions for other kinds of users
*/
if ( $this->mId == 0 ) {
$this->loadDefaults();
return false;
- }
+ }
# Try cache
$key = wfMemcKey( 'user', 'id', $this->mId );
# Object is expired, load from DB
$data = false;
}
-
+
if ( !$data ) {
wfDebug( "Cache miss for user {$this->mId}\n" );
# Load from DB
# Can't load from ID, user is anonymous
return false;
}
-
- # Save to cache
- $data = array();
- foreach ( self::$mCacheVars as $name ) {
- $data[$name] = $this->$name;
- }
- $data['mVersion'] = MW_USER_VERSION;
- $wgMemc->set( $key, $data );
+ $this->saveToCache();
} else {
wfDebug( "Got user {$this->mId} from cache\n" );
# Restore from cache
return true;
}
+ /**
+ * Save user data to the shared cache
+ */
+ function saveToCache() {
+ $this->load();
+ $this->loadGroups();
+ if ( $this->isAnon() ) {
+ // Anonymous users are uncached
+ return;
+ }
+ $data = array();
+ foreach ( self::$mCacheVars as $name ) {
+ $data[$name] = $this->$name;
+ }
+ $data['mVersion'] = MW_USER_VERSION;
+ $key = wfMemcKey( 'user', 'id', $this->mId );
+ global $wgMemc;
+ $wgMemc->set( $key, $data );
+ }
+
/**
* Static factory method for creation from username.
*
* This is slightly less efficient than newFromId(), so use newFromId() if
- * you have both an ID and a name handy.
+ * you have both an ID and a name handy.
*
* @param string $name Username, validated by Title:newFromText()
- * @param mixed $validate Validate username. Takes the same parameters as
- * User::getCanonicalName(), except that true is accepted as an alias
+ * @param mixed $validate Validate username. Takes the same parameters as
+ * User::getCanonicalName(), except that true is accepted as an alias
* for 'valid', for BC.
- *
- * @return User object, or null if the username is invalid. If the username
+ *
+ * @return User object, or null if the username is invalid. If the username
* is not present in the database, the result will be a user object with
- * a name, zero user ID and default settings.
+ * a name, zero user ID and default settings.
* @static
*/
static function newFromName( $name, $validate = 'valid' ) {
return null;
}
}
-
+
/**
* Create a new user object using data from session or cookies. If the
* login credentials are invalid, the result is an anonymous user.
return $user;
}
+ /**
+ * Create a new user object from a user row.
+ * The row should have all fields from the user table in it.
+ */
+ static function newFromRow( $row ) {
+ $user = new User;
+ $user->loadFromRow( $row );
+ return $user;
+ }
+
/**
* Get username given an id.
* @param integer $id Database user id
}
/**
- * Get real username given an id.
- * @param integer $id Database user id
- * @return string Realname of a user
- * @static
+ * Get the real name of a user given their identifier
+ *
+ * @param int $id Database user id
+ * @return string Real name of a user
*/
static function whoIsReal( $id ) {
$dbr = wfGetDB( DB_SLAVE );
- return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
+ return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
}
/**
*
* 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
+ * 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
* Check if $name is an IPv6 IP.
*/
static function isIPv6($name) {
- /*
- * if it has any non-valid characters, it can't be a valid IPv6
+ /*
+ * if it has any non-valid characters, it can't be a valid IPv6
* address.
*/
if (preg_match("/[^:a-fA-F0-9]/", $name))
|| User::isIP( $name )
|| strpos( $name, '/' ) !== false
|| strlen( $name ) > $wgMaxNameChars
- || $name != $wgContLang->ucfirst( $name ) )
+ || $name != $wgContLang->ucfirst( $name ) ) {
+ wfDebugLog( 'username', __METHOD__ .
+ ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
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 );
if( is_null( $parsed )
|| $parsed->getNamespace()
- || strcmp( $name, $parsed->getPrefixedText() ) )
+ || strcmp( $name, $parsed->getPrefixedText() ) ) {
+ wfDebugLog( 'username', __METHOD__ .
+ ": '$name' invalid due to ambiguous prefixes" );
return false;
-
+ }
+
// Check an additional blacklist of troublemaker characters.
// Should these be merged into the title char list?
$unicodeBlacklist = '/[' .
'\x{e000}-\x{f8ff}' . # private use
']/u';
if( preg_match( $unicodeBlacklist, $name ) ) {
+ wfDebugLog( 'username', __METHOD__ .
+ ": '$name' invalid due to blacklisted characters" );
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
static function isUsableName( $name ) {
global $wgReservedUsernames;
return
- // Must be a usable username, obviously ;)
+ // Must be a valid 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
static function isCreatableName( $name ) {
return
self::isUsableName( $name ) &&
-
+
// Registration-time character blacklisting...
strpos( $name, '@' ) === false;
}
/**
- * Is the input a valid password?
+ * Is the input a valid password for this user?
*
- * @param string $password
+ * @param string $password Desired password
* @return bool
- * @static
*/
- static function isValidPassword( $password ) {
- global $wgMinimalPasswordLength;
+ function isValidPassword( $password ) {
+ global $wgMinimalPasswordLength, $wgContLang;
$result = null;
- if( !wfRunHooks( 'isValidPassword', array( $password, &$result ) ) ) return $result;
- if ($result === false) return false;
- return (strlen( $password ) >= $wgMinimalPasswordLength);
+ if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
+ return $result;
+ if( $result === false )
+ return false;
+
+ // Password needs to be long enough, and can't be the same as the username
+ return strlen( $password ) >= $wgMinimalPasswordLength
+ && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
}
/**
- * Does the string match roughly an email address ?
+ * Does a string look like an email address?
*
* There used to be a regular expression here, it got removed because it
* rejected valid addresses. Actually just check if there is '@' somewhere
* @todo Check for RFC 2822 compilance (bug 959)
*
* @param string $addr email address
- * @static
* @return bool
*/
- static function isValidEmailAddr ( $addr ) {
- return ( trim( $addr ) != '' ) &&
- (false !== strpos( $addr, '@' ) );
+ public static function isValidEmailAddr( $addr ) {
+ $result = null;
+ if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
+ return $result;
+ }
+
+ return strpos( $addr, '@' ) !== false;
}
/**
- * Given unvalidated user input, return a canonical username, or false if
+ * Given unvalidated user input, return a canonical username, or false if
* the username is invalid.
* @param string $name
* @param mixed $validate Type of validation to use:
global $wgContLang;
$name = $wgContLang->ucfirst( $name );
+ # Reject names containing '#'; these will be cleaned up
+ # with title normalisation, but then it's too late to
+ # check elsewhere
+ if( strpos( $name, '#' ) !== false )
+ return false;
+
# Clean up name according to title rules
$t = Title::newFromText( $name );
if( is_null( $t ) ) {
* Count the number of edits of a user
*
* It should not be static and some day should be merged as proper member function / deprecated -- domas
- *
+ *
* @param int $uid The user ID to check
* @return int
* @static
);
if( $field === null ) { // it has not been initialized. do so.
- $dbw = wfGetDb( DB_MASTER );
+ $dbw = wfGetDB( DB_MASTER );
$count = $dbr->selectField(
'revision', 'count(*)',
array( 'rev_user' => $uid ),
}
/**
- * Set cached properties to default. Note: this no longer clears
+ * Set cached properties to default. Note: this no longer clears
* uncached lazy-initialised properties. The constructor does that instead.
*
* @private
wfProfileOut( __METHOD__ );
}
-
+
/**
* Initialise php session
* @deprecated use wfSetupSession()
*/
function SetupSession() {
+ wfDeprecated( __METHOD__ );
wfSetupSession();
}
* Load user data from the session or login cookie. If there are no valid
* credentials, initialises the user as an anon.
* @return true if the user is logged in, false otherwise
- *
- * @private
*/
- function loadFromSession() {
+ private function loadFromSession() {
global $wgMemc, $wgCookiePrefix;
+ $result = null;
+ wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
+ if ( $result !== null ) {
+ return $result;
+ }
+
if ( isset( $_SESSION['wsUserID'] ) ) {
if ( 0 != $_SESSION['wsUserID'] ) {
$sId = $_SESSION['wsUserID'];
# Not a valid ID, loadFromId has switched the object to anon for us
return false;
}
-
+
if ( isset( $_SESSION['wsToken'] ) ) {
$passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
$from = 'session';
}
if ( ( $sName == $this->mName ) && $passwordCorrect ) {
+ $_SESSION['wsToken'] = $this->mToken;
wfDebug( "Logged in from $from\n" );
return true;
} else {
return false;
}
}
-
+
/**
* Load user and user_group data from the database
* $this->mId must be set, this is how the user is identified.
- *
+ *
* @return true if the user exists, false if the user is anonymous
* @private
*/
if ( $s !== false ) {
# Initialise user table data
- $this->mName = $s->user_name;
- $this->mRealName = $s->user_real_name;
- $this->mPassword = $s->user_password;
- $this->mNewpassword = $s->user_newpassword;
- $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
- $this->mEmail = $s->user_email;
- $this->decodeOptions( $s->user_options );
- $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
- $this->mToken = $s->user_token;
- $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
- $this->mEmailToken = $s->user_email_token;
- $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
- $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
- $this->mEditCount = $s->user_editcount;
+ $this->loadFromRow( $s );
+ $this->mGroups = null; // deferred
$this->getEditCount(); // revalidation for nulls
+ return true;
+ } else {
+ # Invalid user_id
+ $this->mId = 0;
+ $this->loadDefaults();
+ return false;
+ }
+ }
- # Load group data
+ /**
+ * Initialise the user object from a row from the user table
+ */
+ function loadFromRow( $row ) {
+ $this->mDataLoaded = true;
+
+ if ( isset( $row->user_id ) ) {
+ $this->mId = $row->user_id;
+ }
+ $this->mName = $row->user_name;
+ $this->mRealName = $row->user_real_name;
+ $this->mPassword = $row->user_password;
+ $this->mNewpassword = $row->user_newpassword;
+ $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
+ $this->mEmail = $row->user_email;
+ $this->decodeOptions( $row->user_options );
+ $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
+ $this->mToken = $row->user_token;
+ $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
+ $this->mEmailToken = $row->user_email_token;
+ $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
+ $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
+ $this->mEditCount = $row->user_editcount;
+ }
+
+ /**
+ * Load the groups from the database if they aren't already loaded
+ * @private
+ */
+ function loadGroups() {
+ if ( is_null( $this->mGroups ) ) {
+ $dbr = wfGetDB( DB_MASTER );
$res = $dbr->select( 'user_groups',
array( 'ug_group' ),
array( 'ug_user' => $this->mId ),
while( $row = $dbr->fetchObject( $res ) ) {
$this->mGroups[] = $row->ug_group;
}
- return true;
- } else {
- # Invalid user_id
- $this->mId = 0;
- $this->loadDefaults();
- return false;
}
}
/**
- * Clear various cached data stored in this object.
- * @param string $reloadFrom Reload user and user_groups table data from a
- * given source. May be "name", "id", "defaults", "session" or false for
+ * Clear various cached data stored in this object.
+ * @param string $reloadFrom Reload user and user_groups table data from a
+ * given source. May be "name", "id", "defaults", "session" or false for
* no reload.
*/
function clearInstanceCache( $reloadFrom = false ) {
wfProfileIn( __METHOD__ );
wfDebug( __METHOD__.": checking...\n" );
- $this->mBlockedby = 0;
+ // Initialize data...
+ // Otherwise something ends up stomping on $this->mBlockedby when
+ // things get lazy-loaded later, causing false positive block hits
+ // due to -1 !== 0. Probably session-related... Nothing should be
+ // overwriting mBlockedby, surely?
+ $this->load();
+
+ $this->mBlockedby = 0;
$this->mHideName = 0;
$ip = wfGetIP();
$found = false;
$host = '';
-
+ // FIXME: IPv6 ???
$m = array();
if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
# Make hostname
*/
public function isPingLimitable() {
global $wgRateLimitsExcludedGroups;
- return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) != array();
+ return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
}
/**
return $result;
}
- global $wgRateLimits, $wgRateLimitsExcludedGroups;
+ global $wgRateLimits;
if( !isset( $wgRateLimits[$action] ) ) {
return false;
}
$keys = array();
$id = $this->getId();
$ip = wfGetIP();
+ $userLimit = false;
if( isset( $limits['anon'] ) && $id == 0 ) {
$keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
}
if( isset( $limits['user'] ) && $id != 0 ) {
- $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
+ $userLimit = $limits['user'];
}
if( $this->isNewbie() ) {
if( isset( $limits['newbie'] ) && $id != 0 ) {
$keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
}
}
+ // Check for group-specific permissions
+ // If more than one group applies, use the group with the highest limit
+ foreach ( $this->getGroups() as $group ) {
+ if ( isset( $limits[$group] ) ) {
+ if ( $userLimit === false || $limits[$group] > $userLimit ) {
+ $userLimit = $limits[$group];
+ }
+ }
+ }
+ // Set the user limit key
+ if ( $userLimit !== false ) {
+ wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
+ $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
+ }
$triggered = false;
foreach( $keys as $key => $limit ) {
/**
* Get the user ID. Returns 0 if the user is anonymous or nonexistent.
*/
- function getID() {
- $this->load();
- return $this->mId;
+ function getId() {
+ if( $this->mId === null and $this->mName !== null
+ and User::isIP( $this->mName ) ) {
+ // Special case, we know the user is anonymous
+ return 0;
+ } elseif( $this->mId === null ) {
+ // Don't load if this was initialized from an ID
+ $this->load();
+ }
+ return $this->mId;
}
/**
* Set the user and reload all fields according to that ID
- * @deprecated use User::newFromId()
*/
- function setID( $v ) {
+ function setId( $v ) {
$this->mId = $v;
$this->clearInstanceCache( 'id' );
}
} else {
$this->load();
if ( $this->mName === false ) {
- $this->mName = wfGetIP();
+ # Clean up IPs
+ $this->mName = IP::sanitizeIP( wfGetIP() );
}
- # Clean up IPs
- return IP::sanitizeIP($this->mName);
+ return $this->mName;
}
}
/**
- * Set the user name.
+ * Set the user name.
*
- * This does not reload fields from the database according to the given
+ * This does not reload fields from the database according to the given
* name. Rather, it is used to create a temporary "nonexistent user" for
- * later addition to the database. It can also be used to set the IP
- * address for an anonymous user to something other than the current
+ * later addition to the database. It can also be used to set the IP
+ * address for an anonymous user to something other than the current
* remote IP.
*
* User::newFromName() has rougly the same function, when the named user
global $wgMemc;
$key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
$newtalk = $wgMemc->get( $key );
- if( $newtalk != "" ) {
+ if( strval( $newtalk ) !== '' ) {
$this->mNewtalk = (bool)$newtalk;
} else {
- $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
- $wgMemc->set( $key, (int)$this->mNewtalk, time() + 1800 );
+ // Since we are caching this, make sure it is up to date by getting it
+ // from the master
+ $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
+ $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
}
} else {
$this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
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
- * damn annoying.
+ * Perform a user_newtalk check, uncached.
+ * Use getNewtalk for a cached check.
*
* @param string $field
* @param mixed $id
+ * @param bool $fromMaster True to fetch from the master, false for a slave
* @return bool
* @private
*/
- function checkNewtalk( $field, $id ) {
- $dbr = wfGetDB( DB_SLAVE );
- $ok = $dbr->selectField( 'user_newtalk', $field,
+ function checkNewtalk( $field, $id, $fromMaster = false ) {
+ if ( $fromMaster ) {
+ $db = wfGetDB( DB_MASTER );
+ } else {
+ $db = wfGetDB( DB_SLAVE );
+ }
+ $ok = $db->selectField( 'user_newtalk', $field,
array( $field => $id ), __METHOD__ );
return $ok !== false;
}
* @private
*/
function updateNewtalk( $field, $id ) {
- if( $this->checkNewtalk( $field, $id ) ) {
- wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
- return false;
- }
$dbw = wfGetDB( DB_MASTER );
$dbw->insert( 'user_newtalk',
array( $field => $id ),
__METHOD__,
'IGNORE' );
- wfDebug( __METHOD__.": set on ($field, $id)\n" );
- return true;
+ if ( $dbw->affectedRows() ) {
+ wfDebug( __METHOD__.": set on ($field, $id)\n" );
+ return true;
+ } else {
+ wfDebug( __METHOD__." already set ($field, $id)\n" );
+ return false;
+ }
}
/**
* @private
*/
function deleteNewtalk( $field, $id ) {
- if( !$this->checkNewtalk( $field, $id ) ) {
- wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
- return false;
- }
$dbw = wfGetDB( DB_MASTER );
$dbw->delete( 'user_newtalk',
array( $field => $id ),
__METHOD__ );
- wfDebug( __METHOD__.": killed on ($field, $id)\n" );
- return true;
+ if ( $dbw->affectedRows() ) {
+ wfDebug( __METHOD__.": killed on ($field, $id)\n" );
+ return true;
+ } else {
+ wfDebug( __METHOD__.": already gone ($field, $id)\n" );
+ return false;
+ }
}
/**
$field = 'user_id';
$id = $this->getId();
}
+ global $wgMemc;
if( $val ) {
$changed = $this->updateNewtalk( $field, $id );
$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 $wgMemc;
- $key = wfMemcKey( 'newtalk', 'ip', $val );
- $wgMemc->set( $key, $val ? 1 : 0 );
- } else {
- if( $val ) {
- // Make sure the user page is watched, so a notification
- // will be sent out if enabled.
- $this->addWatch( $this->getTalkPage() );
- }
- }
+ if( $this->isAnon() ) {
+ // Anons have a separate memcached space, since
+ // user records aren't kept for them.
+ $key = wfMemcKey( 'newtalk', 'ip', $id );
+ $wgMemc->set( $key, $val ? 1 : 0, 1800 );
+ }
+ if ( $changed ) {
$this->invalidateCache();
}
}
-
+
/**
* Generate a current or new-future timestamp to be stored in the
* user_touched field when we update things.
global $wgClockSkewFudge;
return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
}
-
+
/**
* Clear user data from memcached.
* Use after applying fun updates to the database; caller's
$this->load();
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->clearSharedCache();
}
}
/**
* Encrypt a password.
- * It can eventuall salt a password @see User::addSalt()
+ * It can eventually salt a password.
+ * @see User::addSalt()
* @param string $p clear Password.
* @return string Encrypted password.
*/
*/
function setPassword( $str ) {
global $wgAuth;
-
+
if( $str !== null ) {
if( !$wgAuth->allowPasswordChange() ) {
throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
}
-
+
if( !$this->isValidPassword( $str ) ) {
global $wgMinimalPasswordLength;
throw new PasswordError( wfMsg( 'passwordtooshort',
if( !$wgAuth->setPassword( $this, $str ) ) {
throw new PasswordError( wfMsg( 'externaldberror' ) );
}
-
+
$this->setInternalPassword( $str );
return true;
function setInternalPassword( $str ) {
$this->load();
$this->setToken();
-
+
if( $str === null ) {
// Save an invalid hash...
$this->mPassword = '';
$expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
return time() < $expiry;
}
-
+
function getEmail() {
$this->load();
+ wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
return $this->mEmail;
}
function getEmailAuthenticationTimestamp() {
$this->load();
+ wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
return $this->mEmailAuthenticated;
}
function setEmail( $str ) {
$this->load();
$this->mEmail = $str;
+ wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
}
function getRealName() {
}
/**
- * Get the user's date preference, including some important migration for
+ * Get the user's date preference, including some important migration for
* old user rows.
*/
function getDatePreference() {
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
}
// 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 );
+ if( $val ) {
+ $val = str_replace( "\r\n", "\n", $val );
+ $val = str_replace( "\r", "\n", $val );
+ $val = str_replace( "\n", " ", $val );
+ }
+ // Explicitly NULL values should refer to defaults
+ global $wgDefaultUserOptions;
+ if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
+ $val = $wgDefaultUserOptions[$oname];
+ }
$this->mOptions[$oname] = $val;
}
function getRights() {
if ( is_null( $this->mRights ) ) {
$this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
+ wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
+ // Force reindexation of rights when a hook has unset one of them
+ $this->mRights = array_values( $this->mRights );
}
return $this->mRights;
}
/**
* Get the list of implicit group memberships this user has.
- * This includes all explicit groups, plus 'user' if logged in
- * and '*' for all accounts.
+ * This includes all explicit groups, plus 'user' if logged in,
+ * '*' for all accounts and autopromoted groups
* @param boolean $recache Don't use the cache
* @return array of strings
*/
function getEffectiveGroups( $recache = false ) {
if ( $recache || is_null( $this->mEffectiveGroups ) ) {
- $this->load();
- $this->mEffectiveGroups = $this->mGroups;
+ $this->mEffectiveGroups = $this->getGroups();
$this->mEffectiveGroups[] = '*';
- if( $this->mId ) {
+ if( $this->getId() ) {
$this->mEffectiveGroups[] = 'user';
-
- global $wgAutoConfirmAge, $wgAutoConfirmCount;
- $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
- if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
- $this->mEffectiveGroups[] = 'autoconfirmed';
- }
- # Implicit group for users whose email addresses are confirmed
- global $wgEmailAuthentication;
- if( self::isValidEmailAddr( $this->mEmail ) ) {
- if( $wgEmailAuthentication ) {
- if( $this->mEmailAuthenticated )
- $this->mEffectiveGroups[] = 'emailconfirmed';
- } else {
- $this->mEffectiveGroups[] = 'emailconfirmed';
- }
- }
+ $this->mEffectiveGroups = array_unique( array_merge(
+ $this->mEffectiveGroups,
+ Autopromote::getAutopromoteGroups( $this )
+ ) );
+
+ # Hook for additional groups
+ wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
}
}
return $this->mEffectiveGroups;
}
-
+
/* Return the edit count for the user. This is where User::edits should have been */
function getEditCount() {
if ($this->mId) {
if ( !isset( $this->mEditCount ) ) {
/* Populate the count, if it has not been populated yet */
$this->mEditCount = User::edits($this->mId);
- }
+ }
return $this->mEditCount;
} else {
/* nil */
return null;
}
}
-
+
/**
* Add the user to the given group.
* This takes immediate effect.
* @param string $group
*/
function addGroup( $group ) {
- $this->load();
$dbw = wfGetDB( DB_MASTER );
if( $this->getId() ) {
$dbw->insert( 'user_groups',
array( 'IGNORE' ) );
}
+ $this->loadGroups();
$this->mGroups[] = $group;
$this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
),
'User::removeGroup' );
+ $this->loadGroups();
$this->mGroups = array_diff( $this->mGroups, array( $group ) );
$this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
* @return bool
*/
function isLoggedIn() {
- return( $this->getID() != 0 );
+ return $this->getID() != 0;
}
/**
* @deprecated
*/
function isBot() {
+ wfDeprecated( __METHOD__ );
return $this->isAllowed( 'bot' );
}
return in_array( $action, $this->getRights() );
}
+ /**
+ * Check whether to enable recent changes patrol features for this user
+ * @return bool
+ */
+ public function useRCPatrol() {
+ global $wgUseRCPatrol;
+ return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
+ }
+
+ /**
+ * Check whether to enable recent changes patrol features for this user
+ * @return bool
+ */
+ public function useNPPatrol() {
+ global $wgUseRCPatrol, $wgUseNPPatrol;
+ return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
+ }
+
/**
* Load a skin if it doesn't exist or return it
* @todo FIXME : need to check the old failback system [AV]
* the next change of the page if it's watched etc.
*/
function clearNotification( &$title ) {
- global $wgUser, $wgUseEnotif;
+ global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
# Do nothing if the database is locked to writes
if( wfReadOnly() ) {
$this->setNewtalk( false );
}
- if( !$wgUseEnotif ) {
+ if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
return;
}
$title->getText() == $wgUser->getName())
{
$watched = true;
- } elseif ( $this->getID() == $wgUser->getID() ) {
+ } elseif ( $this->getId() == $wgUser->getId() ) {
$watched = $title->userIsWatching();
} else {
$watched = true;
* @public
*/
function clearAllNotifications( $currentUser ) {
- global $wgUseEnotif;
- if ( !$wgUseEnotif ) {
+ global $wgUseEnotif, $wgShowUpdatedMarker;
+ if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
$this->setNewtalk( false );
return;
}
if( $currentUser != 0 ) {
-
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'watchlist',
array( /* SET */
'wl_notificationtimestamp' => NULL
), array( /* WHERE */
'wl_user' => $currentUser
- ), 'UserMailer::clearAll'
+ ), __METHOD__
);
-
- # we also need to clear here the "you have new message" notification for the own user_talk page
+ # We also need to clear here the "you have new message" notification for the own user_talk page
# This is cleared one page view later in Article::viewUpdates();
}
}
}
}
}
+
+ protected function setCookie( $name, $value, $exp=0 ) {
+ global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
+ if( $exp == 0 ) {
+ $exp = time() + $wgCookieExpiration;
+ }
+ $httpOnlySafe = wfHttpOnlySafe();
+ wfDebugLog( 'cookie',
+ 'setcookie: "' . implode( '", "',
+ array(
+ $wgCookiePrefix . $name,
+ $value,
+ $exp,
+ '/',
+ $wgCookieDomain,
+ $wgCookieSecure,
+ $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
+ if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
+ setcookie( $wgCookiePrefix . $name,
+ $value,
+ $exp,
+ '/',
+ $wgCookieDomain,
+ $wgCookieSecure,
+ $wgCookieHttpOnly );
+ } else {
+ // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
+ // stab stab!
+ setcookie( $wgCookiePrefix . $name,
+ $value,
+ $exp,
+ '/',
+ $wgCookieDomain,
+ $wgCookieSecure );
+ }
+ }
+
+ protected function clearCookie( $name ) {
+ $this->setCookie( $name, '', time() - 86400 );
+ }
function setCookies() {
- global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
$this->load();
if ( 0 == $this->mId ) return;
- $exp = time() + $wgCookieExpiration;
-
+
$_SESSION['wsUserID'] = $this->mId;
- setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+
+ $this->setCookie( 'UserID', $this->mId );
+ $this->setCookie( 'UserName', $this->getName() );
$_SESSION['wsUserName'] = $this->getName();
- setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
$_SESSION['wsToken'] = $this->mToken;
if ( 1 == $this->getOption( 'rememberpassword' ) ) {
- setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+ $this->setCookie( 'Token', $this->mToken );
} else {
- setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
+ $this->clearCookie( 'Token' );
}
}
/**
- * Logout user
- * Clears the cookies and session, resets the instance cache
+ * Logout user.
*/
function logout() {
- global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
+ global $wgUser;
+ if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
+ $this->doLogout();
+ }
+ }
+
+ /**
+ * Really logout user
+ * Clears the cookies and session, resets the instance cache
+ */
+ function doLogout() {
$this->clearInstanceCache( 'defaults' );
$_SESSION['wsUserID'] = 0;
- setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
- setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+ $this->clearCookie( 'UserID' );
+ $this->clearCookie( 'Token' );
# Remember when user logged out, to prevent seeing cached pages
- setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+ $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
}
/**
$this->load();
if ( wfReadOnly() ) { return; }
if ( 0 == $this->mId ) { return; }
-
+
$this->mTouched = self::newTouchedTimestamp();
$dbw = wfGetDB( DB_MASTER );
'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
'user_options' => $this->encodeOptions(),
'user_touched' => $dbw->timestamp($this->mTouched),
- 'user_token' => $this->mToken
+ 'user_token' => $this->mToken,
+ 'user_email_token' => $this->mEmailToken,
+ 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
), array( /* WHERE */
'user_id' => $this->mId
), __METHOD__
);
+ wfRunHooks( 'UserSaveSettings', array( $this ) );
$this->clearSharedCache();
}
-
/**
- * Checks if a user with the given name exists, returns the ID
+ * Checks if a user with the given name exists, returns the ID.
*/
function idForName() {
$s = trim( $this->getName() );
- if ( 0 == strcmp( '', $s ) ) return 0;
+ if ( $s === '' ) return 0;
$dbr = wfGetDB( DB_SLAVE );
$id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
}
return $newUser;
}
-
+
/**
* Add an existing user object to the database
*/
// extra options or other effects on the parser cache.
wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
+ // Make it a valid memcached key fragment
+ $confstr = str_replace( ' ', '_', $confstr );
$this->mHash = $confstr;
return $confstr;
}
return $this->mBlock && $this->mBlock->mCreateAccount;
}
+ /**
+ * Determine if the user is blocked from using Special:Emailuser.
+ *
+ * @public
+ * @return boolean
+ */
+ function isBlockedFromEmailuser() {
+ $this->getBlockedStatus();
+ return $this->mBlock && $this->mBlock->mBlockEmail;
+ }
+
function isAllowedToCreateAccount() {
return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
}
/**
* @deprecated
*/
- function setLoaded( $loaded ) {}
+ function setLoaded( $loaded ) {
+ wfDeprecated( __METHOD__ );
+ }
/**
* Get this user's personal page title.
} elseif( $wgAuth->strict() ) {
/* Auth plugin doesn't allow local authentication */
return false;
+ } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
+ /* Auth plugin doesn't allow local authentication for this user name */
+ return false;
}
$ep = $this->encryptPassword( $password );
if ( 0 == strcmp( $ep, $this->mPassword ) ) {
}
return false;
}
-
+
/**
* Check if the given clear-text password matches the temporary password
* sent by e-mail for password reset operations.
* @public
*/
function editToken( $salt = '' ) {
- if( !isset( $_SESSION['wsEditToken'] ) ) {
- $token = $this->generateToken();
- $_SESSION['wsEditToken'] = $token;
+ if ( $this->isAnon() ) {
+ return EDIT_TOKEN_SUFFIX;
} else {
- $token = $_SESSION['wsEditToken'];
- }
- if( is_array( $salt ) ) {
- $salt = implode( '|', $salt );
+ if( !isset( $_SESSION['wsEditToken'] ) ) {
+ $token = $this->generateToken();
+ $_SESSION['wsEditToken'] = $token;
+ } else {
+ $token = $_SESSION['wsEditToken'];
+ }
+ if( is_array( $salt ) ) {
+ $salt = implode( '|', $salt );
+ }
+ return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
}
- return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
}
/**
* @public
*/
function matchEditToken( $val, $salt = '' ) {
- global $wgMemc;
$sessionToken = $this->editToken( $salt );
if ( $val != $sessionToken ) {
wfDebug( "User::matchEditToken: broken session data\n" );
}
/**
- * Generate a new e-mail confirmation token and send a confirmation
+ * Check whether the edit token is fine except for the suffix
+ */
+ function matchEditTokenNoSuffix( $val, $salt = '' ) {
+ $sessionToken = $this->editToken( $salt );
+ return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
+ }
+
+ /**
+ * Generate a new e-mail confirmation token and send a confirmation/invalidation
* mail to the user's given address.
*
+ * Calls saveSettings() internally; as it has side effects, not committing changes
+ * would be pretty silly.
+ *
* @return mixed True on success, a WikiError object on failure.
*/
function sendConfirmationMail() {
- global $wgContLang;
+ global $wgLang;
$expiration = null; // gets passed-by-ref and defined in next line.
- $url = $this->confirmationTokenUrl( $expiration );
+ $token = $this->confirmationToken( $expiration );
+ $url = $this->confirmationTokenUrl( $token );
+ $invalidateURL = $this->invalidationTokenUrl( $token );
+ $this->saveSettings();
+
return $this->sendMail( wfMsg( 'confirmemail_subject' ),
wfMsg( 'confirmemail_body',
wfGetIP(),
$this->getName(),
$url,
- $wgContLang->timeanddate( $expiration, false ) ) );
+ $wgLang->timeanddate( $expiration, false ),
+ $invalidateURL ) );
}
/**
*
* @param string $subject
* @param string $body
- * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
+ * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
* @return mixed True on success, a WikiError object on failure.
*/
- function sendMail( $subject, $body, $from = null ) {
+ function sendMail( $subject, $body, $from = null, $replyto = null ) {
if( is_null( $from ) ) {
global $wgPasswordSender;
$from = $wgPasswordSender;
}
- require_once( 'UserMailer.php' );
$to = new MailAddress( $this );
$sender = new MailAddress( $from );
- $error = userMailer( $to, $sender, $subject, $body );
-
- if( $error == '' ) {
- return true;
- } else {
- return new WikiError( $error );
- }
+ return UserMailer::send( $to, $sender, $subject, $body, $replyto );
}
/**
* Generate, store, and return a new e-mail confirmation code.
* A hash (unsalted since it's used as a key) is stored.
+ *
+ * Call saveSettings() after calling this function to commit
+ * this change to the database.
+ *
* @param &$expiration mixed output: accepts the expiration time
* @return string
* @private
$now = time();
$expires = $now + 7 * 24 * 60 * 60;
$expiration = wfTimestamp( TS_MW, $expires );
-
$token = $this->generateToken( $this->mId . $this->mEmail . $expires );
$hash = md5( $token );
-
- $dbw = wfGetDB( DB_MASTER );
- $dbw->update( 'user',
- array( 'user_email_token' => $hash,
- 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
- array( 'user_id' => $this->mId ),
- __METHOD__ );
-
+ $this->load();
+ $this->mEmailToken = $hash;
+ $this->mEmailTokenExpires = $expiration;
return $token;
}
/**
- * Generate and store a new e-mail confirmation token, and return
- * the URL the user can use to confirm.
- * @param &$expiration mixed output: accepts the expiration time
+ * Return a URL the user can use to confirm their email address.
+ * @param $token: accepts the email confirmation token
* @return string
* @private
*/
- function confirmationTokenUrl( &$expiration ) {
- $token = $this->confirmationToken( $expiration );
+ function confirmationTokenUrl( $token ) {
$title = SpecialPage::getTitleFor( 'Confirmemail', $token );
return $title->getFullUrl();
}
+ /**
+ * Return a URL the user can use to invalidate their email address.
+ * @param $token: accepts the email confirmation token
+ * @return string
+ * @private
+ */
+ function invalidationTokenUrl( $token ) {
+ $title = SpecialPage::getTitleFor( 'Invalidateemail', $token );
+ return $title->getFullUrl();
+ }
/**
- * Mark the e-mail address confirmed and save.
+ * Mark the e-mail address confirmed.
+ *
+ * Call saveSettings() after calling this function to commit the change.
*/
function confirmEmail() {
+ $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
+ return true;
+ }
+
+ /**
+ * Invalidate the user's email confirmation, unauthenticate the email
+ * if it was already confirmed.
+ *
+ * Call saveSettings() after calling this function to commit the change.
+ */
+ function invalidateEmail() {
$this->load();
- $this->mEmailAuthenticated = wfTimestampNow();
- $this->saveSettings();
+ $this->mEmailToken = null;
+ $this->mEmailTokenExpires = null;
+ $this->setEmailAuthenticationTimestamp( null );
return true;
}
+ function setEmailAuthenticationTimestamp( $timestamp ) {
+ $this->load();
+ $this->mEmailAuthenticated = $timestamp;
+ wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
+ }
+
/**
* Is this user allowed to send e-mails within limits of current
* site configuration?
* @return bool
*/
function canSendEmail() {
- return $this->isEmailConfirmed();
+ $canSend = $this->isEmailConfirmed();
+ wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
+ return $canSend;
}
/**
* @return bool
*/
function canReceiveEmail() {
- return $this->canSendEmail() && !$this->getOption( 'disablemail' );
+ return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
}
/**
return $confirmed;
}
}
-
+
/**
* Return true if there is an outstanding request for e-mail confirmation.
* @return bool
$this->mEmailTokenExpires > wfTimestamp();
}
+ /**
+ * Get the timestamp of account creation, or false for
+ * non-existent/anonymous user accounts
+ *
+ * @return mixed
+ */
+ public function getRegistration() {
+ return $this->mId > 0
+ ? $this->mRegistration
+ : false;
+ }
+
/**
* @param array $groups list of groups
* @return array list of permission key names for given groups combined
- * @static
*/
static function getGroupPermissions( $groups ) {
global $wgGroupPermissions;
/**
* @param string $group key name
* @return string localized descriptive name for group, if provided
- * @static
*/
static function getGroupName( $group ) {
- MessageCache::loadAllMessages();
+ global $wgMessageCache;
+ $wgMessageCache->loadAllMessages();
$key = "group-$group";
$name = wfMsg( $key );
return $name == '' || wfEmptyMsg( $key, $name )
/**
* @param string $group key name
* @return string localized descriptive name for member of a group, if provided
- * @static
*/
static function getGroupMember( $group ) {
- MessageCache::loadAllMessages();
+ global $wgMessageCache;
+ $wgMessageCache->loadAllMessages();
$key = "group-$group-member";
$name = wfMsg( $key );
return $name == '' || wfEmptyMsg( $key, $name )
/**
* Return the set of defined explicit groups.
- * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
- * groups are not included, as they are defined
- * automatically, not in the database.
+ * The implicit groups (by default *, 'user' and 'autoconfirmed')
+ * are not included, as they are defined automatically,
+ * not in the database.
* @return array
- * @static
*/
static function getAllGroups() {
global $wgGroupPermissions;
return array_diff(
array_keys( $wgGroupPermissions ),
- array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
+ self::getImplicitGroups()
+ );
+ }
+
+ /**
+ * Get a list of all available permissions
+ */
+ static function getAllRights() {
+ if ( self::$mAllRights === false ) {
+ global $wgAvailableRights;
+ if ( count( $wgAvailableRights ) ) {
+ self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
+ } else {
+ self::$mAllRights = self::$mCoreRights;
+ }
+ wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
+ }
+ return self::$mAllRights;
+ }
+
+ /**
+ * Get a list of implicit groups
+ *
+ * @return array
+ */
+ public static function getImplicitGroups() {
+ global $wgImplicitGroups;
+ $groups = $wgImplicitGroups;
+ wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
+ return $groups;
}
/**
* @return mixed
*/
static function getGroupPage( $group ) {
- MessageCache::loadAllMessages();
+ global $wgMessageCache;
+ $wgMessageCache->loadAllMessages();
$page = wfMsgForContent( 'grouppage-' . $group );
if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
$title = Title::newFromText( $page );
return $text;
}
}
-
+
/**
* Increment the user's edit-count field.
* Will have no effect for anonymous users.
array( 'user_editcount=user_editcount+1' ),
array( 'user_id' => $this->getId() ),
__METHOD__ );
-
+
// Lazy initialization check...
if( $dbw->affectedRows() == 0 ) {
// Pull from a slave to be less cruel to servers
'COUNT(rev_user)',
array( 'rev_user' => $this->getId() ),
__METHOD__ );
-
+
// Now here's a goddamn hack...
if( $dbr !== $dbw ) {
// If we actually have a slave server, the count is
// count we just read includes the revision that was
// just added in the working transaction.
}
-
+
$dbw->update( 'user',
array( 'user_editcount' => $count ),
array( 'user_id' => $this->getId() ),
// edit count in user cache too
$this->invalidateCache();
}
+
+ static function getRightDescription( $right ) {
+ global $wgMessageCache;
+ $wgMessageCache->loadAllMessages();
+ $key = "right-$right";
+ $name = wfMsg( $key );
+ return $name == '' || wfEmptyMsg( $key, $name )
+ ? $right
+ : $name;
+ }
}
-
-?>