3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 namespace MediaWiki\Permissions
;
25 use MediaWiki\Config\ServiceOptions
;
26 use MediaWiki\Linker\LinkTarget
;
27 use MediaWiki\Revision\RevisionLookup
;
28 use MediaWiki\Revision\RevisionRecord
;
29 use MediaWiki\Session\SessionManager
;
30 use MediaWiki\Special\SpecialPageFactory
;
31 use MediaWiki\User\UserIdentity
;
38 use Wikimedia\ScopedCallback
;
42 * A service class for checking permissions
43 * To obtain an instance, use MediaWikiServices::getInstance()->getPermissionManager().
47 class PermissionManager
{
49 /** @var string Does cheap permission checks from replica DBs (usable for GUI creation) */
50 const RIGOR_QUICK
= 'quick';
52 /** @var string Does cheap and expensive checks possibly from a replica DB */
53 const RIGOR_FULL
= 'full';
55 /** @var string Does cheap and expensive checks, using the master as needed */
56 const RIGOR_SECURE
= 'secure';
59 * TODO Make this const when HHVM support is dropped (T192166)
64 public static $constructorOptions = [
66 'WhitelistReadRegexp',
72 'NamespaceProtection',
76 /** @var ServiceOptions */
79 /** @var SpecialPageFactory */
80 private $specialPageFactory;
82 /** @var RevisionLookup */
83 private $revisionLookup;
85 /** @var NamespaceInfo */
88 /** @var string[] Cached results of getAllRights() */
89 private $allRights = false;
91 /** @var string[][] Cached user rights */
92 private $usersRights = null;
95 * Temporary user rights, valid for the current request only.
96 * @var string[][][] userid => override group => rights
98 private $temporaryUserRights = [];
100 /** @var string[] Cached rights for isEveryoneAllowed */
101 private $cachedRights = [];
104 * Array of Strings Core rights.
105 * Each of these should have a corresponding message of the form
109 private $coreRights = [
139 'editmyuserjsredirect',
158 'move-categorypages',
159 'move-rootuserpages',
163 'override-export-depth',
185 'userrights-interwiki',
193 * @param ServiceOptions $options
194 * @param SpecialPageFactory $specialPageFactory
195 * @param RevisionLookup $revisionLookup
196 * @param NamespaceInfo $nsInfo
198 public function __construct(
199 ServiceOptions
$options,
200 SpecialPageFactory
$specialPageFactory,
201 RevisionLookup
$revisionLookup,
202 NamespaceInfo
$nsInfo
204 $options->assertRequiredOptions( self
::$constructorOptions );
205 $this->options
= $options;
206 $this->specialPageFactory
= $specialPageFactory;
207 $this->revisionLookup
= $revisionLookup;
208 $this->nsInfo
= $nsInfo;
212 * Can $user perform $action on a page?
214 * The method is intended to replace Title::userCan()
215 * The $user parameter need to be superseded by UserIdentity value in future
216 * The $title parameter need to be superseded by PageIdentity value in future
218 * @see Title::userCan()
220 * @param string $action
222 * @param LinkTarget $page
223 * @param string $rigor One of PermissionManager::RIGOR_ constants
224 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
225 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
226 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
230 public function userCan( $action, User
$user, LinkTarget
$page, $rigor = self
::RIGOR_SECURE
) {
231 return !count( $this->getPermissionErrorsInternal( $action, $user, $page, $rigor, true ) );
235 * Can $user perform $action on a page?
237 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
239 * @param string $action Action that permission needs to be checked for
240 * @param User $user User to check
241 * @param LinkTarget $page
242 * @param string $rigor One of PermissionManager::RIGOR_ constants
243 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
244 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
245 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
246 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
247 * whose corresponding errors may be ignored.
249 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
251 public function getPermissionErrors(
255 $rigor = self
::RIGOR_SECURE
,
258 $errors = $this->getPermissionErrorsInternal( $action, $user, $page, $rigor );
260 // Remove the errors being ignored.
261 foreach ( $errors as $index => $error ) {
262 $errKey = is_array( $error ) ?
$error[0] : $error;
264 if ( in_array( $errKey, $ignoreErrors ) ) {
265 unset( $errors[$index] );
267 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
268 unset( $errors[$index] );
276 * Check if user is blocked from editing a particular article. If the user does not
277 * have a block, this will return false.
280 * @param LinkTarget $page Title to check
281 * @param bool $fromReplica Whether to check the replica DB instead of the master
285 public function isBlockedFrom( User
$user, LinkTarget
$page, $fromReplica = false ) {
286 $block = $user->getBlock( $fromReplica );
291 // TODO: remove upon further migration to LinkTarget
292 $title = Title
::newFromLinkTarget( $page );
294 $blocked = $user->isHidden();
296 // Special handling for a user's own talk page. The block is not aware
297 // of the user, so this must be done here.
298 if ( $title->equals( $user->getTalkPage() ) ) {
299 $blocked = $block->appliesToUsertalk( $title );
301 $blocked = $block->appliesToTitle( $title );
305 // only for the purpose of the hook. We really don't need this here.
306 $allowUsertalk = $user->isAllowUsertalk();
308 // Allow extensions to let a blocked user access a particular page
309 Hooks
::run( 'UserIsBlockedFrom', [ $user, $title, &$blocked, &$allowUsertalk ] );
315 * Can $user perform $action on a page? This is an internal function,
316 * with multiple levels of checks depending on performance needs; see $rigor below.
317 * It does not check wfReadOnly().
319 * @param string $action Action that permission needs to be checked for
320 * @param User $user User to check
321 * @param LinkTarget $page
322 * @param string $rigor One of PermissionManager::RIGOR_ constants
323 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
324 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
325 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
326 * @param bool $short Set this to true to stop after the first permission error.
328 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
331 private function getPermissionErrorsInternal(
335 $rigor = self
::RIGOR_SECURE
,
338 if ( !in_array( $rigor, [ self
::RIGOR_QUICK
, self
::RIGOR_FULL
, self
::RIGOR_SECURE
] ) ) {
339 throw new Exception( "Invalid rigor parameter '$rigor'." );
342 # Read has special handling
343 if ( $action == 'read' ) {
345 'checkPermissionHooks',
346 'checkReadPermissions',
347 'checkUserBlock', // for wgBlockDisablesLogin
349 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
350 # or checkUserConfigPermissions here as it will lead to duplicate
351 # error messages. This is okay to do since anywhere that checks for
352 # create will also check for edit, and those checks are called for edit.
353 } elseif ( $action == 'create' ) {
355 'checkQuickPermissions',
356 'checkPermissionHooks',
357 'checkPageRestrictions',
358 'checkCascadingSourcesRestrictions',
359 'checkActionPermissions',
364 'checkQuickPermissions',
365 'checkPermissionHooks',
366 'checkSpecialsAndNSPermissions',
367 'checkSiteConfigPermissions',
368 'checkUserConfigPermissions',
369 'checkPageRestrictions',
370 'checkCascadingSourcesRestrictions',
371 'checkActionPermissions',
377 foreach ( $checks as $method ) {
378 $errors = $this->$method( $action, $user, $errors, $rigor, $short, $page );
380 if ( $short && $errors !== [] ) {
389 * Check various permission hooks
391 * @param string $action The action to check
392 * @param User $user User to check
393 * @param array $errors List of current errors
394 * @param string $rigor One of PermissionManager::RIGOR_ constants
395 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
396 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
397 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
398 * @param bool $short Short circuit on first error
400 * @param LinkTarget $page
402 * @return array List of errors
404 private function checkPermissionHooks(
412 // TODO: remove when LinkTarget usage will expand further
413 $title = Title
::newFromLinkTarget( $page );
414 // Use getUserPermissionsErrors instead
416 if ( !Hooks
::run( 'userCan', [ &$title, &$user, $action, &$result ] ) ) {
417 return $result ?
[] : [ [ 'badaccess-group0' ] ];
419 // Check getUserPermissionsErrors hook
420 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$title, &$user, $action, &$result ] ) ) {
421 $errors = $this->resultToError( $errors, $result );
423 // Check getUserPermissionsErrorsExpensive hook
425 $rigor !== self
::RIGOR_QUICK
426 && !( $short && count( $errors ) > 0 )
427 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$title, &$user, $action, &$result ] )
429 $errors = $this->resultToError( $errors, $result );
436 * Add the resulting error code to the errors array
438 * @param array $errors List of current errors
439 * @param array|string|MessageSpecifier|false $result Result of errors
441 * @return array List of errors
443 private function resultToError( $errors, $result ) {
444 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
445 // A single array representing an error
447 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
448 // A nested array representing multiple errors
449 $errors = array_merge( $errors, $result );
450 } elseif ( $result !== '' && is_string( $result ) ) {
451 // A string representing a message-id
452 $errors[] = [ $result ];
453 } elseif ( $result instanceof MessageSpecifier
) {
454 // A message specifier representing an error
455 $errors[] = [ $result ];
456 } elseif ( $result === false ) {
457 // a generic "We don't want them to do that"
458 $errors[] = [ 'badaccess-group0' ];
464 * Check that the user is allowed to read this page.
466 * @param string $action The action to check
467 * @param User $user User to check
468 * @param array $errors List of current errors
469 * @param string $rigor One of PermissionManager::RIGOR_ constants
470 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
471 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
472 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
473 * @param bool $short Short circuit on first error
475 * @param LinkTarget $page
477 * @return array List of errors
479 private function checkReadPermissions(
487 // TODO: remove when LinkTarget usage will expand further
488 $title = Title
::newFromLinkTarget( $page );
490 $whiteListRead = $this->options
->get( 'WhitelistRead' );
491 $whitelisted = false;
492 if ( $this->isEveryoneAllowed( 'read' ) ) {
493 # Shortcut for public wikis, allows skipping quite a bit of code
495 } elseif ( $this->userHasRight( $user, 'read' ) ) {
496 # If the user is allowed to read pages, he is allowed to read all pages
498 } elseif ( $this->isSameSpecialPage( 'Userlogin', $title )
499 ||
$this->isSameSpecialPage( 'PasswordReset', $title )
500 ||
$this->isSameSpecialPage( 'Userlogout', $title )
502 # Always grant access to the login page.
503 # Even anons need to be able to log in.
505 } elseif ( is_array( $whiteListRead ) && count( $whiteListRead ) ) {
506 # Time to check the whitelist
507 # Only do these checks is there's something to check against
508 $name = $title->getPrefixedText();
509 $dbName = $title->getPrefixedDBkey();
511 // Check for explicit whitelisting with and without underscores
512 if ( in_array( $name, $whiteListRead, true )
513 ||
in_array( $dbName, $whiteListRead, true ) ) {
515 } elseif ( $title->getNamespace() == NS_MAIN
) {
516 # Old settings might have the title prefixed with
517 # a colon for main-namespace pages
518 if ( in_array( ':' . $name, $whiteListRead ) ) {
521 } elseif ( $title->isSpecialPage() ) {
522 # If it's a special page, ditch the subpage bit and check again
523 $name = $title->getDBkey();
524 list( $name, /* $subpage */ ) =
525 $this->specialPageFactory
->resolveAlias( $name );
527 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
528 if ( in_array( $pure, $whiteListRead, true ) ) {
535 $whitelistReadRegexp = $this->options
->get( 'WhitelistReadRegexp' );
536 if ( !$whitelisted && is_array( $whitelistReadRegexp )
537 && !empty( $whitelistReadRegexp ) ) {
538 $name = $title->getPrefixedText();
539 // Check for regex whitelisting
540 foreach ( $whitelistReadRegexp as $listItem ) {
541 if ( preg_match( $listItem, $name ) ) {
548 if ( !$whitelisted ) {
549 # If the title is not whitelisted, give extensions a chance to do so...
550 Hooks
::run( 'TitleReadWhitelist', [ $title, $user, &$whitelisted ] );
551 if ( !$whitelisted ) {
552 $errors[] = $this->missingPermissionError( $action, $short );
560 * Get a description array when the user doesn't have the right to perform
561 * $action (i.e. when User::isAllowed() returns false)
563 * @param string $action The action to check
564 * @param bool $short Short circuit on first error
565 * @return array Array containing an error message key and any parameters
567 private function missingPermissionError( $action, $short ) {
568 // We avoid expensive display logic for quickUserCan's and such
570 return [ 'badaccess-group0' ];
573 // TODO: it would be a good idea to replace the method below with something else like
574 // maybe callback injection
575 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
579 * Returns true if this title resolves to the named special page
581 * @param string $name The special page name
582 * @param LinkTarget $page
586 private function isSameSpecialPage( $name, LinkTarget
$page ) {
587 if ( $page->getNamespace() == NS_SPECIAL
) {
588 list( $thisName, /* $subpage */ ) =
589 $this->specialPageFactory
->resolveAlias( $page->getDBkey() );
590 if ( $name == $thisName ) {
598 * Check that the user isn't blocked from editing.
600 * @param string $action The action to check
601 * @param User $user User to check
602 * @param array $errors List of current errors
603 * @param string $rigor One of PermissionManager::RIGOR_ constants
604 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
605 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
606 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
607 * @param bool $short Short circuit on first error
609 * @param LinkTarget $page
611 * @return array List of errors
613 private function checkUserBlock(
621 // Account creation blocks handled at userlogin.
622 // Unblocking handled in SpecialUnblock
623 if ( $rigor === self
::RIGOR_QUICK ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
627 // Optimize for a very common case
628 if ( $action === 'read' && !$this->options
->get( 'BlockDisablesLogin' ) ) {
632 if ( $this->options
->get( 'EmailConfirmToEdit' )
633 && !$user->isEmailConfirmed()
634 && $action === 'edit'
636 $errors[] = [ 'confirmedittext' ];
639 $useReplica = ( $rigor !== self
::RIGOR_SECURE
);
640 $block = $user->getBlock( $useReplica );
642 // If the user does not have a block, or the block they do have explicitly
643 // allows the action (like "read" or "upload").
644 if ( !$block ||
$block->appliesToRight( $action ) === false ) {
648 // Determine if the user is blocked from this action on this page.
649 // What gets passed into this method is a user right, not an action name.
650 // There is no way to instantiate an action by restriction. However, this
651 // will get the action where the restriction is the same. This may result
652 // in actions being blocked that shouldn't be.
654 if ( Action
::exists( $action ) ) {
655 // TODO: this drags a ton of dependencies in, would be good to avoid WikiPage
656 // instantiation and decouple it creating an ActionPermissionChecker interface
657 $wikiPage = WikiPage
::factory( Title
::newFromLinkTarget( $page, 'clone' ) );
658 // Creating an action will perform several database queries to ensure that
659 // the action has not been overridden by the content type.
660 // FIXME: avoid use of RequestContext since it drags in User and Title dependencies
661 // probably we may use fake context object since it's unlikely that Action uses it
662 // anyway. It would be nice if we could avoid instantiating the Action at all.
663 $actionObj = Action
::factory( $action, $wikiPage, RequestContext
::getMain() );
664 // Ensure that the retrieved action matches the restriction.
665 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
670 // If no action object is returned, assume that the action requires unblock
671 // which is the default.
672 if ( !$actionObj ||
$actionObj->requiresUnblock() ) {
673 if ( $this->isBlockedFrom( $user, $page, $useReplica ) ) {
674 // @todo FIXME: Pass the relevant context into this function.
675 $errors[] = $block->getPermissionsError( RequestContext
::getMain() );
683 * Permissions checks that fail most often, and which are easiest to test.
685 * @param string $action The action to check
686 * @param User $user User to check
687 * @param array $errors List of current errors
688 * @param string $rigor One of PermissionManager::RIGOR_ constants
689 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
690 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
691 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
692 * @param bool $short Short circuit on first error
694 * @param LinkTarget $page
696 * @return array List of errors
698 private function checkQuickPermissions(
706 // TODO: remove when LinkTarget usage will expand further
707 $title = Title
::newFromLinkTarget( $page );
709 if ( !Hooks
::run( 'TitleQuickPermissions',
710 [ $title, $user, $action, &$errors, ( $rigor !== self
::RIGOR_QUICK
), $short ] )
715 $isSubPage = $this->nsInfo
->hasSubpages( $title->getNamespace() ) ?
716 strpos( $title->getText(), '/' ) !== false : false;
718 if ( $action == 'create' ) {
720 ( $this->nsInfo
->isTalk( $title->getNamespace() ) &&
721 !$this->userHasRight( $user, 'createtalk' ) ) ||
722 ( !$this->nsInfo
->isTalk( $title->getNamespace() ) &&
723 !$this->userHasRight( $user, 'createpage' ) )
725 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
727 } elseif ( $action == 'move' ) {
728 if ( !$this->userHasRight( $user, 'move-rootuserpages' )
729 && $title->getNamespace() == NS_USER
&& !$isSubPage ) {
730 // Show user page-specific message only if the user can move other pages
731 $errors[] = [ 'cant-move-user-page' ];
734 // Check if user is allowed to move files if it's a file
735 if ( $title->getNamespace() == NS_FILE
&&
736 !$this->userHasRight( $user, 'movefile' ) ) {
737 $errors[] = [ 'movenotallowedfile' ];
740 // Check if user is allowed to move category pages if it's a category page
741 if ( $title->getNamespace() == NS_CATEGORY
&&
742 !$this->userHasRight( $user, 'move-categorypages' ) ) {
743 $errors[] = [ 'cant-move-category-page' ];
746 if ( !$this->userHasRight( $user, 'move' ) ) {
747 // User can't move anything
748 $userCanMove = $this->groupHasPermission( 'user', 'move' );
749 $autoconfirmedCanMove = $this->groupHasPermission( 'autoconfirmed', 'move' );
750 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
751 // custom message if logged-in users without any special rights can move
752 $errors[] = [ 'movenologintext' ];
754 $errors[] = [ 'movenotallowed' ];
757 } elseif ( $action == 'move-target' ) {
758 if ( !$this->userHasRight( $user, 'move' ) ) {
759 // User can't move anything
760 $errors[] = [ 'movenotallowed' ];
761 } elseif ( !$this->userHasRight( $user, 'move-rootuserpages' )
762 && $title->getNamespace() == NS_USER
&& !$isSubPage ) {
763 // Show user page-specific message only if the user can move other pages
764 $errors[] = [ 'cant-move-to-user-page' ];
765 } elseif ( !$this->userHasRight( $user, 'move-categorypages' )
766 && $title->getNamespace() == NS_CATEGORY
) {
767 // Show category page-specific message only if the user can move other pages
768 $errors[] = [ 'cant-move-to-category-page' ];
770 } elseif ( !$this->userHasRight( $user, $action ) ) {
771 $errors[] = $this->missingPermissionError( $action, $short );
778 * Check against page_restrictions table requirements on this
779 * page. The user must possess all required rights for this
782 * @param string $action The action to check
783 * @param User $user User to check
784 * @param array $errors List of current errors
785 * @param string $rigor One of PermissionManager::RIGOR_ constants
786 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
787 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
788 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
789 * @param bool $short Short circuit on first error
791 * @param LinkTarget $page
793 * @return array List of errors
795 private function checkPageRestrictions(
803 // TODO: remove & rework upon further use of LinkTarget
804 $title = Title
::newFromLinkTarget( $page );
805 foreach ( $title->getRestrictions( $action ) as $right ) {
806 // Backwards compatibility, rewrite sysop -> editprotected
807 if ( $right == 'sysop' ) {
808 $right = 'editprotected';
810 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
811 if ( $right == 'autoconfirmed' ) {
812 $right = 'editsemiprotected';
814 if ( $right == '' ) {
817 if ( !$this->userHasRight( $user, $right ) ) {
818 $errors[] = [ 'protectedpagetext', $right, $action ];
819 } elseif ( $title->areRestrictionsCascading() &&
820 !$this->userHasRight( $user, 'protect' ) ) {
821 $errors[] = [ 'protectedpagetext', 'protect', $action ];
829 * Check restrictions on cascading pages.
831 * @param string $action The action to check
832 * @param UserIdentity $user User to check
833 * @param array $errors List of current errors
834 * @param string $rigor One of PermissionManager::RIGOR_ constants
835 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
836 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
837 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
838 * @param bool $short Short circuit on first error
840 * @param LinkTarget $page
842 * @return array List of errors
844 private function checkCascadingSourcesRestrictions(
852 // TODO: remove & rework upon further use of LinkTarget
853 $title = Title
::newFromLinkTarget( $page );
854 if ( $rigor !== self
::RIGOR_QUICK
&& !$title->isUserConfigPage() ) {
855 # We /could/ use the protection level on the source page, but it's
856 # fairly ugly as we have to establish a precedence hierarchy for pages
857 # included by multiple cascade-protected pages. So just restrict
858 # it to people with 'protect' permission, as they could remove the
860 list( $cascadingSources, $restrictions ) = $title->getCascadeProtectionSources();
861 # Cascading protection depends on more than this page...
862 # Several cascading protected pages may include this page...
863 # Check each cascading level
864 # This is only for protection restrictions, not for all actions
865 if ( isset( $restrictions[$action] ) ) {
866 foreach ( $restrictions[$action] as $right ) {
867 // Backwards compatibility, rewrite sysop -> editprotected
868 if ( $right == 'sysop' ) {
869 $right = 'editprotected';
871 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
872 if ( $right == 'autoconfirmed' ) {
873 $right = 'editsemiprotected';
875 if ( $right != '' && !$this->userHasAllRights( $user, 'protect', $right ) ) {
877 /** @var Title $wikiPage */
878 foreach ( $cascadingSources as $wikiPage ) {
879 $wikiPages .= '* [[:' . $wikiPage->getPrefixedText() . "]]\n";
881 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $wikiPages, $action ];
891 * Check action permissions not already checked in checkQuickPermissions
893 * @param string $action The action to check
894 * @param User $user User to check
895 * @param array $errors List of current errors
896 * @param string $rigor One of PermissionManager::RIGOR_ constants
897 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
898 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
899 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
900 * @param bool $short Short circuit on first error
902 * @param LinkTarget $page
904 * @return array List of errors
906 private function checkActionPermissions(
914 global $wgDeleteRevisionsLimit, $wgLang;
916 // TODO: remove & rework upon further use of LinkTarget
917 $title = Title
::newFromLinkTarget( $page );
919 if ( $action == 'protect' ) {
920 if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $title, $rigor, true ) ) ) {
921 // If they can't edit, they shouldn't protect.
922 $errors[] = [ 'protect-cantedit' ];
924 } elseif ( $action == 'create' ) {
925 $title_protection = $title->getTitleProtection();
926 if ( $title_protection ) {
927 if ( $title_protection['permission'] == ''
928 ||
!$this->userHasRight( $user, $title_protection['permission'] )
932 // TODO: get rid of the User dependency
933 User
::whoIs( $title_protection['user'] ),
934 $title_protection['reason']
938 } elseif ( $action == 'move' ) {
939 // Check for immobile pages
940 if ( !$this->nsInfo
->isMovable( $title->getNamespace() ) ) {
941 // Specific message for this case
942 $errors[] = [ 'immobile-source-namespace', $title->getNsText() ];
943 } elseif ( !$title->isMovable() ) {
944 // Less specific message for rarer cases
945 $errors[] = [ 'immobile-source-page' ];
947 } elseif ( $action == 'move-target' ) {
948 if ( !$this->nsInfo
->isMovable( $title->getNamespace() ) ) {
949 $errors[] = [ 'immobile-target-namespace', $title->getNsText() ];
950 } elseif ( !$title->isMovable() ) {
951 $errors[] = [ 'immobile-target-page' ];
953 } elseif ( $action == 'delete' ) {
954 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true, $title );
955 if ( !$tempErrors ) {
956 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
957 $user, $tempErrors, $rigor, true, $title );
960 // If protection keeps them from editing, they shouldn't be able to delete.
961 $errors[] = [ 'deleteprotected' ];
963 if ( $rigor !== self
::RIGOR_QUICK
&& $wgDeleteRevisionsLimit
964 && !$this->userCan( 'bigdelete', $user, $title ) && $title->isBigDeletion()
966 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
968 } elseif ( $action === 'undelete' ) {
969 if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $title, $rigor, true ) ) ) {
970 // Undeleting implies editing
971 $errors[] = [ 'undelete-cantedit' ];
973 if ( !$title->exists()
974 && count( $this->getPermissionErrorsInternal( 'create', $user, $title, $rigor, true ) )
976 // Undeleting where nothing currently exists implies creating
977 $errors[] = [ 'undelete-cantcreate' ];
984 * Check permissions on special pages & namespaces
986 * @param string $action The action to check
987 * @param User $user User to check
988 * @param array $errors List of current errors
989 * @param string $rigor One of PermissionManager::RIGOR_ constants
990 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
991 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
992 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
993 * @param bool $short Short circuit on first error
995 * @param LinkTarget $page
997 * @return array List of errors
999 private function checkSpecialsAndNSPermissions(
1007 // TODO: remove & rework upon further use of LinkTarget
1008 $title = Title
::newFromLinkTarget( $page );
1010 # Only 'createaccount' can be performed on special pages,
1011 # which don't actually exist in the DB.
1012 if ( $title->getNamespace() == NS_SPECIAL
&& $action !== 'createaccount' ) {
1013 $errors[] = [ 'ns-specialprotected' ];
1016 # Check $wgNamespaceProtection for restricted namespaces
1017 if ( $title->isNamespaceProtected( $user ) ) {
1018 $ns = $title->getNamespace() == NS_MAIN ?
1019 wfMessage( 'nstab-main' )->text() : $title->getNsText();
1020 $errors[] = $title->getNamespace() == NS_MEDIAWIKI ?
1021 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
1028 * Check sitewide CSS/JSON/JS permissions
1030 * @param string $action The action to check
1031 * @param User $user User to check
1032 * @param array $errors List of current errors
1033 * @param string $rigor One of PermissionManager::RIGOR_ constants
1034 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1035 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1036 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
1037 * @param bool $short Short circuit on first error
1039 * @param LinkTarget $page
1041 * @return array List of errors
1043 private function checkSiteConfigPermissions(
1051 // TODO: remove & rework upon further use of LinkTarget
1052 $title = Title
::newFromLinkTarget( $page );
1054 if ( $action != 'patrol' ) {
1056 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
1057 // editinterface right. That's implemented as a restriction so no check needed here.
1058 if ( $title->isSiteCssConfigPage() && !$this->userHasRight( $user, 'editsitecss' ) ) {
1059 $error = [ 'sitecssprotected', $action ];
1060 } elseif ( $title->isSiteJsonConfigPage() && !$this->userHasRight( $user, 'editsitejson' ) ) {
1061 $error = [ 'sitejsonprotected', $action ];
1062 } elseif ( $title->isSiteJsConfigPage() && !$this->userHasRight( $user, 'editsitejs' ) ) {
1063 $error = [ 'sitejsprotected', $action ];
1064 } elseif ( $title->isRawHtmlMessage() ) {
1065 // Raw HTML can be used to deploy CSS or JS so require rights for both.
1066 if ( !$this->userHasRight( $user, 'editsitejs' ) ) {
1067 $error = [ 'sitejsprotected', $action ];
1068 } elseif ( !$this->userHasRight( $user, 'editsitecss' ) ) {
1069 $error = [ 'sitecssprotected', $action ];
1074 if ( $this->userHasRight( $user, 'editinterface' ) ) {
1075 // Most users / site admins will probably find out about the new, more restrictive
1076 // permissions by failing to edit something. Give them more info.
1077 // TODO remove this a few release cycles after 1.32
1078 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
1088 * Check CSS/JSON/JS sub-page permissions
1090 * @param string $action The action to check
1091 * @param UserIdentity $user User to check
1092 * @param array $errors List of current errors
1093 * @param string $rigor One of PermissionManager::RIGOR_ constants
1094 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1095 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1096 * - RIGOR_SECURE : does cheap and expensive checks, using the master as needed
1097 * @param bool $short Short circuit on first error
1099 * @param LinkTarget $page
1101 * @return array List of errors
1103 private function checkUserConfigPermissions(
1111 // TODO: remove & rework upon further use of LinkTarget
1112 $title = Title
::newFromLinkTarget( $page );
1114 # Protect css/json/js subpages of user pages
1115 # XXX: this might be better using restrictions
1117 if ( $action === 'patrol' ) {
1121 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $title->getText() ) ) {
1122 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
1124 $title->isUserCssConfigPage()
1125 && !$this->userHasAnyRight( $user, 'editmyusercss', 'editusercss' )
1127 $errors[] = [ 'mycustomcssprotected', $action ];
1129 $title->isUserJsonConfigPage()
1130 && !$this->userHasAnyRight( $user, 'editmyuserjson', 'edituserjson' )
1132 $errors[] = [ 'mycustomjsonprotected', $action ];
1134 $title->isUserJsConfigPage()
1135 && !$this->userHasAnyRight( $user, 'editmyuserjs', 'edituserjs' )
1137 $errors[] = [ 'mycustomjsprotected', $action ];
1139 $title->isUserJsConfigPage()
1140 && !$this->userHasAnyRight( $user, 'edituserjs', 'editmyuserjsredirect' )
1142 // T207750 - do not allow users to edit a redirect if they couldn't edit the target
1143 $rev = $this->revisionLookup
->getRevisionByTitle( $title );
1144 $content = $rev ?
$rev->getContent( 'main', RevisionRecord
::RAW
) : null;
1145 $target = $content ?
$content->getUltimateRedirectTarget() : null;
1147 !$target->inNamespace( NS_USER
)
1148 ||
!preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $target->getText() )
1150 $errors[] = [ 'mycustomjsredirectprotected', $action ];
1154 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
1155 // deletion/suppression which cannot be used for attacks and we want to avoid the
1156 // situation where an unprivileged user can post abusive content on their subpages
1157 // and only very highly privileged users could remove it.
1158 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
1160 $title->isUserCssConfigPage()
1161 && !$this->userHasRight( $user, 'editusercss' )
1163 $errors[] = [ 'customcssprotected', $action ];
1165 $title->isUserJsonConfigPage()
1166 && !$this->userHasRight( $user, 'edituserjson' )
1168 $errors[] = [ 'customjsonprotected', $action ];
1170 $title->isUserJsConfigPage()
1171 && !$this->userHasRight( $user, 'edituserjs' )
1173 $errors[] = [ 'customjsprotected', $action ];
1182 * Testing a permission
1186 * @param UserIdentity $user
1187 * @param string $action
1191 public function userHasRight( UserIdentity
$user, $action = '' ) {
1192 if ( $action === '' ) {
1193 return true; // In the spirit of DWIM
1195 // Use strict parameter to avoid matching numeric 0 accidentally inserted
1196 // by misconfiguration: 0 == 'foo'
1197 return in_array( $action, $this->getUserPermissions( $user ), true );
1201 * Check if user is allowed to make any action
1203 * @param UserIdentity $user
1204 * // TODO: HHVM can't create mocks with variable params @param string ...$actions
1205 * @return bool True if user is allowed to perform *any* of the given actions
1208 public function userHasAnyRight( UserIdentity
$user ) {
1209 $actions = array_slice( func_get_args(), 1 );
1210 foreach ( $actions as $action ) {
1211 if ( $this->userHasRight( $user, $action ) ) {
1219 * Check if user is allowed to make all actions
1221 * @param UserIdentity $user
1222 * // TODO: HHVM can't create mocks with variable params @param string ...$actions
1223 * @return bool True if user is allowed to perform *all* of the given actions
1226 public function userHasAllRights( UserIdentity
$user ) {
1227 $actions = array_slice( func_get_args(), 1 );
1228 foreach ( $actions as $action ) {
1229 if ( !$this->userHasRight( $user, $action ) ) {
1237 * Get the permissions this user has.
1241 * @param UserIdentity $user
1243 * @return string[] permission names
1245 public function getUserPermissions( UserIdentity
$user ) {
1246 $user = User
::newFromIdentity( $user );
1247 if ( !isset( $this->usersRights
[ $user->getId() ] ) ) {
1248 $this->usersRights
[ $user->getId() ] = $this->getGroupPermissions(
1249 $user->getEffectiveGroups()
1251 Hooks
::run( 'UserGetRights', [ $user, &$this->usersRights
[ $user->getId() ] ] );
1253 // Deny any rights denied by the user's session, unless this
1254 // endpoint has no sessions.
1255 if ( !defined( 'MW_NO_SESSION' ) ) {
1256 // FIXME: $user->getRequest().. need to be replaced with something else
1257 $allowedRights = $user->getRequest()->getSession()->getAllowedUserRights();
1258 if ( $allowedRights !== null ) {
1259 $this->usersRights
[ $user->getId() ] = array_intersect(
1260 $this->usersRights
[ $user->getId() ],
1266 Hooks
::run( 'UserGetRightsRemove', [ $user, &$this->usersRights
[ $user->getId() ] ] );
1267 // Force reindexation of rights when a hook has unset one of them
1268 $this->usersRights
[ $user->getId() ] = array_values(
1269 array_unique( $this->usersRights
[ $user->getId() ] )
1273 $user->isLoggedIn() &&
1274 $this->options
->get( 'BlockDisablesLogin' ) &&
1278 $this->usersRights
[ $user->getId() ] = array_intersect(
1279 $this->usersRights
[ $user->getId() ],
1280 $this->getUserPermissions( $anon )
1284 $rights = $this->usersRights
[ $user->getId() ];
1285 foreach ( $this->temporaryUserRights
[ $user->getId() ] ??
[] as $overrides ) {
1286 $rights = array_values( array_unique( array_merge( $rights, $overrides ) ) );
1292 * Clears users permissions cache, if specific user is provided it tries to clear
1293 * permissions cache only for provided user.
1297 * @param User|null $user
1299 public function invalidateUsersRightsCache( $user = null ) {
1300 if ( $user !== null ) {
1301 if ( isset( $this->usersRights
[ $user->getId() ] ) ) {
1302 unset( $this->usersRights
[$user->getId()] );
1305 $this->usersRights
= null;
1310 * Check, if the given group has the given permission
1312 * If you're wanting to check whether all users have a permission, use
1313 * PermissionManager::isEveryoneAllowed() instead. That properly checks if it's revoked
1318 * @param string $group Group to check
1319 * @param string $role Role to check
1323 public function groupHasPermission( $group, $role ) {
1324 $groupPermissions = $this->options
->get( 'GroupPermissions' );
1325 $revokePermissions = $this->options
->get( 'RevokePermissions' );
1326 return isset( $groupPermissions[$group][$role] ) && $groupPermissions[$group][$role] &&
1327 !( isset( $revokePermissions[$group][$role] ) && $revokePermissions[$group][$role] );
1331 * Get the permissions associated with a given list of groups
1335 * @param array $groups Array of Strings List of internal group names
1336 * @return array Array of Strings List of permission key names for given groups combined
1338 public function getGroupPermissions( $groups ) {
1340 // grant every granted permission first
1341 foreach ( $groups as $group ) {
1342 if ( isset( $this->options
->get( 'GroupPermissions' )[$group] ) ) {
1343 $rights = array_merge( $rights,
1344 // array_filter removes empty items
1345 array_keys( array_filter( $this->options
->get( 'GroupPermissions' )[$group] ) ) );
1348 // now revoke the revoked permissions
1349 foreach ( $groups as $group ) {
1350 if ( isset( $this->options
->get( 'RevokePermissions' )[$group] ) ) {
1351 $rights = array_diff( $rights,
1352 array_keys( array_filter( $this->options
->get( 'RevokePermissions' )[$group] ) ) );
1355 return array_unique( $rights );
1359 * Get all the groups who have a given permission
1363 * @param string $role Role to check
1364 * @return array Array of Strings List of internal group names with the given permission
1366 public function getGroupsWithPermission( $role ) {
1367 $allowedGroups = [];
1368 foreach ( array_keys( $this->options
->get( 'GroupPermissions' ) ) as $group ) {
1369 if ( $this->groupHasPermission( $group, $role ) ) {
1370 $allowedGroups[] = $group;
1373 return $allowedGroups;
1377 * Check if all users may be assumed to have the given permission
1379 * We generally assume so if the right is granted to '*' and isn't revoked
1380 * on any group. It doesn't attempt to take grants or other extension
1381 * limitations on rights into account in the general case, though, as that
1382 * would require it to always return false and defeat the purpose.
1383 * Specifically, session-based rights restrictions (such as OAuth or bot
1384 * passwords) are applied based on the current session.
1386 * @param string $right Right to check
1391 public function isEveryoneAllowed( $right ) {
1392 // Use the cached results, except in unit tests which rely on
1393 // being able change the permission mid-request
1394 if ( isset( $this->cachedRights
[$right] ) ) {
1395 return $this->cachedRights
[$right];
1398 if ( !isset( $this->options
->get( 'GroupPermissions' )['*'][$right] )
1399 ||
!$this->options
->get( 'GroupPermissions' )['*'][$right] ) {
1400 $this->cachedRights
[$right] = false;
1404 // If it's revoked anywhere, then everyone doesn't have it
1405 foreach ( $this->options
->get( 'RevokePermissions' ) as $rights ) {
1406 if ( isset( $rights[$right] ) && $rights[$right] ) {
1407 $this->cachedRights
[$right] = false;
1412 // Remove any rights that aren't allowed to the global-session user,
1413 // unless there are no sessions for this endpoint.
1414 if ( !defined( 'MW_NO_SESSION' ) ) {
1416 // XXX: think what could be done with the below
1417 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
1418 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
1419 $this->cachedRights
[$right] = false;
1424 // Allow extensions to say false
1425 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
1426 $this->cachedRights
[$right] = false;
1430 $this->cachedRights
[$right] = true;
1435 * Get a list of all available permissions.
1439 * @return string[] Array of permission names
1441 public function getAllPermissions() {
1442 if ( $this->allRights
=== false ) {
1443 if ( count( $this->options
->get( 'AvailableRights' ) ) ) {
1444 $this->allRights
= array_unique( array_merge(
1446 $this->options
->get( 'AvailableRights' )
1449 $this->allRights
= $this->coreRights
;
1451 Hooks
::run( 'UserGetAllRights', [ &$this->allRights
] );
1453 return $this->allRights
;
1457 * Determine which restriction levels it makes sense to use in a namespace,
1458 * optionally filtered by a user's rights.
1460 * @param int $index Index to check
1461 * @param UserIdentity|null $user User to check
1464 public function getNamespaceRestrictionLevels( $index, UserIdentity
$user = null ) {
1465 if ( !isset( $this->options
->get( 'NamespaceProtection' )[$index] ) ) {
1466 // All levels are valid if there's no namespace restriction.
1467 // But still filter by user, if necessary
1468 $levels = $this->options
->get( 'RestrictionLevels' );
1470 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
1472 if ( $right == 'sysop' ) {
1473 $right = 'editprotected'; // BC
1475 if ( $right == 'autoconfirmed' ) {
1476 $right = 'editsemiprotected'; // BC
1478 return $this->userHasRight( $user, $right );
1484 // $wgNamespaceProtection can require one or more rights to edit the namespace, which
1485 // may be satisfied by membership in multiple groups each giving a subset of those rights.
1486 // A restriction level is redundant if, for any one of the namespace rights, all groups
1487 // giving that right also give the restriction level's right. Or, conversely, a
1488 // restriction level is not redundant if, for every namespace right, there's at least one
1489 // group giving that right without the restriction level's right.
1491 // First, for each right, get a list of groups with that right.
1492 $namespaceRightGroups = [];
1493 foreach ( (array)$this->options
->get( 'NamespaceProtection' )[$index] as $right ) {
1494 if ( $right == 'sysop' ) {
1495 $right = 'editprotected'; // BC
1497 if ( $right == 'autoconfirmed' ) {
1498 $right = 'editsemiprotected'; // BC
1500 if ( $right != '' ) {
1501 $namespaceRightGroups[$right] = $this->getGroupsWithPermission( $right );
1505 // Now, go through the protection levels one by one.
1506 $usableLevels = [ '' ];
1507 foreach ( $this->options
->get( 'RestrictionLevels' ) as $level ) {
1509 if ( $right == 'sysop' ) {
1510 $right = 'editprotected'; // BC
1512 if ( $right == 'autoconfirmed' ) {
1513 $right = 'editsemiprotected'; // BC
1516 if ( $right != '' &&
1517 !isset( $namespaceRightGroups[$right] ) &&
1518 ( !$user ||
$this->userHasRight( $user, $right ) )
1520 // Do any of the namespace rights imply the restriction right? (see explanation above)
1521 foreach ( $namespaceRightGroups as $groups ) {
1522 if ( !array_diff( $groups, $this->getGroupsWithPermission( $right ) ) ) {
1523 // Yes, this one does.
1527 // No, keep the restriction level
1528 $usableLevels[] = $level;
1532 return $usableLevels;
1536 * Add temporary user rights, only valid for the current scope.
1537 * This is meant for making it possible to programatically trigger certain actions that
1538 * the user wouldn't be able to trigger themselves; e.g. allow users without the bot right
1539 * to make bot-flagged actions through certain special pages.
1540 * Returns a "scope guard" variable; whenever that variable goes out of scope or is consumed
1541 * via ScopedCallback::consume(), the temporary rights are revoked.
1545 * @param UserIdentity $user
1546 * @param string|string[] $rights
1547 * @return ScopedCallback
1549 public function addTemporaryUserRights( UserIdentity
$user, $rights ) {
1550 $userId = $user->getId();
1551 $nextKey = count( $this->temporaryUserRights
[$userId] ??
[] );
1552 $this->temporaryUserRights
[$userId][$nextKey] = (array)$rights;
1553 return new ScopedCallback( function () use ( $userId, $nextKey ) {
1554 unset( $this->temporaryUserRights
[$userId][$nextKey] );
1559 * Overrides user permissions cache
1564 * @param string[]|string $rights
1568 public function overrideUserRightsForTesting( $user, $rights = [] ) {
1569 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1570 throw new Exception( __METHOD__
. ' can not be called outside of tests' );
1572 $this->usersRights
[ $user->getId() ] = is_array( $rights ) ?
$rights : [ $rights ];