X-Git-Url: https://git.heureux-cyclage.org/?a=blobdiff_plain;f=includes%2Fuser%2FUser.php;h=ba6bb08a736dc143915a4b35fa025e440a504a1b;hb=e5ef0fd0c6607dd34f6dee69d716b159662a0a34;hp=fa74cb341e3b441d3e50a883eb8be648a085a0df;hpb=c4df9b3143d14f695904fa28c50312134080ef57;p=lhc%2Fweb%2Fwiklou.git diff --git a/includes/user/User.php b/includes/user/User.php index fa74cb341e..f3a3e121f3 100644 --- a/includes/user/User.php +++ b/includes/user/User.php @@ -20,6 +20,9 @@ * @file */ +use MediaWiki\Block\AbstractBlock; +use MediaWiki\Block\DatabaseBlock; +use MediaWiki\Block\SystemBlock; use MediaWiki\MediaWikiServices; use MediaWiki\Session\SessionManager; use MediaWiki\Session\Token; @@ -46,18 +49,20 @@ use Wikimedia\Rdbms\IDatabase; * of the database. */ class User implements IDBAccessObject, UserIdentity { + /** - * @const int Number of characters in user_token field. + * Number of characters required for the user_token field. */ const TOKEN_LENGTH = 32; /** - * @const string An invalid value for user_token + * An invalid string value for the user_token field. */ const INVALID_TOKEN = '*** INVALID ***'; /** - * @const int Serialized record version. + * Version number to tag cached versions of serialized User objects. Should be increased when + * {@link $mCacheVars} or one of it's members changes. */ const VERSION = 13; @@ -104,94 +109,6 @@ class User implements IDBAccessObject, UserIdentity { 'mActorId', ]; - /** - * Array of Strings Core rights. - * Each of these should have a corresponding message of the form - * "right-$right". - * @showinitializer - */ - protected static $mCoreRights = [ - 'apihighlimits', - 'applychangetags', - 'autoconfirmed', - 'autocreateaccount', - 'autopatrol', - 'bigdelete', - 'block', - 'blockemail', - 'bot', - 'browsearchive', - 'changetags', - 'createaccount', - 'createpage', - 'createtalk', - 'delete', - 'deletechangetags', - 'deletedhistory', - 'deletedtext', - 'deletelogentry', - 'deleterevision', - 'edit', - 'editcontentmodel', - 'editinterface', - 'editprotected', - 'editmyoptions', - 'editmyprivateinfo', - 'editmyusercss', - 'editmyuserjson', - 'editmyuserjs', - 'editmywatchlist', - 'editsemiprotected', - 'editsitecss', - 'editsitejson', - 'editsitejs', - 'editusercss', - 'edituserjson', - 'edituserjs', - 'hideuser', - 'import', - 'importupload', - 'ipblock-exempt', - 'managechangetags', - 'markbotedits', - 'mergehistory', - 'minoredit', - 'move', - 'movefile', - 'move-categorypages', - 'move-rootuserpages', - 'move-subpages', - 'nominornewtalk', - 'noratelimit', - 'override-export-depth', - 'pagelang', - 'patrol', - 'patrolmarks', - 'protect', - 'purge', - 'read', - 'reupload', - 'reupload-own', - 'reupload-shared', - 'rollback', - 'sendemail', - 'siteadmin', - 'suppressionlog', - 'suppressredirect', - 'suppressrevision', - 'unblockself', - 'undelete', - 'unwatchedpages', - 'upload', - 'upload_by_url', - 'userrights', - 'userrights-interwiki', - 'viewmyprivateinfo', - 'viewmywatchlist', - 'viewsuppressed', - 'writeapi', - ]; - /** * String Cached results of getAllRights() */ @@ -266,8 +183,6 @@ class User implements IDBAccessObject, UserIdentity { public $mBlockedby; /** @var string */ protected $mHash; - /** @var array */ - public $mRights; /** @var string */ protected $mBlockreason; /** @var array */ @@ -276,7 +191,7 @@ class User implements IDBAccessObject, UserIdentity { protected $mImplicitGroups; /** @var array */ protected $mFormerGroups; - /** @var Block */ + /** @var AbstractBlock */ protected $mGlobalBlock; /** @var bool */ protected $mLocked; @@ -288,13 +203,13 @@ class User implements IDBAccessObject, UserIdentity { /** @var WebRequest */ private $mRequest; - /** @var Block */ + /** @var AbstractBlock */ public $mBlock; /** @var bool */ protected $mAllowUsertalk; - /** @var Block */ + /** @var AbstractBlock */ private $mBlockedFromCreateAccount = false; /** @var int User::READ_* constant bitfield used to load data */ @@ -324,6 +239,24 @@ class User implements IDBAccessObject, UserIdentity { return (string)$this->getName(); } + public function __get( $name ) { + // A shortcut for $mRights deprecation phase + if ( $name === 'mRights' ) { + return $this->getRights(); + } + } + + public function __set( $name, $value ) { + // A shortcut for $mRights deprecation phase, only known legitimate use was for + // testing purposes, other uses seem bad in principle + if ( $name === 'mRights' ) { + MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting( + $this, + is_null( $value ) ? [] : $value + ); + } + } + /** * Test if it's safe to load this User object. * @@ -671,11 +604,20 @@ class User implements IDBAccessObject, UserIdentity { * @param int|null $userId User ID, if known * @param string|null $userName User name, if known * @param int|null $actorId Actor ID, if known + * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none * @return User */ - public static function newFromAnyId( $userId, $userName, $actorId ) { + public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) { global $wgActorTableSchemaMigrationStage; + // Stop-gap solution for the problem described in T222212. + // Force the User ID and Actor ID to zero for users loaded from the database + // of another wiki, to prevent subtle data corruption and confusing failure modes. + if ( $wikiId !== false ) { + $userId = 0; + $actorId = 0; + } + $user = new User; $user->mFrom = 'defaults'; @@ -912,7 +854,7 @@ class User implements IDBAccessObject, UserIdentity { } if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) { - return self::$idCacheByName[$name]; + return is_null( self::$idCacheByName[$name] ) ? null : (int)self::$idCacheByName[$name]; } list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags ); @@ -1149,35 +1091,6 @@ class User implements IDBAccessObject, UserIdentity { return $this->checkPasswordValidity( $password )->isGood(); } - /** - * Given unvalidated password input, return error message on failure. - * - * @param string $password Desired password - * @return bool|string|array True on success, string or array of error message on failure - * @deprecated since 1.33, use checkPasswordValidity - */ - public function getPasswordValidity( $password ) { - wfDeprecated( __METHOD__, '1.33' ); - - $result = $this->checkPasswordValidity( $password ); - if ( $result->isGood() ) { - return true; - } - - $messages = []; - foreach ( $result->getErrorsByType( 'error' ) as $error ) { - $messages[] = $error['message']; - } - foreach ( $result->getErrorsByType( 'warning' ) as $warning ) { - $messages[] = $warning['message']; - } - if ( count( $messages ) === 1 ) { - return $messages[0]; - } - - return $messages; - } - /** * Check if this is a valid password for this user * @@ -1288,17 +1201,6 @@ class User implements IDBAccessObject, UserIdentity { return $name; } - /** - * Return a random password. - * - * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString() - * @return string New random password - */ - public static function randomPassword() { - global $wgMinimalPasswordLength; - return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength ); - } - /** * Set cached properties to default. * @@ -1381,8 +1283,8 @@ class User implements IDBAccessObject, UserIdentity { $user = $session->getUser(); if ( $user->isLoggedIn() ) { $this->loadFromUserObject( $user ); - if ( $user->isBlocked() ) { - // If this user is autoblocked, set a cookie to track the Block. This has to be done on + if ( $user->getBlock() ) { + // If this user is autoblocked, set a cookie to track the block. This has to be done on // every session load, because an autoblocked editor might not edit again from the same // IP address after being blocked. $this->trackBlockWithCookie(); @@ -1405,10 +1307,10 @@ class User implements IDBAccessObject, UserIdentity { public function trackBlockWithCookie() { $block = $this->getBlock(); - if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) { - if ( $block->shouldTrackWithCookie( $this->isAnon() ) ) { - $block->setCookie( $this->getRequest()->response() ); - } + if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null + && $block->shouldTrackWithCookie( $this->isAnon() ) + ) { + $block->setCookie( $this->getRequest()->response() ); } } @@ -1671,11 +1573,11 @@ class User implements IDBAccessObject, UserIdentity { * protected against race conditions using a compare-and-set (CAS) mechanism * based on comparing $this->mTouched with the user_touched field. * - * @param Database $db + * @param IDatabase $db * @param array $conditions WHERE conditions for use with Database::update * @return array WHERE conditions for use with Database::update */ - protected function makeUpdateConditions( Database $db, array $conditions ) { + protected function makeUpdateConditions( IDatabase $db, array $conditions ) { if ( $this->mTouched ) { // CAS check: only update if the row wasn't changed sicne it was loaded. $conditions['user_touched'] = $db->timestamp( $this->mTouched ); @@ -1715,7 +1617,7 @@ class User implements IDBAccessObject, UserIdentity { if ( $success ) { $this->mTouched = $newTouched; - $this->clearSharedCache(); + $this->clearSharedCache( 'changed' ); } else { // Clears on failure too since that is desired if the cache is stale $this->clearSharedCache( 'refresh' ); @@ -1732,11 +1634,12 @@ class User implements IDBAccessObject, UserIdentity { * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload. */ public function clearInstanceCache( $reloadFrom = false ) { + global $wgFullyInitialised; + $this->mNewtalk = -1; $this->mDatePreference = null; $this->mBlockedby = -1; # Unset $this->mHash = false; - $this->mRights = null; $this->mEffectiveGroups = null; $this->mImplicitGroups = null; $this->mGroupMemberships = null; @@ -1744,6 +1647,13 @@ class User implements IDBAccessObject, UserIdentity { $this->mOptionsLoaded = false; $this->mEditCount = null; + // Replacement of former `$this->mRights = null` line + if ( $wgFullyInitialised && $this->mFrom ) { + MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache( + $this + ); + } + if ( $reloadFrom ) { $this->mLoadedItems = []; $this->mFrom = $reloadFrom; @@ -1822,13 +1732,14 @@ class User implements IDBAccessObject, UserIdentity { /** * Get blocking information + * + * TODO: Move this into the BlockManager, along with block-related properties. + * * @param bool $fromReplica Whether to check the replica DB first. * To improve performance, non-critical checks are done against replica DBs. * Check when actually saving should be done against master. */ private function getBlockedStatus( $fromReplica = true ) { - global $wgProxyWhitelist, $wgApplyIpBlocksToXff, $wgSoftBlockRanges; - if ( $this->mBlockedby != -1 ) { return; } @@ -1842,81 +1753,12 @@ class User implements IDBAccessObject, UserIdentity { // overwriting mBlockedby, surely? $this->load(); - # We only need to worry about passing the IP address to the Block generator if the - # user is not immune to autoblocks/hardblocks, and they are the current user so we - # know which IP address they're actually coming from - $ip = null; - $sessionUser = RequestContext::getMain()->getUser(); - // the session user is set up towards the end of Setup.php. Until then, - // assume it's a logged-out user. - $globalUserName = $sessionUser->isSafeToLoad() - ? $sessionUser->getName() - : IP::sanitizeIP( $sessionUser->getRequest()->getIP() ); - if ( $this->getName() === $globalUserName && !$this->isAllowed( 'ipblock-exempt' ) ) { - $ip = $this->getRequest()->getIP(); - } - - // User/IP blocking - $block = Block::newFromTarget( $this, $ip, !$fromReplica ); - - // Cookie blocking - if ( !$block instanceof Block ) { - $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) ); - } - - // Proxy blocking - if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) { - // Local list - if ( self::isLocallyBlockedProxy( $ip ) ) { - $block = new Block( [ - 'byText' => wfMessage( 'proxyblocker' )->text(), - 'reason' => wfMessage( 'proxyblockreason' )->plain(), - 'address' => $ip, - 'systemBlock' => 'proxy', - ] ); - } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) { - $block = new Block( [ - 'byText' => wfMessage( 'sorbs' )->text(), - 'reason' => wfMessage( 'sorbsreason' )->plain(), - 'address' => $ip, - 'systemBlock' => 'dnsbl', - ] ); - } - } - - // (T25343) Apply IP blocks to the contents of XFF headers, if enabled - if ( !$block instanceof Block - && $wgApplyIpBlocksToXff - && $ip !== null - && !in_array( $ip, $wgProxyWhitelist ) - ) { - $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' ); - $xff = array_map( 'trim', explode( ',', $xff ) ); - $xff = array_diff( $xff, [ $ip ] ); - $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$fromReplica ); - $block = Block::chooseBlock( $xffblocks, $xff ); - if ( $block instanceof Block ) { - # Mangle the reason to alert the user that the block - # originated from matching the X-Forwarded-For header. - $block->setReason( wfMessage( 'xffblockreason', $block->getReason() )->plain() ); - } - } - - if ( !$block instanceof Block - && $ip !== null - && $this->isAnon() - && IP::isInRanges( $ip, $wgSoftBlockRanges ) - ) { - $block = new Block( [ - 'address' => $ip, - 'byText' => 'MediaWiki default', - 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(), - 'anonOnly' => true, - 'systemBlock' => 'wgSoftBlockRanges', - ] ); - } + $block = MediaWikiServices::getInstance()->getBlockManager()->getUserBlock( + $this, + $fromReplica + ); - if ( $block instanceof Block ) { + if ( $block instanceof AbstractBlock ) { wfDebug( __METHOD__ . ": Found block.\n" ); $this->mBlock = $block; $this->mBlockedby = $block->getByName(); @@ -1937,82 +1779,30 @@ class User implements IDBAccessObject, UserIdentity { Hooks::run( 'GetBlockedStatus', [ &$thisUser ] ); } - /** - * Try to load a Block from an ID given in a cookie value. - * @param string|null $blockCookieVal The cookie value to check. - * @return Block|bool The Block object, or false if none could be loaded. - */ - protected function getBlockFromCookieValue( $blockCookieVal ) { - // Make sure there's something to check. The cookie value must start with a number. - if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) { - return false; - } - // Load the Block from the ID in the cookie. - $blockCookieId = Block::getIdFromCookieValue( $blockCookieVal ); - if ( $blockCookieId !== null ) { - // An ID was found in the cookie. - $tmpBlock = Block::newFromID( $blockCookieId ); - if ( $tmpBlock instanceof Block ) { - $config = RequestContext::getMain()->getConfig(); - - switch ( $tmpBlock->getType() ) { - case Block::TYPE_USER: - $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking(); - $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true ); - break; - case Block::TYPE_IP: - case Block::TYPE_RANGE: - // If block is type IP or IP range, load only if user is not logged in (T152462) - $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn(); - $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true ); - break; - default: - $blockIsValid = false; - $useBlockCookie = false; - } - - if ( $blockIsValid && $useBlockCookie ) { - // Use the block. - return $tmpBlock; - } - - // If the block is not valid, remove the cookie. - Block::clearCookie( $this->getRequest()->response() ); - } else { - // If the block doesn't exist, remove the cookie. - Block::clearCookie( $this->getRequest()->response() ); - } - } - return false; - } - /** * Whether the given IP is in a DNS blacklist. * + * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted. * @param string $ip IP to check * @param bool $checkWhitelist Whether to check the whitelist first * @return bool True if blacklisted. */ public function isDnsBlacklisted( $ip, $checkWhitelist = false ) { - global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist; - - if ( !$wgEnableDnsBlacklist || - ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) - ) { - return false; - } - - return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls ); + return MediaWikiServices::getInstance()->getBlockManager() + ->isDnsBlacklisted( $ip, $checkWhitelist ); } /** * Whether the given IP is in a given DNS blacklist. * + * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead. * @param string $ip IP to check * @param string|array $bases Array of Strings: URL of the DNS blacklist * @return bool True if blacklisted. */ public function inDnsBlacklist( $ip, $bases ) { + wfDeprecated( __METHOD__, '1.34' ); + $found = false; // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170) if ( IP::isIPv4( $ip ) ) { @@ -2054,11 +1844,13 @@ class User implements IDBAccessObject, UserIdentity { /** * Check if an IP address is in the local proxy list * + * @deprecated since 1.34 Use BlockManager::getUserBlock instead. * @param string $ip - * * @return bool */ public static function isLocallyBlockedProxy( $ip ) { + wfDeprecated( __METHOD__, '1.34' ); + global $wgProxyList; if ( !$wgProxyList ) { @@ -2205,6 +1997,9 @@ class User implements IDBAccessObject, UserIdentity { // Set the user limit key if ( $userLimit !== false ) { + // phan is confused because &can-bypass's value is a bool, so it assumes + // that $userLimit is also a bool here. + // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring list( $max, $period ) = $userLimit; wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" ); $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit; @@ -2236,6 +2031,9 @@ class User implements IDBAccessObject, UserIdentity { $triggered = false; foreach ( $keys as $key => $limit ) { + // phan is confused because &can-bypass's value is a bool, so it assumes + // that $userLimit is also a bool here. + // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring list( $max, $period ) = $limit; $summary = "(limit $max in {$period}s)"; $count = $cache->get( $key ); @@ -2265,12 +2063,16 @@ class User implements IDBAccessObject, UserIdentity { /** * Check if user is blocked * + * @deprecated since 1.34, use User::getBlock() or + * PermissionManager::isBlockedFrom() or + * PermissionManager::userCan() instead. + * * @param bool $fromReplica Whether to check the replica DB instead of * the master. Hacked from false due to horrible probs on site. * @return bool True if blocked, false otherwise */ public function isBlocked( $fromReplica = true ) { - return $this->getBlock( $fromReplica ) instanceof Block && + return $this->getBlock( $fromReplica ) instanceof AbstractBlock && $this->getBlock()->appliesToRight( 'edit' ); } @@ -2278,11 +2080,11 @@ class User implements IDBAccessObject, UserIdentity { * Get the block affecting the user, or null if the user is not blocked * * @param bool $fromReplica Whether to check the replica DB instead of the master - * @return Block|null + * @return AbstractBlock|null */ public function getBlock( $fromReplica = true ) { $this->getBlockedStatus( $fromReplica ); - return $this->mBlock instanceof Block ? $this->mBlock : null; + return $this->mBlock instanceof AbstractBlock ? $this->mBlock : null; } /** @@ -2291,29 +2093,14 @@ class User implements IDBAccessObject, UserIdentity { * @param Title $title Title to check * @param bool $fromReplica Whether to check the replica DB instead of the master * @return bool + * + * @deprecated since 1.33, + * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..) + * */ public function isBlockedFrom( $title, $fromReplica = false ) { - $blocked = $this->isHidden(); - - if ( !$blocked ) { - $block = $this->getBlock( $fromReplica ); - if ( $block ) { - // Special handling for a user's own talk page. The block is not aware - // of the user, so this must be done here. - if ( $title->equals( $this->getTalkPage() ) ) { - $blocked = $block->appliesToUsertalk( $title ); - } else { - $blocked = $block->appliesToTitle( $title ); - } - } - } - - // only for the purpose of the hook. We really don't need this here. - $allowUsertalk = $this->mAllowUsertalk; - - Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] ); - - return $blocked; + return MediaWikiServices::getInstance()->getPermissionManager() + ->isBlockedFrom( $this, $title, $fromReplica ); } /** @@ -2352,7 +2139,7 @@ class User implements IDBAccessObject, UserIdentity { * @return bool True if blocked, false otherwise */ public function isBlockedGlobally( $ip = '' ) { - return $this->getGlobalBlock( $ip ) instanceof Block; + return $this->getGlobalBlock( $ip ) instanceof AbstractBlock; } /** @@ -2361,7 +2148,7 @@ class User implements IDBAccessObject, UserIdentity { * This is intended for quick UI checks. * * @param string $ip IP address, uses current client if none given - * @return Block|null Block object if blocked, null otherwise + * @return AbstractBlock|null Block object if blocked, null otherwise * @throws FatalError * @throws MWException */ @@ -2383,7 +2170,7 @@ class User implements IDBAccessObject, UserIdentity { if ( $blocked && $block === null ) { // back-compat: UserIsBlockedGlobally didn't have $block param first - $block = new Block( [ + $block = new SystemBlock( [ 'address' => $ip, 'systemBlock' => 'global-block' ] ); @@ -2779,29 +2566,26 @@ class User implements IDBAccessObject, UserIdentity { * * Called implicitly from invalidateCache() and saveSettings(). * - * @param string $mode Use 'refresh' to clear now; otherwise before DB commit + * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit */ - public function clearSharedCache( $mode = 'changed' ) { + public function clearSharedCache( $mode = 'refresh' ) { if ( !$this->getId() ) { return; } + $lb = MediaWikiServices::getInstance()->getDBLoadBalancer(); $cache = MediaWikiServices::getInstance()->getMainWANObjectCache(); $key = $this->getCacheKey( $cache ); + if ( $mode === 'refresh' ) { - $cache->delete( $key, 1 ); + $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL } else { - $lb = MediaWikiServices::getInstance()->getDBLoadBalancer(); - if ( $lb->hasOrMadeRecentMasterChanges() ) { - $lb->getConnection( DB_MASTER )->onTransactionPreCommitOrIdle( - function () use ( $cache, $key ) { - $cache->delete( $key ); - }, - __METHOD__ - ); - } else { - $cache->delete( $key ); - } + $lb->getConnection( DB_MASTER )->onTransactionPreCommitOrIdle( + function () use ( $cache, $key ) { + $cache->delete( $key ); + }, + __METHOD__ + ); } } @@ -2812,7 +2596,7 @@ class User implements IDBAccessObject, UserIdentity { */ public function invalidateCache() { $this->touch(); - $this->clearSharedCache(); + $this->clearSharedCache( 'changed' ); } /** @@ -3554,42 +3338,13 @@ class User implements IDBAccessObject, UserIdentity { /** * Get the permissions this user has. * @return string[] permission names + * + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->getUserPermissions(..) instead + * */ public function getRights() { - if ( is_null( $this->mRights ) ) { - $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() ); - Hooks::run( 'UserGetRights', [ $this, &$this->mRights ] ); - - // Deny any rights denied by the user's session, unless this - // endpoint has no sessions. - if ( !defined( 'MW_NO_SESSION' ) ) { - $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights(); - if ( $allowedRights !== null ) { - $this->mRights = array_intersect( $this->mRights, $allowedRights ); - } - } - - Hooks::run( 'UserGetRightsRemove', [ $this, &$this->mRights ] ); - // Force reindexation of rights when a hook has unset one of them - $this->mRights = array_values( array_unique( $this->mRights ) ); - - // If block disables login, we should also remove any - // extra rights blocked users might have, in case the - // blocked user has a pre-existing session (T129738). - // This is checked here for cases where people only call - // $user->isAllowed(). It is also checked in Title::checkUserBlock() - // to give a better error message in the common case. - $config = RequestContext::getMain()->getConfig(); - if ( - $this->isLoggedIn() && - $config->get( 'BlockDisablesLogin' ) && - $this->isBlocked() - ) { - $anon = new User; - $this->mRights = array_intersect( $this->mRights, $anon->getRights() ); - } - } - return $this->mRights; + return MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissions( $this ); } /** @@ -3758,8 +3513,7 @@ class User implements IDBAccessObject, UserIdentity { // Refresh the groups caches, and clear the rights cache so it will be // refreshed on the next call to $this->getRights(). $this->getEffectiveGroups( true ); - $this->mRights = null; - + MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this ); $this->invalidateCache(); return true; @@ -3790,19 +3544,31 @@ class User implements IDBAccessObject, UserIdentity { // Refresh the groups caches, and clear the rights cache so it will be // refreshed on the next call to $this->getRights(). $this->getEffectiveGroups( true ); - $this->mRights = null; - + MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this ); $this->invalidateCache(); return true; } + /** + * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has + * only this new name and not the old isLoggedIn() variant. + * + * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is + * anonymous or has no local account (which can happen when importing). This is equivalent to + * getId() != 0 and is provided for code readability. + * @since 1.34 + */ + public function isRegistered() { + return $this->getId() != 0; + } + /** * Get whether the user is logged in * @return bool */ public function isLoggedIn() { - return $this->getId() != 0; + return $this->isRegistered(); } /** @@ -3810,7 +3576,7 @@ class User implements IDBAccessObject, UserIdentity { * @return bool */ public function isAnon() { - return !$this->isLoggedIn(); + return !$this->isRegistered(); } /** @@ -3861,16 +3627,17 @@ class User implements IDBAccessObject, UserIdentity { /** * Internal mechanics of testing a permission + * + * @deprecated since 1.34, use MediaWikiServices::getInstance() + * ->getPermissionManager()->userHasRight(...) instead + * * @param string $action + * * @return bool */ public function isAllowed( $action = '' ) { - if ( $action === '' ) { - return true; // In the spirit of DWIM - } - // Use strict parameter to avoid matching numeric 0 accidentally inserted - // by misconfiguration: 0 == 'foo' - return in_array( $action, $this->getRights(), true ); + return MediaWikiServices::getInstance()->getPermissionManager() + ->userHasRight( $this, $action ); } /** @@ -4217,7 +3984,7 @@ class User implements IDBAccessObject, UserIdentity { $newTouched = $this->newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); - $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) use ( $newTouched ) { + $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $newTouched ) { global $wgActorTableSchemaMigrationStage; $dbw->update( 'user', @@ -4263,7 +4030,7 @@ class User implements IDBAccessObject, UserIdentity { $this->saveOptions(); Hooks::run( 'UserSaveSettings', [ $this ] ); - $this->clearSharedCache(); + $this->clearSharedCache( 'changed' ); $this->getUserPage()->purgeSquid(); } @@ -4343,7 +4110,7 @@ class User implements IDBAccessObject, UserIdentity { $fields["user_$name"] = $value; } - return $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) use ( $fields ) { + return $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $fields ) { $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] ); if ( $dbw->affectedRows() ) { $newUser = self::newFromId( $dbw->insertId() ); @@ -4397,7 +4164,7 @@ class User implements IDBAccessObject, UserIdentity { $this->mTouched = $this->newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); - $status = $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) { + $status = $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) { $noPass = PasswordFactory::newInvalidPassword()->toString(); $dbw->insert( 'user', [ @@ -4424,10 +4191,8 @@ class User implements IDBAccessObject, UserIdentity { [ 'LOCK IN SHARE MODE' ] ); $loaded = false; - if ( $this->mId ) { - if ( $this->loadFromDatabase( self::READ_LOCKING ) ) { - $loaded = true; - } + if ( $this->mId && $this->loadFromDatabase( self::READ_LOCKING ) ) { + $loaded = true; } if ( !$loaded ) { throw new MWException( $fname . ": hit a key conflict attempting " . @@ -4475,7 +4240,7 @@ class User implements IDBAccessObject, UserIdentity { * @return bool A block was spread */ public function spreadAnyEditBlock() { - if ( $this->isLoggedIn() && $this->isBlocked() ) { + if ( $this->isLoggedIn() && $this->getBlock() ) { return $this->spreadBlock(); } @@ -4494,7 +4259,7 @@ class User implements IDBAccessObject, UserIdentity { return false; } - $userblock = Block::newFromTarget( $this->getName() ); + $userblock = DatabaseBlock::newFromTarget( $this->getName() ); if ( !$userblock ) { return false; } @@ -4504,7 +4269,7 @@ class User implements IDBAccessObject, UserIdentity { /** * Get whether the user is explicitly blocked from account creation. - * @return bool|Block + * @return bool|AbstractBlock */ public function isBlockedFromCreateAccount() { $this->getBlockedStatus(); @@ -4516,9 +4281,11 @@ class User implements IDBAccessObject, UserIdentity { # blocked with createaccount disabled, prevent new account creation there even # when the user is logged in if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) { - $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() ); + $this->mBlockedFromCreateAccount = DatabaseBlock::newFromTarget( + null, $this->getRequest()->getIP() + ); } - return $this->mBlockedFromCreateAccount instanceof Block + return $this->mBlockedFromCreateAccount instanceof AbstractBlock && $this->mBlockedFromCreateAccount->appliesToRight( 'createaccount' ) ? $this->mBlockedFromCreateAccount : false; @@ -5019,45 +4786,27 @@ class User implements IDBAccessObject, UserIdentity { /** * Get the permissions associated with a given list of groups * + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->getGroupPermissions() instead + * * @param array $groups Array of Strings List of internal group names * @return array Array of Strings List of permission key names for given groups combined */ public static function getGroupPermissions( $groups ) { - global $wgGroupPermissions, $wgRevokePermissions; - $rights = []; - // grant every granted permission first - foreach ( $groups as $group ) { - if ( isset( $wgGroupPermissions[$group] ) ) { - $rights = array_merge( $rights, - // array_filter removes empty items - array_keys( array_filter( $wgGroupPermissions[$group] ) ) ); - } - } - // now revoke the revoked permissions - foreach ( $groups as $group ) { - if ( isset( $wgRevokePermissions[$group] ) ) { - $rights = array_diff( $rights, - array_keys( array_filter( $wgRevokePermissions[$group] ) ) ); - } - } - return array_unique( $rights ); + return MediaWikiServices::getInstance()->getPermissionManager()->getGroupPermissions( $groups ); } /** * Get all the groups who have a given permission * + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->getGroupsWithPermission() instead + * * @param string $role Role to check * @return array Array of Strings List of internal group names with the given permission */ public static function getGroupsWithPermission( $role ) { - global $wgGroupPermissions; - $allowedGroups = []; - foreach ( array_keys( $wgGroupPermissions ) as $group ) { - if ( self::groupHasPermission( $group, $role ) ) { - $allowedGroups[] = $group; - } - } - return $allowedGroups; + return MediaWikiServices::getInstance()->getPermissionManager()->getGroupsWithPermission( $role ); } /** @@ -5067,15 +4816,17 @@ class User implements IDBAccessObject, UserIdentity { * User::isEveryoneAllowed() instead. That properly checks if it's revoked * from anyone. * + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->groupHasPermission(..) instead + * * @since 1.21 * @param string $group Group to check * @param string $role Role to check * @return bool */ public static function groupHasPermission( $group, $role ) { - global $wgGroupPermissions, $wgRevokePermissions; - return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role] - && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] ); + return MediaWikiServices::getInstance()->getPermissionManager() + ->groupHasPermission( $group, $role ); } /** @@ -5088,51 +4839,16 @@ class User implements IDBAccessObject, UserIdentity { * Specifically, session-based rights restrictions (such as OAuth or bot * passwords) are applied based on the current session. * - * @since 1.22 + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->isEveryoneAllowed() instead + * * @param string $right Right to check + * * @return bool + * @since 1.22 */ public static function isEveryoneAllowed( $right ) { - global $wgGroupPermissions, $wgRevokePermissions; - static $cache = []; - - // Use the cached results, except in unit tests which rely on - // being able change the permission mid-request - if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) { - return $cache[$right]; - } - - if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) { - $cache[$right] = false; - return false; - } - - // If it's revoked anywhere, then everyone doesn't have it - foreach ( $wgRevokePermissions as $rights ) { - if ( isset( $rights[$right] ) && $rights[$right] ) { - $cache[$right] = false; - return false; - } - } - - // Remove any rights that aren't allowed to the global-session user, - // unless there are no sessions for this endpoint. - if ( !defined( 'MW_NO_SESSION' ) ) { - $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights(); - if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) { - $cache[$right] = false; - return false; - } - } - - // Allow extensions to say false - if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) { - $cache[$right] = false; - return false; - } - - $cache[$right] = true; - return true; + return MediaWikiServices::getInstance()->getPermissionManager()->isEveryoneAllowed( $right ); } /** @@ -5151,19 +4867,14 @@ class User implements IDBAccessObject, UserIdentity { /** * Get a list of all available permissions. + * + * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager() + * ->getAllPermissions() instead + * * @return string[] Array of permission names */ public 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; - } - Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] ); - } - return self::$mAllRights; + return MediaWikiServices::getInstance()->getPermissionManager()->getAllPermissions(); } /** @@ -5177,68 +4888,6 @@ class User implements IDBAccessObject, UserIdentity { return $wgImplicitGroups; } - /** - * Get the title of a page describing a particular group - * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead - * - * @param string $group Internal group name - * @return Title|bool Title of the page if it exists, false otherwise - */ - public static function getGroupPage( $group ) { - wfDeprecated( __METHOD__, '1.29' ); - return UserGroupMembership::getGroupPage( $group ); - } - - /** - * Create a link to the group in HTML, if available; - * else return the group name. - * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or - * make the link yourself if you need custom text - * - * @param string $group Internal name of the group - * @param string $text The text of the link - * @return string HTML link to the group - */ - public static function makeGroupLinkHTML( $group, $text = '' ) { - wfDeprecated( __METHOD__, '1.29' ); - - if ( $text == '' ) { - $text = UserGroupMembership::getGroupName( $group ); - } - $title = UserGroupMembership::getGroupPage( $group ); - if ( $title ) { - return MediaWikiServices::getInstance() - ->getLinkRenderer()->makeLink( $title, $text ); - } - - return htmlspecialchars( $text ); - } - - /** - * Create a link to the group in Wikitext, if available; - * else return the group name. - * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or - * make the link yourself if you need custom text - * - * @param string $group Internal name of the group - * @param string $text The text of the link - * @return string Wikilink to the group - */ - public static function makeGroupLinkWiki( $group, $text = '' ) { - wfDeprecated( __METHOD__, '1.29' ); - - if ( $text == '' ) { - $text = UserGroupMembership::getGroupName( $group ); - } - $title = UserGroupMembership::getGroupPage( $group ); - if ( $title ) { - $page = $title->getFullText(); - return "[[$page|$text]]"; - } - - return $text; - } - /** * Returns an array of the groups that a particular group can add/remove. * @@ -5743,4 +5392,14 @@ class User implements IDBAccessObject, UserIdentity { // XXX it's not clear whether central ID providers are supposed to obey this return $this->getName() === $user->getName(); } + + /** + * Checks if usertalk is allowed + * + * @return bool + */ + public function isAllowUsertalk() { + return $this->mAllowUsertalk; + } + }