<?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.
define( 'EDIT_TOKEN_SUFFIX', '+\\' );
/**
* Thrown by User::setPassword() on error
- * @addtogroup Exception
+ * @ingroup Exception
*/
class PasswordError extends MWException {
// NOP
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;
}
-
$this->saveToCache();
} else {
wfDebug( "Got user {$this->mId} from cache\n" );
*/
function saveToCache() {
$this->load();
+ $this->loadGroups();
if ( $this->isAnon() ) {
// Anonymous users are uncached
return;
* 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
*
* 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
return
// 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;
}
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 );
}
/**
- * 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:
* 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
}
/**
- * 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();
}
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';
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
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() {
+ function getId() {
if( $this->mId === null and $this->mName !== null
and User::isIP( $this->mName ) ) {
// Special case, we know the user is anonymous
/**
* 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' );
}
}
/**
- * 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
return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
}
-
+
/**
- * Perform a user_newtalk check, uncached.
+ * 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
$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();
}
}
*/
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;
}
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;
}
*/
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';
$this->mEffectiveGroups = array_unique( array_merge(
}
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 ) );
* @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_user' => $currentUser
), __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' );
}
}
global $wgUser;
if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
$this->doLogout();
- wfRunHooks( 'UserLogoutComplete', array(&$wgUser) );
}
}
* Clears the cookies and session, resets the instance cache
*/
function doLogout() {
- global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
$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.
*/
}
return $newUser;
}
-
+
/**
* Add an existing user object to the database
*/
/**
* @deprecated
*/
- function setLoaded( $loaded ) {}
+ function setLoaded( $loaded ) {
+ wfDeprecated( __METHOD__ );
+ }
/**
* Get this user's personal page title.
}
return false;
}
-
+
/**
* Check if the given clear-text password matches the temporary password
* sent by e-mail for password reset operations.
}
/**
- * Generate a new e-mail confirmation token and send a confirmation
+ * 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;
$to = new MailAddress( $this );
$sender = new MailAddress( $from );
- $error = UserMailer::send( $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 $confirmed;
}
}
-
+
/**
* Return true if there is an outstanding request for e-mail confirmation.
* @return bool
$this->mEmailToken &&
$this->mEmailTokenExpires > wfTimestamp();
}
-
+
/**
* Get the timestamp of account creation, or false for
* non-existent/anonymous user accounts
/**
* @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 ) {
global $wgMessageCache;
/**
* @param string $group key name
* @return string localized descriptive name for member of a group, if provided
- * @static
*/
static function getGroupMember( $group ) {
global $wgMessageCache;
/**
* 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;
);
}
+ /**
+ * 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 $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;
+ }
}
-
-
-