Merge "watcheditem: Fix bad $options param in NoWriteWatchedItemStore::countWatchersM...
[lhc/web/wiklou.git] / includes / Permissions / PermissionManager.php
index 2d4885e..0a8e515 100644 (file)
@@ -68,7 +68,9 @@ class PermissionManager {
                'BlockDisablesLogin',
                'GroupPermissions',
                'RevokePermissions',
-               'AvailableRights'
+               'AvailableRights',
+               'NamespaceProtection',
+               'RestrictionLevels'
        ];
 
        /** @var ServiceOptions */
@@ -83,8 +85,8 @@ class PermissionManager {
        /** @var NamespaceInfo */
        private $nsInfo;
 
-       /** @var string[] Cached results of getAllRights() */
-       private $allRights = false;
+       /** @var string[]|null Cached results of getAllRights() */
+       private $allRights;
 
        /** @var string[][] Cached user rights */
        private $usersRights = null;
@@ -229,6 +231,25 @@ class PermissionManager {
                return !count( $this->getPermissionErrorsInternal( $action, $user, $page, $rigor, true ) );
        }
 
+       /**
+        * A convenience method for calling PermissionManager::userCan
+        * with PermissionManager::RIGOR_QUICK
+        *
+        * Suitable for use for nonessential UI controls in common cases, but
+        * _not_ for functional access control.
+        * May provide false positives, but should never provide a false negative.
+        *
+        * @see PermissionManager::userCan()
+        *
+        * @param string $action
+        * @param User $user
+        * @param LinkTarget $page
+        * @return bool
+        */
+       public function quickUserCan( $action, User $user, LinkTarget $page ) {
+               return $this->userCan( $action, $user, $page, self::RIGOR_QUICK );
+       }
+
        /**
         * Can $user perform $action on a page?
         *
@@ -827,7 +848,7 @@ class PermissionManager {
         * Check restrictions on cascading pages.
         *
         * @param string $action The action to check
-        * @param User $user User to check
+        * @param UserIdentity $user User to check
         * @param array $errors List of current errors
         * @param string $rigor One of PermissionManager::RIGOR_ constants
         *   - RIGOR_QUICK  : does cheap permission checks from replica DBs (usable for GUI creation)
@@ -841,7 +862,7 @@ class PermissionManager {
         */
        private function checkCascadingSourcesRestrictions(
                $action,
-               User $user,
+               UserIdentity $user,
                $errors,
                $rigor,
                $short,
@@ -870,7 +891,7 @@ class PermissionManager {
                                        if ( $right == 'autoconfirmed' ) {
                                                $right = 'editsemiprotected';
                                        }
-                                       if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
+                                       if ( $right != '' && !$this->userHasAllRights( $user, 'protect', $right ) ) {
                                                $wikiPages = '';
                                                /** @var Title $wikiPage */
                                                foreach ( $cascadingSources as $wikiPage ) {
@@ -982,7 +1003,7 @@ class PermissionManager {
         * Check permissions on special pages & namespaces
         *
         * @param string $action The action to check
-        * @param User $user User to check
+        * @param UserIdentity $user User to check
         * @param array $errors List of current errors
         * @param string $rigor One of PermissionManager::RIGOR_ constants
         *   - RIGOR_QUICK  : does cheap permission checks from replica DBs (usable for GUI creation)
@@ -996,7 +1017,7 @@ class PermissionManager {
         */
        private function checkSpecialsAndNSPermissions(
                $action,
-               User $user,
+               UserIdentity $user,
                $errors,
                $rigor,
                $short,
@@ -1012,7 +1033,7 @@ class PermissionManager {
                }
 
                # Check $wgNamespaceProtection for restricted namespaces
-               if ( $title->isNamespaceProtected( $user ) ) {
+               if ( $this->isNamespaceProtected( $title->getNamespace(), $user ) ) {
                        $ns = $title->getNamespace() == NS_MAIN ?
                                wfMessage( 'nstab-main' )->text() : $title->getNsText();
                        $errors[] = $title->getNamespace() == NS_MEDIAWIKI ?
@@ -1086,7 +1107,7 @@ class PermissionManager {
         * Check CSS/JSON/JS sub-page permissions
         *
         * @param string $action The action to check
-        * @param User $user User to check
+        * @param UserIdentity $user User to check
         * @param array $errors List of current errors
         * @param string $rigor One of PermissionManager::RIGOR_ constants
         *   - RIGOR_QUICK  : does cheap permission checks from replica DBs (usable for GUI creation)
@@ -1100,7 +1121,7 @@ class PermissionManager {
         */
        private function checkUserConfigPermissions(
                $action,
-               User $user,
+               UserIdentity $user,
                $errors,
                $rigor,
                $short,
@@ -1120,22 +1141,22 @@ class PermissionManager {
                        // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
                        if (
                                $title->isUserCssConfigPage()
-                               && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
+                               && !$this->userHasAnyRight( $user, 'editmyusercss', 'editusercss' )
                        ) {
                                $errors[] = [ 'mycustomcssprotected', $action ];
                        } elseif (
                                $title->isUserJsonConfigPage()
-                               && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
+                               && !$this->userHasAnyRight( $user, 'editmyuserjson', 'edituserjson' )
                        ) {
                                $errors[] = [ 'mycustomjsonprotected', $action ];
                        } elseif (
                                $title->isUserJsConfigPage()
-                               && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
+                               && !$this->userHasAnyRight( $user, 'editmyuserjs', 'edituserjs' )
                        ) {
                                $errors[] = [ 'mycustomjsprotected', $action ];
                        } elseif (
                                $title->isUserJsConfigPage()
-                               && !$user->isAllowedAny( 'edituserjs', 'editmyuserjsredirect' )
+                               && !$this->userHasAnyRight( $user, 'edituserjs', 'editmyuserjsredirect' )
                        ) {
                                // T207750 - do not allow users to edit a redirect if they couldn't edit the target
                                $rev = $this->revisionLookup->getRevisionByTitle( $title );
@@ -1195,6 +1216,44 @@ class PermissionManager {
                return in_array( $action, $this->getUserPermissions( $user ), true );
        }
 
+       /**
+        * Check if user is allowed to make any action
+        *
+        * @param UserIdentity $user
+        * // TODO: HHVM bug T228695#5450847 @param string ...$actions
+        * @suppress PhanCommentParamWithoutRealParam
+        * @return bool True if user is allowed to perform *any* of the given actions
+        * @since 1.34
+        */
+       public function userHasAnyRight( UserIdentity $user ) {
+               $actions = array_slice( func_get_args(), 1 );
+               foreach ( $actions as $action ) {
+                       if ( $this->userHasRight( $user, $action ) ) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Check if user is allowed to make all actions
+        *
+        * @param UserIdentity $user
+        * // TODO: HHVM bug T228695#5450847 @param string ...$actions
+        * @suppress PhanCommentParamWithoutRealParam
+        * @return bool True if user is allowed to perform *all* of the given actions
+        * @since 1.34
+        */
+       public function userHasAllRights( UserIdentity $user ) {
+               $actions = array_slice( func_get_args(), 1 );
+               foreach ( $actions as $action ) {
+                       if ( !$this->userHasRight( $user, $action ) ) {
+                               return false;
+                       }
+               }
+               return true;
+       }
+
        /**
         * Get the permissions this user has.
         *
@@ -1206,11 +1265,12 @@ class PermissionManager {
         */
        public function getUserPermissions( UserIdentity $user ) {
                $user = User::newFromIdentity( $user );
-               if ( !isset( $this->usersRights[ $user->getId() ] ) ) {
-                       $this->usersRights[ $user->getId() ] = $this->getGroupPermissions(
+               $rightsCacheKey = $this->getRightsCacheKey( $user );
+               if ( !isset( $this->usersRights[ $rightsCacheKey ] ) ) {
+                       $this->usersRights[ $rightsCacheKey ] = $this->getGroupPermissions(
                                $user->getEffectiveGroups()
                        );
-                       Hooks::run( 'UserGetRights', [ $user, &$this->usersRights[ $user->getId() ] ] );
+                       Hooks::run( 'UserGetRights', [ $user, &$this->usersRights[ $rightsCacheKey ] ] );
 
                        // Deny any rights denied by the user's session, unless this
                        // endpoint has no sessions.
@@ -1218,17 +1278,17 @@ class PermissionManager {
                                // FIXME: $user->getRequest().. need to be replaced with something else
                                $allowedRights = $user->getRequest()->getSession()->getAllowedUserRights();
                                if ( $allowedRights !== null ) {
-                                       $this->usersRights[ $user->getId() ] = array_intersect(
-                                               $this->usersRights[ $user->getId() ],
+                                       $this->usersRights[ $rightsCacheKey ] = array_intersect(
+                                               $this->usersRights[ $rightsCacheKey ],
                                                $allowedRights
                                        );
                                }
                        }
 
-                       Hooks::run( 'UserGetRightsRemove', [ $user, &$this->usersRights[ $user->getId() ] ] );
+                       Hooks::run( 'UserGetRightsRemove', [ $user, &$this->usersRights[ $rightsCacheKey ] ] );
                        // Force reindexation of rights when a hook has unset one of them
-                       $this->usersRights[ $user->getId() ] = array_values(
-                               array_unique( $this->usersRights[ $user->getId() ] )
+                       $this->usersRights[ $rightsCacheKey ] = array_values(
+                               array_unique( $this->usersRights[ $rightsCacheKey ] )
                        );
 
                        if (
@@ -1237,13 +1297,13 @@ class PermissionManager {
                                $user->getBlock()
                        ) {
                                $anon = new User;
-                               $this->usersRights[ $user->getId() ] = array_intersect(
-                                       $this->usersRights[ $user->getId() ],
+                               $this->usersRights[ $rightsCacheKey ] = array_intersect(
+                                       $this->usersRights[ $rightsCacheKey ],
                                        $this->getUserPermissions( $anon )
                                );
                        }
                }
-               $rights = $this->usersRights[ $user->getId() ];
+               $rights = $this->usersRights[ $rightsCacheKey ];
                foreach ( $this->temporaryUserRights[ $user->getId() ] ?? [] as $overrides ) {
                        $rights = array_values( array_unique( array_merge( $rights, $overrides ) ) );
                }
@@ -1260,14 +1320,24 @@ class PermissionManager {
         */
        public function invalidateUsersRightsCache( $user = null ) {
                if ( $user !== null ) {
-                       if ( isset( $this->usersRights[ $user->getId() ] ) ) {
-                               unset( $this->usersRights[$user->getId()] );
+                       $rightsCacheKey = $this->getRightsCacheKey( $user );
+                       if ( isset( $this->usersRights[ $rightsCacheKey ] ) ) {
+                               unset( $this->usersRights[ $rightsCacheKey ] );
                        }
                } else {
                        $this->usersRights = null;
                }
        }
 
+       /**
+        * Gets a unique key for user rights cache.
+        * @param UserIdentity $user
+        * @return string
+        */
+       private function getRightsCacheKey( UserIdentity $user ) {
+               return $user->isRegistered() ? "u:{$user->getId()}" : "anon:{$user->getName()}";
+       }
+
        /**
         * Check, if the given group has the given permission
         *
@@ -1401,7 +1471,7 @@ class PermissionManager {
         * @return string[] Array of permission names
         */
        public function getAllPermissions() {
-               if ( $this->allRights === false ) {
+               if ( $this->allRights === null ) {
                        if ( count( $this->options->get( 'AvailableRights' ) ) ) {
                                $this->allRights = array_unique( array_merge(
                                        $this->coreRights,
@@ -1415,6 +1485,99 @@ class PermissionManager {
                return $this->allRights;
        }
 
+       /**
+        * Determines if $user is unable to edit pages in namespace because it has been protected.
+        * @param $index
+        * @param UserIdentity $user
+        * @return bool
+        */
+       private function isNamespaceProtected( $index, UserIdentity $user ) {
+               $namespaceProtection = $this->options->get( 'NamespaceProtection' );
+               if ( isset( $namespaceProtection[$index] ) ) {
+                       return !$this->userHasAllRights( $user, ...(array)$namespaceProtection[$index] );
+               }
+               return false;
+       }
+
+       /**
+        * Determine which restriction levels it makes sense to use in a namespace,
+        * optionally filtered by a user's rights.
+        *
+        * @param int $index Index to check
+        * @param UserIdentity|null $user User to check
+        * @return array
+        */
+       public function getNamespaceRestrictionLevels( $index, UserIdentity $user = null ) {
+               if ( !isset( $this->options->get( 'NamespaceProtection' )[$index] ) ) {
+                       // All levels are valid if there's no namespace restriction.
+                       // But still filter by user, if necessary
+                       $levels = $this->options->get( 'RestrictionLevels' );
+                       if ( $user ) {
+                               $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
+                                       $right = $level;
+                                       if ( $right == 'sysop' ) {
+                                               $right = 'editprotected'; // BC
+                                       }
+                                       if ( $right == 'autoconfirmed' ) {
+                                               $right = 'editsemiprotected'; // BC
+                                       }
+                                       return $this->userHasRight( $user, $right );
+                               } ) );
+                       }
+                       return $levels;
+               }
+
+               // $wgNamespaceProtection can require one or more rights to edit the namespace, which
+               // may be satisfied by membership in multiple groups each giving a subset of those rights.
+               // A restriction level is redundant if, for any one of the namespace rights, all groups
+               // giving that right also give the restriction level's right. Or, conversely, a
+               // restriction level is not redundant if, for every namespace right, there's at least one
+               // group giving that right without the restriction level's right.
+               //
+               // First, for each right, get a list of groups with that right.
+               $namespaceRightGroups = [];
+               foreach ( (array)$this->options->get( 'NamespaceProtection' )[$index] as $right ) {
+                       if ( $right == 'sysop' ) {
+                               $right = 'editprotected'; // BC
+                       }
+                       if ( $right == 'autoconfirmed' ) {
+                               $right = 'editsemiprotected'; // BC
+                       }
+                       if ( $right != '' ) {
+                               $namespaceRightGroups[$right] = $this->getGroupsWithPermission( $right );
+                       }
+               }
+
+               // Now, go through the protection levels one by one.
+               $usableLevels = [ '' ];
+               foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
+                       $right = $level;
+                       if ( $right == 'sysop' ) {
+                               $right = 'editprotected'; // BC
+                       }
+                       if ( $right == 'autoconfirmed' ) {
+                               $right = 'editsemiprotected'; // BC
+                       }
+
+                       if ( $right != '' &&
+                                !isset( $namespaceRightGroups[$right] ) &&
+                                ( !$user || $this->userHasRight( $user, $right ) )
+                       ) {
+                               // Do any of the namespace rights imply the restriction right? (see explanation above)
+                               foreach ( $namespaceRightGroups as $groups ) {
+                                       if ( !array_diff( $groups, $this->getGroupsWithPermission( $right ) ) ) {
+                                               // Yes, this one does.
+                                               continue 2;
+                                       }
+                               }
+                               // No, keep the restriction level
+                               $usableLevels[] = $level;
+                       }
+               }
+
+               return $usableLevels;
+       }
+
        /**
         * Add temporary user rights, only valid for the current scope.
         * This is meant for making it possible to programatically trigger certain actions that
@@ -1452,7 +1615,8 @@ class PermissionManager {
                if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
                        throw new Exception( __METHOD__ . ' can not be called outside of tests' );
                }
-               $this->usersRights[ $user->getId() ] = is_array( $rights ) ? $rights : [ $rights ];
+               $this->usersRights[ $this->getRightsCacheKey( $user ) ] =
+                       is_array( $rights ) ? $rights : [ $rights ];
        }
 
 }