Debian Codegraph @

includes/Permissions/PermissionManager.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20 namespace MediaWiki\Permissions;
21
22 use InvalidArgumentException;
23 use LogicException;
24 use MediaWiki\Actions\ActionFactory;
25 use MediaWiki\Block\AbstractBlock;
26 use MediaWiki\Block\Block;
27 use MediaWiki\Block\BlockErrorFormatter;
28 use MediaWiki\Block\BlockManager;
29 use MediaWiki\Config\ServiceOptions;
30 use MediaWiki\Context\IContextSource;
31 use MediaWiki\Context\RequestContext;
32 use MediaWiki\HookContainer\HookContainer;
33 use MediaWiki\HookContainer\HookRunner;
34 use MediaWiki\Linker\LinkTarget;
35 use MediaWiki\MainConfigNames;
36 use MediaWiki\Message\Message;
37 use MediaWiki\Page\PageIdentity;
38 use MediaWiki\Page\PageReference;
39 use MediaWiki\Page\RedirectLookup;
40 use MediaWiki\Request\WebRequest;
41 use MediaWiki\Session\SessionManager;
42 use MediaWiki\SpecialPage\SpecialPage;
43 use MediaWiki\SpecialPage\SpecialPageFactory;
44 use MediaWiki\Title\NamespaceInfo;
45 use MediaWiki\Title\Title;
46 use MediaWiki\Title\TitleFormatter;
47 use MediaWiki\User\TempUser\TempUserConfig;
48 use MediaWiki\User\User;
49 use MediaWiki\User\UserFactory;
50 use MediaWiki\User\UserGroupManager;
51 use MediaWiki\User\UserGroupMembership;
52 use MediaWiki\User\UserIdentity;
53 use MediaWiki\User\UserIdentityLookup;
54 use PermissionsError;
55 use StatusValue;
56 use Wikimedia\Message\MessageSpecifier;
57 use Wikimedia\ScopedCallback;
58
59 /**
60 * A service class for checking permissions
61 * To obtain an instance, use MediaWikiServices::getInstance()->getPermissionManager().
62 *
63 * @since 1.33
64 */
65 class PermissionManager {
66
67 /** @var string Does cheap permission checks from replica DBs (usable for GUI creation) */
68 public const RIGOR_QUICK = 'quick';
69
70 /** @var string Does cheap and expensive checks possibly from a replica DB */
71 public const RIGOR_FULL = 'full';
72
73 /** @var string Does cheap and expensive checks, using the primary DB as needed */
74 public const RIGOR_SECURE = 'secure';
75
76 /**
77 * @internal For use by ServiceWiring
78 */
79 public const CONSTRUCTOR_OPTIONS = [
80 MainConfigNames::WhitelistRead,
81 MainConfigNames::WhitelistReadRegexp,
82 MainConfigNames::EmailConfirmToEdit,
83 MainConfigNames::BlockDisablesLogin,
84 MainConfigNames::EnablePartialActionBlocks,
85 MainConfigNames::GroupPermissions,
86 MainConfigNames::RevokePermissions,
87 MainConfigNames::AvailableRights,
88 MainConfigNames::NamespaceProtection,
89 MainConfigNames::RestrictionLevels,
90 MainConfigNames::DeleteRevisionsLimit,
91 MainConfigNames::RateLimits,
92 MainConfigNames::ImplicitRights,
93 ];
94
95 private ServiceOptions $options;
96 private SpecialPageFactory $specialPageFactory;
97 private NamespaceInfo $nsInfo;
98 private GroupPermissionsLookup $groupPermissionsLookup;
99 private UserGroupManager $userGroupManager;
100 private BlockManager $blockManager;
101 private BlockErrorFormatter $blockErrorFormatter;
102 private HookRunner $hookRunner;
103 private UserIdentityLookup $userIdentityLookup;
104 private RedirectLookup $redirectLookup;
105 private RestrictionStore $restrictionStore;
106 private TitleFormatter $titleFormatter;
107 private TempUserConfig $tempUserConfig;
108 private UserFactory $userFactory;
109 private ActionFactory $actionFactory;
110
111 /** @var string[]|null Cached results of getAllPermissions() */
112 private $allRights;
113
114 /** @var string[]|null Cached results of getImplicitRights() */
115 private $implicitRights;
116
117 /** @var string[][] Cached user rights */
118 private $usersRights = [];
119
120 /**
121 * Temporary user rights, valid for the current request only.
122 * @var string[][][] userid => override group => rights
123 */
124 private $temporaryUserRights = [];
125
126 /** @var bool[] Cached rights for isEveryoneAllowed, [ right => allowed ] */
127 private $cachedRights = [];
128
129 /**
130 * Array of core rights.
131 * Each of these should have a corresponding message of the form
132 * "right-$right".
133 * @showinitializer
134 */
135 private const CORE_RIGHTS = [
136 'apihighlimits',
137 'applychangetags',
138 'autoconfirmed',
139 'autocreateaccount',
140 'autopatrol',
141 'bigdelete',
142 'block',
143 'blockemail',
144 'bot',
145 'browsearchive',
146 'changetags',
147 'createaccount',
148 'createpage',
149 'createtalk',
150 'delete',
151 'delete-redirect',
152 'deletechangetags',
153 'deletedhistory',
154 'deletedtext',
155 'deletelogentry',
156 'deleterevision',
157 'edit',
158 'editcontentmodel',
159 'editinterface',
160 'editprotected',
161 'editmyoptions',
162 'editmyprivateinfo',
163 'editmyusercss',
164 'editmyuserjson',
165 'editmyuserjs',
166 'editmyuserjsredirect',
167 'editmywatchlist',
168 'editsemiprotected',
169 'editsitecss',
170 'editsitejson',
171 'editsitejs',
172 'editusercss',
173 'edituserjson',
174 'edituserjs',
175 'hideuser',
176 'import',
177 'importupload',
178 'ipblock-exempt',
179 'logentryimport',
180 'managechangetags',
181 'markbotedits',
182 'mergehistory',
183 'minoredit',
184 'move',
185 'movefile',
186 'move-categorypages',
187 'move-rootuserpages',
188 'move-subpages',
189 'nominornewtalk',
190 'noratelimit',
191 'override-export-depth',
192 'pagelang',
193 'patrol',
194 'patrolmarks',
195 'protect',
196 'read',
197 'renameuser',
198 'reupload',
199 'reupload-own',
200 'reupload-shared',
201 'rollback',
202 'sendemail',
203 'siteadmin',
204 'suppressionlog',
205 'suppressredirect',
206 'suppressrevision',
207 'unblockself',
208 'undelete',
209 'unwatchedpages',
210 'upload',
211 'upload_by_url',
212 'userrights',
213 'userrights-interwiki',
214 'viewmyprivateinfo',
215 'viewmywatchlist',
216 'viewsuppressed',
217 ];
218
219 /**
220 * List of implicit rights.
221 * These should not have a corresponding message of the form
222 * "right-$right".
223 * @showinitializer
224 */
225 private const CORE_IMPLICIT_RIGHTS = [
226 'renderfile',
227 'renderfile-nonstandard',
228 'stashedit',
229 'stashbasehtml',
230 'mailpassword',
231 'changeemail',
232 'confirmemail',
233 'linkpurge',
234 'purge',
235 ];
236
237 public function __construct(
238 ServiceOptions $options,
239 SpecialPageFactory $specialPageFactory,
240 NamespaceInfo $nsInfo,
241 GroupPermissionsLookup $groupPermissionsLookup,
242 UserGroupManager $userGroupManager,
243 BlockManager $blockManager,
244 BlockErrorFormatter $blockErrorFormatter,
245 HookContainer $hookContainer,
246 UserIdentityLookup $userIdentityLookup,
247 RedirectLookup $redirectLookup,
248 RestrictionStore $restrictionStore,
249 TitleFormatter $titleFormatter,
250 TempUserConfig $tempUserConfig,
251 UserFactory $userFactory,
252 ActionFactory $actionFactory
253 ) {
254 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
255 $this->options = $options;
256 $this->specialPageFactory = $specialPageFactory;
257 $this->nsInfo = $nsInfo;
258 $this->groupPermissionsLookup = $groupPermissionsLookup;
259 $this->userGroupManager = $userGroupManager;
260 $this->blockManager = $blockManager;
261 $this->blockErrorFormatter = $blockErrorFormatter;
262 $this->hookRunner = new HookRunner( $hookContainer );
263 $this->userIdentityLookup = $userIdentityLookup;
264 $this->redirectLookup = $redirectLookup;
265 $this->restrictionStore = $restrictionStore;
266 $this->titleFormatter = $titleFormatter;
267 $this->tempUserConfig = $tempUserConfig;
268 $this->userFactory = $userFactory;
269 $this->actionFactory = $actionFactory;
270 }
271
272 /**
273 * Can $user perform $action on a page?
274 *
275 * The method replaced Title::userCan()
276 * The $user parameter need to be superseded by UserIdentity value in future
277 * The $title parameter need to be superseded by PageIdentity value in future
278 *
279 * @param string $action
280 * @param User $user
281 * @param LinkTarget $page
282 * @param string $rigor One of PermissionManager::RIGOR_ constants
283 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
284 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
285 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
286 *
287 * @return bool
288 */
289 public function userCan( $action, User $user, LinkTarget $page, $rigor = self::RIGOR_SECURE ): bool {
290 return $this->getPermissionStatus( $action, $user, $page, $rigor, true )->isGood();
291 }
292
293 /**
294 * A convenience method for calling PermissionManager::userCan
295 * with PermissionManager::RIGOR_QUICK
296 *
297 * Suitable for use for nonessential UI controls in common cases, but
298 * _not_ for functional access control.
299 * May provide false positives, but should never provide a false negative.
300 *
301 * @see PermissionManager::userCan()
302 *
303 * @param string $action
304 * @param User $user
305 * @param LinkTarget $page
306 * @return bool
307 */
308 public function quickUserCan( $action, User $user, LinkTarget $page ): bool {
309 return $this->userCan( $action, $user, $page, self::RIGOR_QUICK );
310 }
311
312 /**
313 * Can $user perform $action on a page?
314 *
315 * This *does not* check throttles (User::pingLimiter()). If that's desired, use the Authority
316 * interface methods instead.
317 *
318 * @deprecated since 1.43 Use getPermissionStatus() instead.
319 *
320 * @param string $action Action that permission needs to be checked for
321 * @param User $user User to check
322 * @param LinkTarget $page
323 * @param string $rigor One of PermissionManager::RIGOR_ constants
324 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
325 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
326 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
327 * @param string[] $ignoreErrors Set this to a list of message keys
328 * whose corresponding errors may be ignored.
329 *
330 * @return array[] Permission errors.
331 * Each entry contains valid arguments for wfMessage() / MessageLocalizer::msg().
332 * The format is *different* from the normal "legacy error array", as used by
333 * Status::getErrorsArray() or PermissionStatus::toLegacyErrorArray():
334 * the first element of each entry can be a MessageSpecifier, not just a string.
335 * @phan-return non-empty-array[]
336 */
337 public function getPermissionErrors(
338 $action,
339 User $user,
340 LinkTarget $page,
341 $rigor = self::RIGOR_SECURE,
342 $ignoreErrors = []
343 ): array {
344 $status = $this->getPermissionStatus( $action, $user, $page, $rigor );
345 $result = [];
346
347 // Produce a result in the weird format used by this function
348 foreach ( $status->getErrors() as [ 'message' => $keyOrMsg, 'params' => $params ] ) {
349 $key = $keyOrMsg instanceof MessageSpecifier ? $keyOrMsg->getKey() : $keyOrMsg;
350 // Remove the errors being ignored.
351 if ( !in_array( $key, $ignoreErrors ) ) {
352 $result[] = [ $keyOrMsg, ...$params ];
353 }
354 }
355 return $result;
356 }
357
358 /**
359 * Like {@link getPermissionErrors}, but immediately throw if there are any errors.
360 *
361 * @param string $action Action that permission needs to be checked for
362 * @param User $user User to check
363 * @param LinkTarget $page
364 * @param string $rigor One of PermissionManager::RIGOR_ constants
365 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
366 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
367 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
368 * @param string[] $ignoreErrors Set this to a list of message keys
369 * whose corresponding errors may be ignored.
370 *
371 * @throws PermissionsError
372 */
373 public function throwPermissionErrors(
374 $action,
375 User $user,
376 LinkTarget $page,
377 $rigor = self::RIGOR_SECURE,
378 $ignoreErrors = []
379 ): void {
380 $status = $this->getPermissionStatus(
381 $action, $user, $page, $rigor );
382 if ( $status->hasMessagesExcept( ...$ignoreErrors ) ) {
383 throw new PermissionsError( $action, $status );
384 }
385 }
386
387 /**
388 * Check if user is blocked from editing a particular article. If the user does not
389 * have a block, this will return false.
390 *
391 * @param User $user
392 * @param PageIdentity|LinkTarget $page Title to check
393 * @param bool $fromReplica Whether to check the replica DB instead of the primary DB
394 * @return bool
395 */
396 public function isBlockedFrom( User $user, $page, $fromReplica = false ): bool {
397 return (bool)$this->getApplicableBlock(
398 'edit',
399 $user,
400 $fromReplica ? self::RIGOR_FULL : self::RIGOR_SECURE,
401 $page,
402 $user->getRequest()
403 );
404 }
405
406 /**
407 * Can $user perform $action on a page?
408 *
409 * This *does not* check throttles (User::pingLimiter()). If that's desired, use the Authority
410 * interface methods instead.
411 *
412 * @param string $action Action that permission needs to be checked for
413 * @param User $user User to check
414 * @param LinkTarget $page
415 * @param string $rigor One of PermissionManager::RIGOR_ constants
416 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
417 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
418 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
419 * @param bool $short Set this to true to stop after the first permission error.
420 * @return PermissionStatus Permission errors as a status.
421 * Check `$status->isGood()` to tell if the user can perform the action.
422 * Use `$status->getMessages()` to display errors if the status is not good.
423 */
424 public function getPermissionStatus(
425 $action,
426 User $user,
427 LinkTarget $page,
428 $rigor = self::RIGOR_SECURE,
429 $short = false
430 ): PermissionStatus {
431 if ( !in_array( $rigor, [ self::RIGOR_QUICK, self::RIGOR_FULL, self::RIGOR_SECURE ] ) ) {
432 throw new InvalidArgumentException( "Invalid rigor parameter '$rigor'." );
433 }
434
435 // With RIGOR_QUICK we can assume automatic account creation will
436 // occur. At a higher rigor level, the caller is required to opt
437 // in by either passing in a temp placeholder user or by actually
438 // creating the account.
439 if ( $rigor === self::RIGOR_QUICK
440 && !$user->isRegistered()
441 && $this->tempUserConfig->isAutoCreateAction( $action )
442 ) {
443 $user = $this->userFactory->newTempPlaceholder();
444 }
445
446 # Read has special handling
447 if ( $action === 'read' ) {
448 $checks = [
449 [ $this, 'checkPermissionHooks' ],
450 [ $this, 'checkReadPermissions' ],
451 [ $this, 'checkUserBlock' ], // for wgBlockDisablesLogin
452 ];
453 } elseif ( $action === 'create' ) {
454 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
455 # or checkUserConfigPermissions here as it will lead to duplicate
456 # error messages. This is okay to do since anywhere that checks for
457 # create will also check for edit, and those checks are called for edit.
458 $checks = [
459 [ $this, 'checkQuickPermissions' ],
460 [ $this, 'checkPermissionHooks' ],
461 [ $this, 'checkPageRestrictions' ],
462 [ $this, 'checkCascadingSourcesRestrictions' ],
463 [ $this, 'checkActionPermissions' ],
464 [ $this, 'checkUserBlock' ],
465 ];
466 } else {
467 // Exclude checkUserConfigPermissions on actions that cannot change the
468 // content of the configuration pages.
469 $skipUserConfigActions = [
470 // Allow patrolling per T21818
471 'patrol',
472
473 // Allow admins and oversighters to delete. For user pages we want to avoid the
474 // situation where an unprivileged user can post abusive content on
475 // their subpages and only very highly privileged users could remove it.
476 // See T200176.
477 'delete',
478 'deleterevision',
479 'suppressrevision',
480
481 // Allow admins and oversighters to view deleted content, even if they
482 // cannot restore it. See T202989
483 'deletedhistory',
484 'deletedtext',
485 'viewsuppressed',
486 ];
487
488 $checks = [
489 [ $this, 'checkQuickPermissions' ],
490 [ $this, 'checkPermissionHooks' ],
491 [ $this, 'checkSpecialsAndNSPermissions' ],
492 [ $this, 'checkSiteConfigPermissions' ],
493 ];
494 if ( !in_array( $action, $skipUserConfigActions, true ) ) {
495 $checks[] = [ $this, 'checkUserConfigPermissions' ];
496 }
497 $checks = [
498 ...$checks,
499 [ $this, 'checkPageRestrictions' ],
500 [ $this, 'checkCascadingSourcesRestrictions' ],
501 [ $this, 'checkActionPermissions' ],
502 [ $this, 'checkUserBlock' ]
503 ];
504 }
505
506 $status = PermissionStatus::newEmpty();
507 foreach ( $checks as $method ) {
508 $method( $action, $user, $status, $rigor, $short, $page );
509
510 if ( $short && !$status->isGood() ) {
511 break;
512 }
513 }
514 if ( !$status->isGood() ) {
515 $errors = $status->toLegacyErrorArray();
516 $this->hookRunner->onPermissionErrorAudit( $page, $user, $action, $rigor, $errors );
517 }
518
519 return $status;
520 }
521
522 /**
523 * Check various permission hooks
524 *
525 * @param string $action The action to check
526 * @param User $user User to check
527 * @param PermissionStatus $status Current errors
528 * @param string $rigor One of PermissionManager::RIGOR_ constants
529 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
530 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
531 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
532 * @param bool $short Short circuit on first error
533 * @param LinkTarget $page
534 */
535 private function checkPermissionHooks(
536 $action,
537 User $user,
538 PermissionStatus $status,
539 $rigor,
540 $short,
541 LinkTarget $page
542 ): void {
543 // TODO: remove when LinkTarget usage will expand further
544 $title = Title::newFromLinkTarget( $page );
545 // Use getUserPermissionsErrors instead
546 $result = '';
547 if ( !$this->hookRunner->onUserCan( $title, $user, $action, $result ) ) {
548 if ( !$result ) {
549 $status->fatal( 'badaccess-group0' );
550 }
551 return;
552 }
553 // Check getUserPermissionsErrors hook
554 if ( !$this->hookRunner->onGetUserPermissionsErrors( $title, $user, $action, $result ) ) {
555 $this->resultToStatus( $status, $result );
556 }
557 // Check getUserPermissionsErrorsExpensive hook
558 if (
559 $rigor !== self::RIGOR_QUICK
560 && !( $short && !$status->isGood() )
561 && !$this->hookRunner->onGetUserPermissionsErrorsExpensive(
562 $title, $user, $action, $result )
563 ) {
564 $this->resultToStatus( $status, $result );
565 }
566 }
567
568 /**
569 * Add the resulting error code to the errors array
570 *
571 * @param PermissionStatus $status Current errors
572 * @param array|string|MessageSpecifier|false $result Result of errors
573 */
574 private function resultToStatus( PermissionStatus $status, $result ): void {
575 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
576 // A single array representing an error
577 $status->fatal( ...$result );
578 } elseif ( is_array( $result ) && count( $result ) && is_array( $result[0] ) ) {
579 // A nested array representing multiple errors
580 foreach ( $result as $result1 ) {
581 $this->resultToStatus( $status, $result1 );
582 }
583 } elseif ( is_string( $result ) && $result !== '' ) {
584 // A string representing a message-id
585 $status->fatal( $result );
586 } elseif ( $result instanceof MessageSpecifier ) {
587 // A message specifier representing an error
588 $status->fatal( $result );
589 } elseif ( $result === false ) {
590 // a generic "We don't want them to do that"
591 $status->fatal( 'badaccess-group0' );
592 }
593 // If we got here, $results is the empty array or empty string, which mean no errors.
594 }
595
596 /**
597 * Check that the user is allowed to read this page.
598 *
599 * @param string $action The action to check
600 * @param User $user User to check
601 * @param PermissionStatus $status Current errors
602 * @param string $rigor One of PermissionManager::RIGOR_ constants
603 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
604 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
605 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
606 * @param bool $short Short circuit on first error
607 * @param LinkTarget $page
608 */
609 private function checkReadPermissions(
610 $action,
611 User $user,
612 PermissionStatus $status,
613 $rigor,
614 $short,
615 LinkTarget $page
616 ): void {
617 // TODO: remove when LinkTarget usage will expand further
618 $title = Title::newFromLinkTarget( $page );
619
620 $whiteListRead = $this->options->get( MainConfigNames::WhitelistRead );
621 $allowed = false;
622 if ( $this->isEveryoneAllowed( 'read' ) ) {
623 // Shortcut for public wikis, allows skipping quite a bit of code
624 $allowed = true;
625 } elseif ( $this->userHasRight( $user, 'read' ) ) {
626 // If the user is allowed to read pages, he is allowed to read all pages
627 $allowed = true;
628 } elseif ( $this->isSameSpecialPage( 'Userlogin', $page )
629 || $this->isSameSpecialPage( 'PasswordReset', $page )
630 || $this->isSameSpecialPage( 'Userlogout', $page )
631 ) {
632 // Always grant access to the login page.
633 // Even anons need to be able to log in.
634 $allowed = true;
635 } elseif ( $this->isSameSpecialPage( 'RunJobs', $page ) ) {
636 // relies on HMAC key signature alone
637 $allowed = true;
638 } elseif ( is_array( $whiteListRead ) && count( $whiteListRead ) ) {
639 // Time to check the whitelist
640 // Only do these checks if there's something to check against
641 $name = $title->getPrefixedText();
642 $dbName = $title->getPrefixedDBkey();
643
644 // Check for explicit whitelisting with and without underscores
645 if ( in_array( $name, $whiteListRead, true )
646 || in_array( $dbName, $whiteListRead, true )
647 ) {
648 $allowed = true;
649 } elseif ( $page->getNamespace() === NS_MAIN ) {
650 // Old settings might have the title prefixed with
651 // a colon for main-namespace pages
652 if ( in_array( ':' . $name, $whiteListRead ) ) {
653 $allowed = true;
654 }
655 } elseif ( $title->isSpecialPage() ) {
656 // If it's a special page, ditch the subpage bit and check again
657 $name = $title->getDBkey();
658 [ $name, /* $subpage */ ] =
659 $this->specialPageFactory->resolveAlias( $name );
660 if ( $name ) {
661 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
662 if ( in_array( $pure, $whiteListRead, true ) ) {
663 $allowed = true;
664 }
665 }
666 }
667 }
668
669 $whitelistReadRegexp = $this->options->get( MainConfigNames::WhitelistReadRegexp );
670 if ( !$allowed && is_array( $whitelistReadRegexp )
671 && $whitelistReadRegexp
672 ) {
673 $name = $title->getPrefixedText();
674 // Check for regex whitelisting
675 foreach ( $whitelistReadRegexp as $listItem ) {
676 if ( preg_match( $listItem, $name ) ) {
677 $allowed = true;
678 break;
679 }
680 }
681 }
682
683 if ( !$allowed ) {
684 # If the title is not whitelisted, give extensions a chance to do so...
685 $this->hookRunner->onTitleReadWhitelist( $title, $user, $allowed );
686 if ( !$allowed ) {
687 $this->missingPermissionError( $action, $short, $status );
688 }
689 }
690 }
691
692 /**
693 * Add an error to the status when an action isn't allowed to be performed.
694 *
695 * @param string $action The action to check
696 * @param bool $short Short circuit on first error
697 * @param PermissionStatus $status
698 */
699 private function missingPermissionError( string $action, bool $short, PermissionStatus $status ): void {
700 // We avoid expensive display logic for quickUserCan's and such
701 if ( $short ) {
702 $status->fatal( 'badaccess-group0' );
703 return;
704 }
705
706 // TODO: it would be a good idea to replace the method below with something else like
707 // maybe callback injection
708 $context = RequestContext::getMain();
709 $fatalStatus = $this->newFatalPermissionDeniedStatus( $action, $context );
710 $status->merge( $fatalStatus );
711 $statusPermission = $fatalStatus->getPermission();
712 if ( $statusPermission ) {
713 $status->setPermission( $statusPermission );
714 }
715 }
716
717 /**
718 * Factory function for fatal permission-denied errors
719 *
720 * @internal for use by UserAuthority
721 *
722 * @param string $permission User right required
723 * @param IContextSource $context
724 *
725 * @return PermissionStatus
726 */
727 public function newFatalPermissionDeniedStatus( $permission, IContextSource $context ): StatusValue {
728 $groups = [];
729 foreach ( $this->groupPermissionsLookup->getGroupsWithPermission( $permission ) as $group ) {
730 $groups[] = UserGroupMembership::getLinkWiki( $group, $context );
731 }
732
733 if ( $groups ) {
734 return PermissionStatus::newFatal(
735 'badaccess-groups',
736 Message::listParam( $groups, 'comma' ),
737 count( $groups )
738 );
739 }
740
741 $status = PermissionStatus::newFatal( 'badaccess-group0' );
742 $status->setPermission( $permission );
743 return $status;
744 }
745
746 /**
747 * Whether a title resolves to the named special page.
748 *
749 * @param string $name The special page name
750 * @param LinkTarget $page
751 * @return bool
752 */
753 private function isSameSpecialPage( $name, LinkTarget $page ): bool {
754 if ( $page->getNamespace() === NS_SPECIAL ) {
755 [ $pageName ] = $this->specialPageFactory->resolveAlias( $page->getDBkey() );
756 if ( $name === $pageName ) {
757 return true;
758 }
759 }
760 return false;
761 }
762
763 /**
764 * Check that the user isn't blocked from editing.
765 *
766 * @param string $action The action to check
767 * @param User $user User to check
768 * @param PermissionStatus $status Current errors
769 * @param string $rigor One of PermissionManager::RIGOR_ constants
770 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
771 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
772 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
773 * @param bool $short Short circuit on first error
774 * @param LinkTarget $page
775 */
776 private function checkUserBlock(
777 $action,
778 User $user,
779 PermissionStatus $status,
780 $rigor,
781 $short,
782 LinkTarget $page
783 ): void {
784 $block = $this->getApplicableBlock(
785 $action,
786 $user,
787 $rigor,
788 $page,
789 $user->getRequest()
790 );
791
792 if ( $block ) {
793 // @todo FIXME: Pass the relevant context into this function.
794 $context = RequestContext::getMain();
795 $messages = $this->blockErrorFormatter->getMessages(
796 $block,
797 $user,
798 $context->getRequest()->getIP()
799 );
800
801 foreach ( $messages as $message ) {
802 // TODO: We can pass $message directly once getPermissionErrors() is removed.
803 // For now we store the message key as a string here out of overabundance of caution,
804 // because there is a test case verifying that block messages use strings in that format.
805 $status->fatal( $message->getKey(), ...$message->getParams() );
806 }
807 }
808 }
809
810 /**
811 * Return the Block object applicable for the given permission check, if any.
812 *
813 * @internal for use by UserAuthority only
814 *
815 * @param string $action The action to check
816 * @param User $user User to check
817 * @param string $rigor One of PermissionManager::RIGOR_ constants
818 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
819 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
820 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
821 * @param LinkTarget|PageReference|null $page
822 * @param WebRequest|null $request The request to get the IP and cookies
823 * from. If this is null, IP and cookie blocks will not be checked.
824 * @return ?Block
825 */
826 public function getApplicableBlock(
827 string $action,
828 User $user,
829 string $rigor,
830 $page,
831 ?WebRequest $request
832 ): ?Block {
833 // Unblocking handled in SpecialUnblock
834 if ( $rigor === self::RIGOR_QUICK || in_array( $action, [ 'unblock' ] ) ) {
835 return null;
836 }
837
838 // Optimize for a very common case
839 if ( $action === 'read' && !$this->options->get( MainConfigNames::BlockDisablesLogin ) ) {
840 return null;
841 }
842
843 // Implicit rights aren't blockable (T350117, T350202).
844 if ( in_array( $action, $this->getImplicitRights(), true ) ) {
845 return null;
846 }
847
848 $useReplica = $rigor !== self::RIGOR_SECURE;
849 $isExempt = $this->userHasRight( $user, 'ipblock-exempt' );
850 $requestIfNotExempt = $isExempt ? null : $request;
851
852 // Create account blocks are implemented separately due to weird IP exemption rules
853 if ( in_array( $action, [ 'createaccount', 'autocreateaccount' ], true ) ) {
854 return $this->blockManager->getCreateAccountBlock(
855 $user,
856 $requestIfNotExempt,
857 $useReplica
858 );
859 }
860
861 $block = $this->blockManager->getBlock( $user, $requestIfNotExempt, $useReplica );
862 if ( !$block ) {
863 return null;
864 }
865 $userIsHidden = $block->getHideName();
866
867 // Remove elements from the block that explicitly allow the action
868 // (like "read" or "upload").
869 $block = $this->blockManager->filter(
870 $block,
871 static function ( AbstractBlock $originalBlock ) use ( $action ) {
872 // Remove the block if it explicitly allows the action
873 return $originalBlock->appliesToRight( $action ) !== false;
874 }
875 );
876 if ( !$block ) {
877 return null;
878 }
879
880 // Convert the input page to a Title
881 $targetTitle = null;
882 if ( $page ) {
883 $targetTitle = $page instanceof PageReference ?
884 Title::castFromPageReference( $page ) :
885 Title::castFromLinkTarget( $page );
886
887 if ( !$targetTitle->canExist() ) {
888 $targetTitle = null;
889 }
890 }
891
892 // What gets passed into this method is a user right, not an action name.
893 // There is no way to instantiate an action by restriction. However, this
894 // will get the action where the restriction is the same. This may result
895 // in actions being blocked that shouldn't be.
896 $actionInfo = $this->actionFactory->getActionInfo( $action, $targetTitle );
897
898 // Ensure that the retrieved action matches the restriction.
899 if ( $actionInfo && $actionInfo->getRestriction() !== $action ) {
900 $actionInfo = null;
901 }
902
903 // Return null if the action does not require an unblocked user.
904 // If no ActionInfo is returned, assume that the action requires unblock
905 // which is the default.
906 // NOTE: We may get null here even for known actions, if a wiki's main page
907 // is set to a special page, e.g. Special:MyLanguage/Main_Page (T348451, T346036).
908 if ( $actionInfo && !$actionInfo->requiresUnblock() ) {
909 return null;
910 }
911
912 // Remove elements from the block that do not apply to the specific page
913 if ( $targetTitle ) {
914 $targetIsUserTalk = !$userIsHidden && $targetTitle->equals( $user->getTalkPage() );
915 $block = $this->blockManager->filter(
916 $block,
917 static function ( AbstractBlock $originalBlock )
918 use ( $action, $targetTitle, $targetIsUserTalk ) {
919 if ( $originalBlock->appliesToRight( $action ) ) {
920 // An action block takes precedence over appliesToTitle().
921 // Block::appliesToRight('edit') always returns null,
922 // allowing title-based exemptions to take effect.
923 return true;
924 } elseif ( $targetIsUserTalk ) {
925 // Special handling for a user's own talk page. The block is not aware
926 // of the user, so this must be done here.
927 return $originalBlock->appliesToUsertalk( $targetTitle );
928 } else {
929 return $originalBlock->appliesToTitle( $targetTitle );
930 }
931 }
932 );
933 }
934
935 if ( $targetTitle && $block
936 && $block instanceof AbstractBlock // for phan
937 ) {
938 // Allow extensions to let a blocked user access a particular page
939 $allowUsertalk = $block->isUsertalkEditAllowed();
940 $blocked = true;
941 $this->hookRunner->onUserIsBlockedFrom( $user, $targetTitle, $blocked, $allowUsertalk );
942 if ( !$blocked ) {
943 $block = null;
944 }
945 }
946 return $block;
947 }
948
949 /**
950 * Run easy-to-test (or "quick") permissions checks for a given action.
951 *
952 * @param string $action The action to check
953 * @param User $user User to check
954 * @param PermissionStatus $status Current errors
955 * @param string $rigor One of PermissionManager::RIGOR_ constants
956 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
957 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
958 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
959 * @param bool $short Short circuit on first error
960 * @param LinkTarget $page
961 */
962 private function checkQuickPermissions(
963 $action,
964 User $user,
965 PermissionStatus $status,
966 $rigor,
967 $short,
968 LinkTarget $page
969 ): void {
970 // TODO: remove when LinkTarget usage will expand further
971 $title = Title::newFromLinkTarget( $page );
972
973 // This method is always called first, so $status is guaranteed to be empty, so we can
974 // just pass an empty $errors array, instead of converting it to the legacy format and back.
975 $errors = [];
976 if ( !$this->hookRunner->onTitleQuickPermissions( $title, $user, $action,
977 $errors, $rigor !== self::RIGOR_QUICK, $short )
978 ) {
979 // $errors is an array of results, not a result, but resultToStatus() handles
980 // arrays of arrays with recursion so this will work
981 $this->resultToStatus( $status, $errors );
982 return;
983 }
984
985 $isSubPage =
986 $this->nsInfo->hasSubpages( $title->getNamespace() ) &&
987 strpos( $title->getText(), '/' ) !== false;
988
989 if ( $action === 'create' ) {
990 if (
991 ( $this->nsInfo->isTalk( $title->getNamespace() ) &&
992 !$this->userHasRight( $user, 'createtalk' ) ) ||
993 ( !$this->nsInfo->isTalk( $title->getNamespace() ) &&
994 !$this->userHasRight( $user, 'createpage' ) )
995 ) {
996 $status->fatal( $user->isNamed() ? 'nocreate-loggedin' : 'nocreatetext' );
997 }
998 } elseif ( $action === 'move' ) {
999 if ( !$this->userHasRight( $user, 'move-rootuserpages' )
1000 && $title->getNamespace() === NS_USER && !$isSubPage
1001 ) {
1002 // Show user page-specific message only if the user can move other pages
1003 $status->fatal( 'cant-move-user-page' );
1004 }
1005
1006 // Check if user is allowed to move files if it's a file
1007 if ( $title->getNamespace() === NS_FILE &&
1008 !$this->userHasRight( $user, 'movefile' )
1009 ) {
1010 $status->fatal( 'movenotallowedfile' );
1011 }
1012
1013 // Check if user is allowed to move category pages if it's a category page
1014 if ( $title->getNamespace() === NS_CATEGORY &&
1015 !$this->userHasRight( $user, 'move-categorypages' )
1016 ) {
1017 $status->fatal( 'cant-move-category-page' );
1018 }
1019
1020 if ( !$this->userHasRight( $user, 'move' ) ) {
1021 // User can't move anything
1022 $userCanMove = $this->groupPermissionsLookup
1023 ->groupHasPermission( 'user', 'move' );
1024 $autoconfirmedCanMove = $this->groupPermissionsLookup
1025 ->groupHasPermission( 'autoconfirmed', 'move' );
1026 if ( $user->isAnon()
1027 && ( $userCanMove || $autoconfirmedCanMove )
1028 ) {
1029 // custom message if logged-in users without any special rights can move
1030 $status->fatal( 'movenologintext' );
1031 } elseif ( $user->isTemp() && $autoconfirmedCanMove ) {
1032 // Temp user may be able to move if they log in as a proper account
1033 $status->fatal( 'movenologintext' );
1034 } else {
1035 $status->fatal( 'movenotallowed' );
1036 }
1037 }
1038 } elseif ( $action === 'move-target' ) {
1039 if ( !$this->userHasRight( $user, 'move' ) ) {
1040 // User can't move anything
1041 $status->fatal( 'movenotallowed' );
1042 } elseif ( !$this->userHasRight( $user, 'move-rootuserpages' )
1043 && $title->getNamespace() === NS_USER
1044 && !$isSubPage
1045 ) {
1046 // Show user page-specific message only if the user can move other pages
1047 $status->fatal( 'cant-move-to-user-page' );
1048 } elseif ( !$this->userHasRight( $user, 'move-categorypages' )
1049 && $title->getNamespace() === NS_CATEGORY
1050 ) {
1051 // Show category page-specific message only if the user can move other pages
1052 $status->fatal( 'cant-move-to-category-page' );
1053 }
1054 } elseif ( $action === 'autocreateaccount' ) {
1055 // createaccount implies autocreateaccount
1056 if ( !$this->userHasAnyRight( $user, 'autocreateaccount', 'createaccount' ) ) {
1057 $this->missingPermissionError( $action, $short, $status );
1058 }
1059 } elseif ( !$this->userHasRight( $user, $action ) ) {
1060 $this->missingPermissionError( $action, $short, $status );
1061 }
1062 }
1063
1064 /**
1065 * Check for any page_restrictions table requirements on this page.
1066 *
1067 * If the page has multiple restrictions, the user must have
1068 * all of those rights to perform the action in question.
1069 *
1070 * @param string $action The action to check
1071 * @param UserIdentity $user User to check
1072 * @param PermissionStatus $status Current errors
1073 * @param string $rigor One of PermissionManager::RIGOR_ constants
1074 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1075 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1076 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1077 * @param bool $short Short circuit on first error
1078 * @param LinkTarget $page
1079 */
1080 private function checkPageRestrictions(
1081 $action,
1082 UserIdentity $user,
1083 PermissionStatus $status,
1084 $rigor,
1085 $short,
1086 LinkTarget $page
1087 ): void {
1088 // TODO: remove & rework upon further use of LinkTarget
1089 $title = Title::newFromLinkTarget( $page );
1090 foreach ( $this->restrictionStore->getRestrictions( $title, $action ) as $right ) {
1091 // Backwards compatibility, rewrite sysop -> editprotected
1092 if ( $right === 'sysop' ) {
1093 $right = 'editprotected';
1094 }
1095 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
1096 if ( $right === 'autoconfirmed' ) {
1097 $right = 'editsemiprotected';
1098 }
1099 if ( $right == '' ) {
1100 continue;
1101 }
1102 if ( !$this->userHasRight( $user, $right ) ) {
1103 $status->fatal( 'protectedpagetext', $right, $action );
1104 } elseif ( $this->restrictionStore->areRestrictionsCascading( $title ) &&
1105 !$this->userHasRight( $user, 'protect' )
1106 ) {
1107 $status->fatal( 'protectedpagetext', 'protect', $action );
1108 }
1109 }
1110 }
1111
1112 /**
1113 * Check restrictions on cascading pages.
1114 *
1115 * @param string $action The action to check
1116 * @param UserIdentity $user User to check
1117 * @param PermissionStatus $status Current errors
1118 * @param string $rigor One of PermissionManager::RIGOR_ constants
1119 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1120 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1121 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1122 * @param bool $short Short circuit on first error
1123 * @param LinkTarget $page
1124 */
1125 private function checkCascadingSourcesRestrictions(
1126 $action,
1127 UserIdentity $user,
1128 PermissionStatus $status,
1129 $rigor,
1130 $short,
1131 LinkTarget $page
1132 ): void {
1133 // TODO: remove & rework upon further use of LinkTarget
1134 $title = Title::newFromLinkTarget( $page );
1135
1136 if ( $rigor !== self::RIGOR_QUICK && !$title->isUserConfigPage() ) {
1137 [ $sources, $restrictions, $tlSources, $ilSources ] = $this->restrictionStore
1138 ->getCascadeProtectionSources( $title );
1139
1140 // If the file Wikitext isn't transcluded then we
1141 // don't care about edit cascade restrictions for edit action
1142 if ( $action === 'edit' && $page->getNamespace() === NS_FILE && !$tlSources ) {
1143 return;
1144 }
1145
1146 // For the purposes of cascading protection, edit restrictions should apply to uploads or moves
1147 // Thus remap upload and move to edit
1148 // Unless the file content itself is not transcluded
1149 if ( $ilSources && ( $action === 'upload' || $action === 'move' ) ) {
1150 $restrictedAction = 'edit';
1151 } else {
1152 $restrictedAction = $action;
1153 }
1154
1155 // Cascading protection depends on more than this page...
1156 // Several cascading protected pages may include this page...
1157 // Check each cascading level
1158 // This is only for protection restrictions, not for all actions
1159 if ( isset( $restrictions[$restrictedAction] ) ) {
1160 foreach ( $restrictions[$restrictedAction] as $right ) {
1161 // Backwards compatibility, rewrite sysop -> editprotected
1162 if ( $right === 'sysop' ) {
1163 $right = 'editprotected';
1164 }
1165 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
1166 if ( $right === 'autoconfirmed' ) {
1167 $right = 'editsemiprotected';
1168 }
1169 if ( $right != '' && !$this->userHasAllRights( $user, 'protect', $right ) ) {
1170 $wikiPages = '';
1171 foreach ( $sources as $pageIdentity ) {
1172 $wikiPages .= '* [[:' . $this->titleFormatter->getPrefixedText( $pageIdentity ) . "]]\n";
1173 }
1174 $status->fatal( 'cascadeprotected', count( $sources ), $wikiPages, $action );
1175 }
1176 }
1177 }
1178 }
1179 }
1180
1181 /**
1182 * Check action permissions not already checked in checkQuickPermissions
1183 *
1184 * @param string $action The action to check
1185 * @param User $user User to check
1186 * @param PermissionStatus $status Current errors
1187 * @param string $rigor One of PermissionManager::RIGOR_ constants
1188 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1189 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1190 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1191 * @param bool $short Short circuit on first error
1192 * @param LinkTarget $page
1193 */
1194 private function checkActionPermissions(
1195 $action,
1196 User $user,
1197 PermissionStatus $status,
1198 $rigor,
1199 $short,
1200 LinkTarget $page
1201 ): void {
1202 // TODO: remove & rework upon further use of LinkTarget
1203 $title = Title::newFromLinkTarget( $page );
1204
1205 if ( $rigor !== self::RIGOR_QUICK && !defined( 'MW_NO_SESSION' ) ) {
1206 $sessionRestrictions = $user->getRequest()->getSession()->getRestrictions();
1207 if ( $sessionRestrictions ) {
1208 $userCan = $sessionRestrictions->userCan( $title );
1209 if ( !$userCan->isOK() ) {
1210 $status->merge( $userCan );
1211 }
1212 }
1213 }
1214
1215 if ( $action === 'protect' ) {
1216 if ( !$this->getPermissionStatus( 'edit', $user, $title, $rigor, true )->isGood() ) {
1217 // If they can't edit, they shouldn't protect.
1218 $status->fatal( 'protect-cantedit' );
1219 }
1220 } elseif ( $action === 'create' ) {
1221 $createProtection = $this->restrictionStore->getCreateProtection( $title );
1222 if ( $createProtection ) {
1223 if ( $createProtection['permission'] == ''
1224 || !$this->userHasRight( $user, $createProtection['permission'] )
1225 ) {
1226 $protectUserIdentity = $this->userIdentityLookup
1227 ->getUserIdentityByUserId( $createProtection['user'] );
1228 $status->fatal(
1229 'titleprotected',
1230 $protectUserIdentity ? $protectUserIdentity->getName() : '',
1231 $createProtection['reason']
1232 );
1233 }
1234 }
1235 } elseif ( $action === 'move' ) {
1236 // Check for immobile pages
1237 if ( !$this->nsInfo->isMovable( $title->getNamespace() ) ) {
1238 // Specific message for this case
1239 $nsText = $title->getNsText();
1240 if ( $nsText === '' ) {
1241 $nsText = wfMessage( 'blanknamespace' )->text();
1242 }
1243 $status->fatal( 'immobile-source-namespace', $nsText );
1244 } elseif ( !$title->isMovable() ) {
1245 // Less specific message for rarer cases
1246 $status->fatal( 'immobile-source-page' );
1247 }
1248 } elseif ( $action === 'move-target' ) {
1249 if ( !$this->nsInfo->isMovable( $title->getNamespace() ) ) {
1250 $nsText = $title->getNsText();
1251 if ( $nsText === '' ) {
1252 $nsText = wfMessage( 'blanknamespace' )->text();
1253 }
1254 $status->fatal( 'immobile-target-namespace', $nsText );
1255 } elseif ( !$title->isMovable() ) {
1256 $status->fatal( 'immobile-target-page' );
1257 }
1258 } elseif ( $action === 'delete' || $action === 'delete-redirect' ) {
1259 $tempStatus = PermissionStatus::newEmpty();
1260 $this->checkPageRestrictions( 'edit', $user, $tempStatus, $rigor, true, $title );
1261 if ( $tempStatus->isGood() ) {
1262 $this->checkCascadingSourcesRestrictions( 'edit',
1263 $user, $tempStatus, $rigor, true, $title );
1264 }
1265 if ( !$tempStatus->isGood() ) {
1266 // If protection keeps them from editing, they shouldn't be able to delete.
1267 $status->fatal( 'deleteprotected' );
1268 }
1269 if ( $rigor !== self::RIGOR_QUICK
1270 && $action === 'delete'
1271 && $this->options->get( MainConfigNames::DeleteRevisionsLimit )
1272 && !$this->userCan( 'bigdelete', $user, $title )
1273 && $title->isBigDeletion()
1274 ) {
1275 // NOTE: This check is deprecated since 1.37, see T288759
1276 $status->fatal(
1277 'delete-toobig',
1278 Message::numParam( $this->options->get( MainConfigNames::DeleteRevisionsLimit ) )
1279 );
1280 }
1281 } elseif ( $action === 'undelete' ) {
1282 if ( !$this->getPermissionStatus( 'edit', $user, $title, $rigor, true )->isGood() ) {
1283 // Undeleting implies editing
1284 $status->fatal( 'undelete-cantedit' );
1285 }
1286 if ( !$title->exists()
1287 && !$this->getPermissionStatus( 'create', $user, $title, $rigor, true )->isGood()
1288 ) {
1289 // Undeleting where nothing currently exists implies creating
1290 $status->fatal( 'undelete-cantcreate' );
1291 }
1292 } elseif ( $action === 'edit' ) {
1293 if ( $this->options->get( MainConfigNames::EmailConfirmToEdit )
1294 && !$user->isEmailConfirmed()
1295 ) {
1296 $status->fatal( 'confirmedittext' );
1297 }
1298
1299 if ( !$title->exists() ) {
1300 $status->merge(
1301 $this->getPermissionStatus(
1302 'create',
1303 $user,
1304 $title,
1305 $rigor,
1306 true
1307 )
1308 );
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Check permissions on special pages & namespaces
1315 *
1316 * @param string $action The action to check
1317 * @param UserIdentity $user User to check
1318 * @param PermissionStatus $status Current errors
1319 * @param string $rigor One of PermissionManager::RIGOR_ constants
1320 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1321 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1322 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1323 * @param bool $short Short circuit on first error
1324 * @param LinkTarget $page
1325 */
1326 private function checkSpecialsAndNSPermissions(
1327 $action,
1328 UserIdentity $user,
1329 PermissionStatus $status,
1330 $rigor,
1331 $short,
1332 LinkTarget $page
1333 ): void {
1334 // TODO: remove & rework upon further use of LinkTarget
1335 $title = Title::newFromLinkTarget( $page );
1336
1337 // Only 'createaccount' can be performed on special pages,
1338 // which don't actually exist in the DB.
1339 if ( $title->getNamespace() === NS_SPECIAL
1340 && !in_array( $action, [ 'createaccount', 'autocreateaccount' ], true )
1341 ) {
1342 $status->fatal( 'ns-specialprotected' );
1343 }
1344
1345 // Check $wgNamespaceProtection for restricted namespaces
1346 if ( $this->isNamespaceProtected( $title->getNamespace(), $user )
1347 // Allow admins and oversighters to view deleted content, even if they
1348 // cannot restore it. See T362536.
1349 && !in_array( $action, [ 'deletedhistory', 'deletedtext', 'viewsuppressed' ], true )
1350 ) {
1351 $ns = $title->getNamespace() === NS_MAIN ?
1352 wfMessage( 'nstab-main' )->text() : $title->getNsText();
1353 if ( $title->getNamespace() === NS_MEDIAWIKI ) {
1354 $status->fatal( 'protectedinterface', $action );
1355 } else {
1356 $status->fatal( 'namespaceprotected', $ns, $action );
1357 }
1358 }
1359 }
1360
1361 /**
1362 * Check sitewide CSS/JSON/JS permissions
1363 *
1364 * @param string $action The action to check
1365 * @param UserIdentity $user User to check
1366 * @param PermissionStatus $status Current errors
1367 * @param string $rigor One of PermissionManager::RIGOR_ constants
1368 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1369 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1370 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1371 * @param bool $short Short circuit on first error
1372 * @param LinkTarget $page
1373 */
1374 private function checkSiteConfigPermissions(
1375 $action,
1376 UserIdentity $user,
1377 PermissionStatus $status,
1378 $rigor,
1379 $short,
1380 LinkTarget $page
1381 ): void {
1382 // TODO: remove & rework upon further use of LinkTarget
1383 $title = Title::newFromLinkTarget( $page );
1384
1385 if ( $action === 'patrol' ) {
1386 return;
1387 }
1388
1389 if ( in_array( $action, [ 'deletedhistory', 'deletedtext', 'viewsuppressed' ], true ) ) {
1390 // Allow admins and oversighters to view deleted content, even if they
1391 // cannot restore it. See T202989
1392 // Not using the same handling in `getPermissionStatus` as the checks
1393 // for skipping `checkUserConfigPermissions` since normal admins can delete
1394 // user scripts, but not sitewide scripts
1395 return;
1396 }
1397
1398 // Sitewide CSS/JSON/JS/RawHTML changes, like all NS_MEDIAWIKI changes, also require the
1399 // editinterface right. That's implemented as a restriction so no check needed here.
1400 if ( $title->isSiteCssConfigPage() && !$this->userHasRight( $user, 'editsitecss' ) ) {
1401 $status->fatal( 'sitecssprotected', $action );
1402 } elseif ( $title->isSiteJsonConfigPage() && !$this->userHasRight( $user, 'editsitejson' ) ) {
1403 $status->fatal( 'sitejsonprotected', $action );
1404 } elseif ( $title->isSiteJsConfigPage() && !$this->userHasRight( $user, 'editsitejs' ) ) {
1405 $status->fatal( 'sitejsprotected', $action );
1406 }
1407 if ( $title->isRawHtmlMessage() && !$this->userCanEditRawHtmlPage( $user ) ) {
1408 $status->fatal( 'siterawhtmlprotected', $action );
1409 }
1410 }
1411
1412 /**
1413 * Check CSS/JSON/JS subpage permissions
1414 *
1415 * @param string $action The action to check
1416 * @param UserIdentity $user User to check
1417 * @param PermissionStatus $status Current errors
1418 * @param string $rigor One of PermissionManager::RIGOR_ constants
1419 * - RIGOR_QUICK : does cheap permission checks from replica DBs (usable for GUI creation)
1420 * - RIGOR_FULL : does cheap and expensive checks possibly from a replica DB
1421 * - RIGOR_SECURE : does cheap and expensive checks, using the primary DB as needed
1422 * @param bool $short Short circuit on first error
1423 * @param LinkTarget $page
1424 */
1425 private function checkUserConfigPermissions(
1426 $action,
1427 UserIdentity $user,
1428 PermissionStatus $status,
1429 $rigor,
1430 $short,
1431 LinkTarget $page
1432 ): void {
1433 // TODO: remove & rework upon further use of LinkTarget
1434 $title = Title::newFromLinkTarget( $page );
1435
1436 // Protect css/json/js subpages of user pages
1437 // XXX: this might be better using restrictions
1438 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $title->getText() ) ) {
1439 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
1440 if (
1441 $title->isUserCssConfigPage()
1442 && !$this->userHasAnyRight( $user, 'editmyusercss', 'editusercss' )
1443 ) {
1444 $status->fatal( 'mycustomcssprotected', $action );
1445 } elseif (
1446 $title->isUserJsonConfigPage()
1447 && !$this->userHasAnyRight( $user, 'editmyuserjson', 'edituserjson' )
1448 ) {
1449 $status->fatal( 'mycustomjsonprotected', $action );
1450 } elseif (
1451 $title->isUserJsConfigPage()
1452 && !$this->userHasAnyRight( $user, 'editmyuserjs', 'edituserjs' )
1453 ) {
1454 $status->fatal( 'mycustomjsprotected', $action );
1455 } elseif (
1456 $title->isUserJsConfigPage()
1457 && !$this->userHasAnyRight( $user, 'edituserjs', 'editmyuserjsredirect' )
1458 ) {
1459 // T207750 - do not allow users to edit a redirect if they couldn't edit the target
1460 $target = $this->redirectLookup->getRedirectTarget( $title );
1461 if ( $target && (
1462 !$target->inNamespace( NS_USER )
1463 || !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $target->getText() )
1464 ) ) {
1465 $status->fatal( 'mycustomjsredirectprotected', $action );
1466 }
1467 }
1468 } else {
1469 // Users need edituser* to edit others' CSS/JSON/JS subpages.
1470 // The checks to exclude deletion/suppression, which cannot be used for
1471 // attacks and should be excluded to avoid the situation where an
1472 // unprivileged user can post abusive content on their subpages
1473 // and only very highly privileged users could remove it,
1474 // are now a part of `getPermissionStatus` and this method isn't called.
1475 if (
1476 $title->isUserCssConfigPage()
1477 && !$this->userHasRight( $user, 'editusercss' )
1478 ) {
1479 $status->fatal( 'customcssprotected', $action );
1480 } elseif (
1481 $title->isUserJsonConfigPage()
1482 && !$this->userHasRight( $user, 'edituserjson' )
1483 ) {
1484 $status->fatal( 'customjsonprotected', $action );
1485 } elseif (
1486 $title->isUserJsConfigPage()
1487 && !$this->userHasRight( $user, 'edituserjs' )
1488 ) {
1489 $status->fatal( 'customjsprotected', $action );
1490 }
1491 }
1492 }
1493
1494 /**
1495 * Whether the user is generally allowed to perform the given action.
1496 *
1497 * @since 1.34
1498 * @param UserIdentity $user
1499 * @param string $action
1500 * @return bool True if allowed
1501 */
1502 public function userHasRight( UserIdentity $user, $action = '' ): bool {
1503 if ( $action === '' ) {
1504 // In the spirit of DWIM
1505 return true;
1506 }
1507 // Use strict parameter to avoid matching numeric 0 accidentally inserted
1508 // by misconfiguration: 0 == 'foo'
1509 return in_array( $action, $this->getImplicitRights(), true )
1510 || in_array( $action, $this->getUserPermissions( $user ), true );
1511 }
1512
1513 /**
1514 * Whether the user is generally allowed to perform at least one of the actions.
1515 *
1516 * @since 1.34
1517 * @param UserIdentity $user
1518 * @param string ...$actions
1519 * @return bool True if user is allowed to perform *any* of the actions
1520 */
1521 public function userHasAnyRight( UserIdentity $user, ...$actions ): bool {
1522 foreach ( $actions as $action ) {
1523 if ( $this->userHasRight( $user, $action ) ) {
1524 return true;
1525 }
1526 }
1527 return false;
1528 }
1529
1530 /**
1531 * Whether the user is allowed to perform all of the given actions.
1532 *
1533 * @since 1.34
1534 * @param UserIdentity $user
1535 * @param string ...$actions
1536 * @return bool True if user is allowed to perform *all* of the given actions
1537 */
1538 public function userHasAllRights( UserIdentity $user, ...$actions ): bool {
1539 foreach ( $actions as $action ) {
1540 if ( !$this->userHasRight( $user, $action ) ) {
1541 return false;
1542 }
1543 }
1544 return true;
1545 }
1546
1547 /**
1548 * Get the permissions this user has.
1549 *
1550 * @since 1.34
1551 * @param UserIdentity $user
1552 * @return string[] permission names
1553 */
1554 public function getUserPermissions( UserIdentity $user ): array {
1555 $rightsCacheKey = $this->getRightsCacheKey( $user );
1556 if ( !isset( $this->usersRights[ $rightsCacheKey ] ) ) {
1557 $userObj = $this->userFactory->newFromUserIdentity( $user );
1558 $rights = $this->groupPermissionsLookup->getGroupPermissions(
1559 $this->userGroupManager->getUserEffectiveGroups( $user )
1560 );
1561 // Hook requires a full User object
1562 $this->hookRunner->onUserGetRights( $userObj, $rights );
1563
1564 // Deny any rights denied by the user's session, unless this
1565 // endpoint has no sessions.
1566 if ( !defined( 'MW_NO_SESSION' ) ) {
1567 // FIXME: $userObj->getRequest().. need to be replaced with something else
1568 $allowedRights = $userObj->getRequest()->getSession()->getAllowedUserRights();
1569 if ( $allowedRights !== null ) {
1570 $rights = array_intersect( $rights, $allowedRights );
1571 }
1572 }
1573
1574 // Hook requires a full User object
1575 $this->hookRunner->onUserGetRightsRemove( $userObj, $rights );
1576 // Force reindexation of rights when a hook has unset one of them
1577 $rights = array_values( array_unique( $rights ) );
1578
1579 // If BlockDisablesLogin is true, remove rights that anonymous
1580 // users don't have. This has to be done after the hooks so that
1581 // we know whether the user is exempt. (T129738)
1582 if (
1583 $userObj->isRegistered()
1584 && $this->options->get( MainConfigNames::BlockDisablesLogin )
1585 ) {
1586 // Stash the permissions as they are before triggering any block checks for BlockDisablesLogin
1587 // to avoid a potential infinite loop, since GetUserBlock handlers may themselves check
1588 // permissions on this user. (T384197)
1589 $this->usersRights[ $rightsCacheKey ] = $rights;
1590
1591 $isExempt = in_array( 'ipblock-exempt', $rights, true );
1592 if ( $this->blockManager->getBlock(
1593 $userObj,
1594 $isExempt ? null : $userObj->getRequest()
1595 ) ) {
1596 $anon = $this->userFactory->newAnonymous();
1597 $rights = array_intersect( $rights, $this->getUserPermissions( $anon ) );
1598 }
1599 }
1600
1601 $this->usersRights[ $rightsCacheKey ] = $rights;
1602 } else {
1603 $rights = $this->usersRights[ $rightsCacheKey ];
1604 }
1605 foreach ( $this->temporaryUserRights[ $user->getId() ] ?? [] as $overrides ) {
1606 $rights = array_values( array_unique( array_merge( $rights, $overrides ) ) );
1607 }
1608 return $rights;
1609 }
1610
1611 /**
1612 * Clear the in-process permission cache for one or all users.
1613 *
1614 * @since 1.34
1615 * @param UserIdentity|null $user If a specific user is provided it will clear
1616 * the permission cache only for that user.
1617 */
1618 public function invalidateUsersRightsCache( $user = null ): void {
1619 if ( $user !== null ) {
1620 $rightsCacheKey = $this->getRightsCacheKey( $user );
1621 unset( $this->usersRights[ $rightsCacheKey ] );
1622 } else {
1623 $this->usersRights = [];
1624 }
1625 }
1626
1627 /**
1628 * Get a unique key for user rights cache.
1629 *
1630 * @param UserIdentity $user
1631 * @return string
1632 */
1633 private function getRightsCacheKey( UserIdentity $user ): string {
1634 return $user->isRegistered() ? "u:{$user->getId()}" : "anon:{$user->getName()}";
1635 }
1636
1637 /**
1638 * Check if all users may be assumed to have the given permission
1639 *
1640 * We generally assume so if the right is granted to '*' and isn't revoked
1641 * on any group. It doesn't attempt to take grants or other extension
1642 * limitations on rights into account in the general case, though, as that
1643 * would require it to always return false and defeat the purpose.
1644 * Specifically, session-based rights restrictions (such as OAuth or bot
1645 * passwords) are applied based on the current session.
1646 *
1647 * @since 1.34
1648 * @param string $right Right to check
1649 * @return bool
1650 */
1651 public function isEveryoneAllowed( $right ): bool {
1652 // Use the cached results, except in unit tests which rely on
1653 // being able change the permission mid-request
1654 if ( isset( $this->cachedRights[$right] ) ) {
1655 return $this->cachedRights[$right];
1656 }
1657
1658 if ( !isset( $this->options->get( MainConfigNames::GroupPermissions )['*'][$right] )
1659 || !$this->options->get( MainConfigNames::GroupPermissions )['*'][$right]
1660 ) {
1661 $this->cachedRights[$right] = false;
1662 return false;
1663 }
1664
1665 // If it's revoked anywhere, then everyone doesn't have it
1666 foreach ( $this->options->get( MainConfigNames::RevokePermissions ) as $rights ) {
1667 if ( isset( $rights[$right] ) && $rights[$right] ) {
1668 $this->cachedRights[$right] = false;
1669 return false;
1670 }
1671 }
1672
1673 // Remove any rights that aren't allowed to the global-session user,
1674 // unless there are no sessions for this endpoint.
1675 if ( !defined( 'MW_NO_SESSION' ) ) {
1676 // XXX: think what could be done with the below
1677 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
1678 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
1679 $this->cachedRights[$right] = false;
1680 return false;
1681 }
1682 }
1683
1684 // Allow extensions to say false
1685 if ( !$this->hookRunner->onUserIsEveryoneAllowed( $right ) ) {
1686 $this->cachedRights[$right] = false;
1687 return false;
1688 }
1689
1690 $this->cachedRights[$right] = true;
1691 return true;
1692 }
1693
1694 /**
1695 * Get a list of all permissions that can be managed through group permissions.
1696 * This does not include implicit rights which are granted to all users automatically.
1697 *
1698 * @see getImplicitRights()
1699 *
1700 * @since 1.34
1701 * @return string[] Array of permission names
1702 */
1703 public function getAllPermissions(): array {
1704 if ( $this->allRights === null ) {
1705 if ( count( $this->options->get( MainConfigNames::AvailableRights ) ) ) {
1706 $this->allRights = array_unique( array_merge(
1707 self::CORE_RIGHTS,
1708 $this->options->get( MainConfigNames::AvailableRights )
1709 ) );
1710 } else {
1711 $this->allRights = self::CORE_RIGHTS;
1712 }
1713 $this->hookRunner->onUserGetAllRights( $this->allRights );
1714 }
1715 return $this->allRights;
1716 }
1717
1718 /**
1719 * Get a list of implicit rights.
1720 *
1721 * Rights in this list should be granted to all users implicitly.
1722 *
1723 * Implicit rights are defined to allow rate limits to be imposed
1724 * on permissions
1725 *
1726 * @since 1.41
1727 * @return string[] Array of permission names
1728 */
1729 public function getImplicitRights(): array {
1730 if ( $this->implicitRights === null ) {
1731 $rights = array_unique( array_merge(
1732 self::CORE_IMPLICIT_RIGHTS,
1733 $this->options->get( MainConfigNames::ImplicitRights )
1734 ) );
1735
1736 $this->implicitRights = array_diff( $rights, $this->getAllPermissions() );
1737 }
1738 return $this->implicitRights;
1739 }
1740
1741 /**
1742 * Determine if $user is unable to edit pages in namespace because it has been protected.
1743 *
1744 * @param int $index
1745 * @param UserIdentity $user
1746 * @return bool
1747 */
1748 private function isNamespaceProtected( $index, UserIdentity $user ): bool {
1749 $namespaceProtection = $this->options->get( MainConfigNames::NamespaceProtection );
1750 if ( isset( $namespaceProtection[$index] ) ) {
1751 return !$this->userHasAllRights( $user, ...(array)$namespaceProtection[$index] );
1752 }
1753 return false;
1754 }
1755
1756 /**
1757 * Determine which restriction levels it makes sense to use in a namespace,
1758 * optionally filtered by a user's rights.
1759 *
1760 * @param int $index Namespace ID (index) to check
1761 * @param UserIdentity|null $user User to check
1762 * @return string[]
1763 */
1764 public function getNamespaceRestrictionLevels( $index, ?UserIdentity $user = null ): array {
1765 if ( !isset( $this->options->get( MainConfigNames::NamespaceProtection )[$index] ) ) {
1766 // All levels are valid if there's no namespace restriction.
1767 // But still filter by user, if necessary
1768 $levels = $this->options->get( MainConfigNames::RestrictionLevels );
1769 if ( $user ) {
1770 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
1771 $right = $level;
1772 if ( $right === 'sysop' ) {
1773 $right = 'editprotected'; // BC
1774 }
1775 if ( $right === 'autoconfirmed' ) {
1776 $right = 'editsemiprotected'; // BC
1777 }
1778 return $this->userHasRight( $user, $right );
1779 } ) );
1780 }
1781 return $levels;
1782 }
1783
1784 // $wgNamespaceProtection can require one or more rights to edit the namespace, which
1785 // may be satisfied by membership in multiple groups each giving a subset of those rights.
1786 // A restriction level is redundant if, for any one of the namespace rights, all groups
1787 // giving that right also give the restriction level's right. Or, conversely, a
1788 // restriction level is not redundant if, for every namespace right, there's at least one
1789 // group giving that right without the restriction level's right.
1790 //
1791 // First, for each right, get a list of groups with that right.
1792 $namespaceRightGroups = [];
1793 foreach ( (array)$this->options->get( MainConfigNames::NamespaceProtection )[$index] as $right ) {
1794 if ( $right === 'sysop' ) {
1795 $right = 'editprotected'; // BC
1796 }
1797 if ( $right === 'autoconfirmed' ) {
1798 $right = 'editsemiprotected'; // BC
1799 }
1800 if ( $right != '' ) {
1801 $namespaceRightGroups[$right] = $this->groupPermissionsLookup->getGroupsWithPermission( $right );
1802 }
1803 }
1804
1805 // Now, go through the protection levels one by one.
1806 $usableLevels = [ '' ];
1807 foreach ( $this->options->get( MainConfigNames::RestrictionLevels ) as $level ) {
1808 $right = $level;
1809 if ( $right === 'sysop' ) {
1810 $right = 'editprotected'; // BC
1811 }
1812 if ( $right === 'autoconfirmed' ) {
1813 $right = 'editsemiprotected'; // BC
1814 }
1815
1816 if ( $right != '' &&
1817 !isset( $namespaceRightGroups[$right] ) &&
1818 ( !$user || $this->userHasRight( $user, $right ) )
1819 ) {
1820 // Do any of the namespace rights imply the restriction right? (see explanation above)
1821 foreach ( $namespaceRightGroups as $groups ) {
1822 if ( !array_diff( $groups, $this->groupPermissionsLookup->getGroupsWithPermission( $right ) ) ) {
1823 // Yes, this one does.
1824 continue 2;
1825 }
1826 }
1827 // No, keep the restriction level
1828 $usableLevels[] = $level;
1829 }
1830 }
1831
1832 return $usableLevels;
1833 }
1834
1835 /**
1836 * Check if user is allowed to edit sitewide pages that contain raw HTML.
1837 *
1838 * Pages listed in $wgRawHtmlMessages allow raw HTML which can be used to deploy CSS or JS
1839 * code to all users so both rights are required to edit them.
1840 *
1841 * @param UserIdentity $user
1842 * @return bool True if user has both rights
1843 */
1844 private function userCanEditRawHtmlPage( UserIdentity $user ): bool {
1845 return $this->userHasAllRights( $user, 'editsitecss', 'editsitejs' );
1846 }
1847
1848 /**
1849 * Add temporary user rights, only valid for the current function scope.
1850 *
1851 * This is meant for making it possible to programatically trigger certain actions that
1852 * the user wouldn't be able to trigger themselves; e.g. allow users without the bot right
1853 * to make bot-flagged actions through certain special pages.
1854 *
1855 * This returns a "scope guard" variable. Its only purpose is to be stored in a variable
1856 * by the caller, which is automatically closed at the end of the function, at which point
1857 * the rights are revoked again. Alternatively, you can close it earlier by consuming it
1858 * via ScopedCallback::consume().
1859 *
1860 * @since 1.34
1861 * @param UserIdentity $user
1862 * @param string|string[] $rights
1863 * @return ScopedCallback
1864 */
1865 public function addTemporaryUserRights( UserIdentity $user, $rights ) {
1866 $userId = $user->getId();
1867 $nextKey = count( $this->temporaryUserRights[$userId] ?? [] );
1868 $this->temporaryUserRights[$userId][$nextKey] = (array)$rights;
1869 return new ScopedCallback( function () use ( $userId, $nextKey ) {
1870 unset( $this->temporaryUserRights[$userId][$nextKey] );
1871 } );
1872 }
1873
1874 /**
1875 * Override the user permissions cache
1876 *
1877 * @internal For testing only
1878 * @since 1.34
1879 * @param UserIdentity $user
1880 * @param string[]|string $rights
1881 */
1882 public function overrideUserRightsForTesting( $user, $rights = [] ) {
1883 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1884 throw new LogicException( __METHOD__ . ' can not be called outside of tests' );
1885 }
1886 $this->usersRights[ $this->getRightsCacheKey( $user ) ] =
1887 is_array( $rights ) ? $rights : [ $rights ];
1888 }
1889
1890 }