MediaWiki  1.33.0
PermissionManager.php
Go to the documentation of this file.
1 <?php
21 
22 use Action;
23 use Exception;
25 use Hooks;
33 use Title;
34 use User;
36 
44 
46  const RIGOR_QUICK = 'quick';
47 
49  const RIGOR_FULL = 'full';
50 
52  const RIGOR_SECURE = 'secure';
53 
55  private $specialPageFactory;
56 
58  private $whitelistRead;
59 
62 
65 
68 
76  public function __construct(
82  ) {
83  $this->specialPageFactory = $specialPageFactory;
84  $this->whitelistRead = $whitelistRead;
85  $this->whitelistReadRegexp = $whitelistReadRegexp;
86  $this->emailConfirmToEdit = $emailConfirmToEdit;
87  $this->blockDisablesLogin = $blockDisablesLogin;
88  }
89 
110  public function userCan( $action, User $user, LinkTarget $page, $rigor = self::RIGOR_SECURE ) {
111  return !count( $this->getPermissionErrorsInternal( $action, $user, $page, $rigor, true ) );
112  }
113 
132  public function getPermissionErrors(
133  $action,
134  User $user,
135  LinkTarget $page,
136  $rigor = self::RIGOR_SECURE,
137  $ignoreErrors = []
138  ) {
139  $errors = $this->getPermissionErrorsInternal( $action, $user, $page, $rigor );
140 
141  // Remove the errors being ignored.
142  foreach ( $errors as $index => $error ) {
143  $errKey = is_array( $error ) ? $error[0] : $error;
144 
145  if ( in_array( $errKey, $ignoreErrors ) ) {
146  unset( $errors[$index] );
147  }
148  if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
149  unset( $errors[$index] );
150  }
151  }
152 
153  return $errors;
154  }
155 
167  public function isBlockedFrom( User $user, LinkTarget $page, $fromReplica = false ) {
168  $blocked = $user->isHidden();
169 
170  // TODO: remove upon further migration to LinkTarget
171  $page = Title::newFromLinkTarget( $page );
172 
173  if ( !$blocked ) {
174  $block = $user->getBlock( $fromReplica );
175  if ( $block ) {
176  // Special handling for a user's own talk page. The block is not aware
177  // of the user, so this must be done here.
178  if ( $page->equals( $user->getTalkPage() ) ) {
179  $blocked = $block->appliesToUsertalk( $page );
180  } else {
181  $blocked = $block->appliesToTitle( $page );
182  }
183  }
184  }
185 
186  // only for the purpose of the hook. We really don't need this here.
187  $allowUsertalk = $user->isAllowUsertalk();
188 
189  Hooks::run( 'UserIsBlockedFrom', [ $user, $page, &$blocked, &$allowUsertalk ] );
190 
191  return $blocked;
192  }
193 
211  private function getPermissionErrorsInternal(
212  $action,
213  User $user,
214  LinkTarget $page,
215  $rigor = self::RIGOR_SECURE,
216  $short = false
217  ) {
218  if ( !in_array( $rigor, [ self::RIGOR_QUICK, self::RIGOR_FULL, self::RIGOR_SECURE ] ) ) {
219  throw new Exception( "Invalid rigor parameter '$rigor'." );
220  }
221 
222  # Read has special handling
223  if ( $action == 'read' ) {
224  $checks = [
225  'checkPermissionHooks',
226  'checkReadPermissions',
227  'checkUserBlock', // for wgBlockDisablesLogin
228  ];
229  # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
230  # or checkUserConfigPermissions here as it will lead to duplicate
231  # error messages. This is okay to do since anywhere that checks for
232  # create will also check for edit, and those checks are called for edit.
233  } elseif ( $action == 'create' ) {
234  $checks = [
235  'checkQuickPermissions',
236  'checkPermissionHooks',
237  'checkPageRestrictions',
238  'checkCascadingSourcesRestrictions',
239  'checkActionPermissions',
240  'checkUserBlock'
241  ];
242  } else {
243  $checks = [
244  'checkQuickPermissions',
245  'checkPermissionHooks',
246  'checkSpecialsAndNSPermissions',
247  'checkSiteConfigPermissions',
248  'checkUserConfigPermissions',
249  'checkPageRestrictions',
250  'checkCascadingSourcesRestrictions',
251  'checkActionPermissions',
252  'checkUserBlock'
253  ];
254  }
255 
256  $errors = [];
257  foreach ( $checks as $method ) {
258  $errors = $this->$method( $action, $user, $errors, $rigor, $short, $page );
259 
260  if ( $short && $errors !== [] ) {
261  break;
262  }
263  }
264 
265  return $errors;
266  }
267 
286  private function checkPermissionHooks(
287  $action,
288  User $user,
289  $errors,
290  $rigor,
291  $short,
292  LinkTarget $page
293  ) {
294  // TODO: remove when LinkTarget usage will expand further
295  $page = Title::newFromLinkTarget( $page );
296  // Use getUserPermissionsErrors instead
297  $result = '';
298  if ( !Hooks::run( 'userCan', [ &$page, &$user, $action, &$result ] ) ) {
299  return $result ? [] : [ [ 'badaccess-group0' ] ];
300  }
301  // Check getUserPermissionsErrors hook
302  if ( !Hooks::run( 'getUserPermissionsErrors', [ &$page, &$user, $action, &$result ] ) ) {
303  $errors = $this->resultToError( $errors, $result );
304  }
305  // Check getUserPermissionsErrorsExpensive hook
306  if (
307  $rigor !== self::RIGOR_QUICK
308  && !( $short && count( $errors ) > 0 )
309  && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$page, &$user, $action, &$result ] )
310  ) {
311  $errors = $this->resultToError( $errors, $result );
312  }
313 
314  return $errors;
315  }
316 
325  private function resultToError( $errors, $result ) {
326  if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
327  // A single array representing an error
328  $errors[] = $result;
329  } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
330  // A nested array representing multiple errors
331  $errors = array_merge( $errors, $result );
332  } elseif ( $result !== '' && is_string( $result ) ) {
333  // A string representing a message-id
334  $errors[] = [ $result ];
335  } elseif ( $result instanceof MessageSpecifier ) {
336  // A message specifier representing an error
337  $errors[] = [ $result ];
338  } elseif ( $result === false ) {
339  // a generic "We don't want them to do that"
340  $errors[] = [ 'badaccess-group0' ];
341  }
342  return $errors;
343  }
344 
363  private function checkReadPermissions(
364  $action,
365  User $user,
366  $errors,
367  $rigor,
368  $short,
369  LinkTarget $page
370  ) {
371  // TODO: remove when LinkTarget usage will expand further
372  $page = Title::newFromLinkTarget( $page );
373 
374  $whitelisted = false;
375  if ( User::isEveryoneAllowed( 'read' ) ) {
376  # Shortcut for public wikis, allows skipping quite a bit of code
377  $whitelisted = true;
378  } elseif ( $user->isAllowed( 'read' ) ) {
379  # If the user is allowed to read pages, he is allowed to read all pages
380  $whitelisted = true;
381  } elseif ( $this->isSameSpecialPage( 'Userlogin', $page )
382  || $this->isSameSpecialPage( 'PasswordReset', $page )
383  || $this->isSameSpecialPage( 'Userlogout', $page )
384  ) {
385  # Always grant access to the login page.
386  # Even anons need to be able to log in.
387  $whitelisted = true;
388  } elseif ( is_array( $this->whitelistRead ) && count( $this->whitelistRead ) ) {
389  # Time to check the whitelist
390  # Only do these checks is there's something to check against
391  $name = $page->getPrefixedText();
392  $dbName = $page->getPrefixedDBkey();
393 
394  // Check for explicit whitelisting with and without underscores
395  if ( in_array( $name, $this->whitelistRead, true )
396  || in_array( $dbName, $this->whitelistRead, true ) ) {
397  $whitelisted = true;
398  } elseif ( $page->getNamespace() == NS_MAIN ) {
399  # Old settings might have the title prefixed with
400  # a colon for main-namespace pages
401  if ( in_array( ':' . $name, $this->whitelistRead ) ) {
402  $whitelisted = true;
403  }
404  } elseif ( $page->isSpecialPage() ) {
405  # If it's a special page, ditch the subpage bit and check again
406  $name = $page->getDBkey();
407  list( $name, /* $subpage */ ) =
408  $this->specialPageFactory->resolveAlias( $name );
409  if ( $name ) {
410  $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
411  if ( in_array( $pure, $this->whitelistRead, true ) ) {
412  $whitelisted = true;
413  }
414  }
415  }
416  }
417 
418  if ( !$whitelisted && is_array( $this->whitelistReadRegexp )
419  && !empty( $this->whitelistReadRegexp ) ) {
420  $name = $page->getPrefixedText();
421  // Check for regex whitelisting
422  foreach ( $this->whitelistReadRegexp as $listItem ) {
423  if ( preg_match( $listItem, $name ) ) {
424  $whitelisted = true;
425  break;
426  }
427  }
428  }
429 
430  if ( !$whitelisted ) {
431  # If the title is not whitelisted, give extensions a chance to do so...
432  Hooks::run( 'TitleReadWhitelist', [ $page, $user, &$whitelisted ] );
433  if ( !$whitelisted ) {
434  $errors[] = $this->missingPermissionError( $action, $short );
435  }
436  }
437 
438  return $errors;
439  }
440 
449  private function missingPermissionError( $action, $short ) {
450  // We avoid expensive display logic for quickUserCan's and such
451  if ( $short ) {
452  return [ 'badaccess-group0' ];
453  }
454 
455  // TODO: it would be a good idea to replace the method below with something else like
456  // maybe callback injection
457  return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
458  }
459 
468  private function isSameSpecialPage( $name, LinkTarget $page ) {
469  if ( $page->getNamespace() == NS_SPECIAL ) {
470  list( $thisName, /* $subpage */ ) =
471  $this->specialPageFactory->resolveAlias( $page->getDBkey() );
472  if ( $name == $thisName ) {
473  return true;
474  }
475  }
476  return false;
477  }
478 
496  private function checkUserBlock(
497  $action,
498  User $user,
499  $errors,
500  $rigor,
501  $short,
502  LinkTarget $page
503  ) {
504  // Account creation blocks handled at userlogin.
505  // Unblocking handled in SpecialUnblock
506  if ( $rigor === self::RIGOR_QUICK || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
507  return $errors;
508  }
509 
510  // Optimize for a very common case
511  if ( $action === 'read' && !$this->blockDisablesLogin ) {
512  return $errors;
513  }
514 
515  if ( $this->emailConfirmToEdit
516  && !$user->isEmailConfirmed()
517  && $action === 'edit'
518  ) {
519  $errors[] = [ 'confirmedittext' ];
520  }
521 
522  $useReplica = ( $rigor !== self::RIGOR_SECURE );
523  $block = $user->getBlock( $useReplica );
524 
525  // If the user does not have a block, or the block they do have explicitly
526  // allows the action (like "read" or "upload").
527  if ( !$block || $block->appliesToRight( $action ) === false ) {
528  return $errors;
529  }
530 
531  // Determine if the user is blocked from this action on this page.
532  // What gets passed into this method is a user right, not an action name.
533  // There is no way to instantiate an action by restriction. However, this
534  // will get the action where the restriction is the same. This may result
535  // in actions being blocked that shouldn't be.
536  $actionObj = null;
537  if ( Action::exists( $action ) ) {
538  // TODO: this drags a ton of dependencies in, would be good to avoid WikiPage
539  // instantiation and decouple it creating an ActionPermissionChecker interface
540  $wikiPage = WikiPage::factory( Title::newFromLinkTarget( $page, 'clone' ) );
541  // Creating an action will perform several database queries to ensure that
542  // the action has not been overridden by the content type.
543  // FIXME: avoid use of RequestContext since it drags in User and Title dependencies
544  // probably we may use fake context object since it's unlikely that Action uses it
545  // anyway. It would be nice if we could avoid instantiating the Action at all.
546  $actionObj = Action::factory( $action, $wikiPage, RequestContext::getMain() );
547  // Ensure that the retrieved action matches the restriction.
548  if ( $actionObj && $actionObj->getRestriction() !== $action ) {
549  $actionObj = null;
550  }
551  }
552 
553  // If no action object is returned, assume that the action requires unblock
554  // which is the default.
555  if ( !$actionObj || $actionObj->requiresUnblock() ) {
556  if ( $this->isBlockedFrom( $user, $page, $useReplica ) ) {
557  // @todo FIXME: Pass the relevant context into this function.
558  $errors[] = $block->getPermissionsError( RequestContext::getMain() );
559  }
560  }
561 
562  return $errors;
563  }
564 
583  private function checkQuickPermissions(
584  $action,
585  User $user,
586  $errors,
587  $rigor,
588  $short,
589  LinkTarget $page
590  ) {
591  // TODO: remove when LinkTarget usage will expand further
592  $page = Title::newFromLinkTarget( $page );
593 
594  if ( !Hooks::run( 'TitleQuickPermissions',
595  [ $page, $user, $action, &$errors, ( $rigor !== self::RIGOR_QUICK ), $short ] )
596  ) {
597  return $errors;
598  }
599 
600  $isSubPage = MWNamespace::hasSubpages( $page->getNamespace() ) ?
601  strpos( $page->getText(), '/' ) !== false : false;
602 
603  if ( $action == 'create' ) {
604  if (
605  ( MWNamespace::isTalk( $page->getNamespace() ) && !$user->isAllowed( 'createtalk' ) ) ||
606  ( !MWNamespace::isTalk( $page->getNamespace() ) && !$user->isAllowed( 'createpage' ) )
607  ) {
608  $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
609  }
610  } elseif ( $action == 'move' ) {
611  if ( !$user->isAllowed( 'move-rootuserpages' )
612  && $page->getNamespace() == NS_USER && !$isSubPage ) {
613  // Show user page-specific message only if the user can move other pages
614  $errors[] = [ 'cant-move-user-page' ];
615  }
616 
617  // Check if user is allowed to move files if it's a file
618  if ( $page->getNamespace() == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
619  $errors[] = [ 'movenotallowedfile' ];
620  }
621 
622  // Check if user is allowed to move category pages if it's a category page
623  if ( $page->getNamespace() == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
624  $errors[] = [ 'cant-move-category-page' ];
625  }
626 
627  if ( !$user->isAllowed( 'move' ) ) {
628  // User can't move anything
629  $userCanMove = User::groupHasPermission( 'user', 'move' );
630  $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
631  if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
632  // custom message if logged-in users without any special rights can move
633  $errors[] = [ 'movenologintext' ];
634  } else {
635  $errors[] = [ 'movenotallowed' ];
636  }
637  }
638  } elseif ( $action == 'move-target' ) {
639  if ( !$user->isAllowed( 'move' ) ) {
640  // User can't move anything
641  $errors[] = [ 'movenotallowed' ];
642  } elseif ( !$user->isAllowed( 'move-rootuserpages' )
643  && $page->getNamespace() == NS_USER && !$isSubPage ) {
644  // Show user page-specific message only if the user can move other pages
645  $errors[] = [ 'cant-move-to-user-page' ];
646  } elseif ( !$user->isAllowed( 'move-categorypages' )
647  && $page->getNamespace() == NS_CATEGORY ) {
648  // Show category page-specific message only if the user can move other pages
649  $errors[] = [ 'cant-move-to-category-page' ];
650  }
651  } elseif ( !$user->isAllowed( $action ) ) {
652  $errors[] = $this->missingPermissionError( $action, $short );
653  }
654 
655  return $errors;
656  }
657 
676  private function checkPageRestrictions(
677  $action,
678  User $user,
679  $errors,
680  $rigor,
681  $short,
682  LinkTarget $page
683  ) {
684  // TODO: remove & rework upon further use of LinkTarget
685  $page = Title::newFromLinkTarget( $page );
686  foreach ( $page->getRestrictions( $action ) as $right ) {
687  // Backwards compatibility, rewrite sysop -> editprotected
688  if ( $right == 'sysop' ) {
689  $right = 'editprotected';
690  }
691  // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
692  if ( $right == 'autoconfirmed' ) {
693  $right = 'editsemiprotected';
694  }
695  if ( $right == '' ) {
696  continue;
697  }
698  if ( !$user->isAllowed( $right ) ) {
699  $errors[] = [ 'protectedpagetext', $right, $action ];
700  } elseif ( $page->areRestrictionsCascading() && !$user->isAllowed( 'protect' ) ) {
701  $errors[] = [ 'protectedpagetext', 'protect', $action ];
702  }
703  }
704 
705  return $errors;
706  }
707 
725  $action,
726  User $user,
727  $errors,
728  $rigor,
729  $short,
730  LinkTarget $page
731  ) {
732  // TODO: remove & rework upon further use of LinkTarget
733  $page = Title::newFromLinkTarget( $page );
734  if ( $rigor !== self::RIGOR_QUICK && !$page->isUserConfigPage() ) {
735  # We /could/ use the protection level on the source page, but it's
736  # fairly ugly as we have to establish a precedence hierarchy for pages
737  # included by multiple cascade-protected pages. So just restrict
738  # it to people with 'protect' permission, as they could remove the
739  # protection anyway.
740  list( $cascadingSources, $restrictions ) = $page->getCascadeProtectionSources();
741  # Cascading protection depends on more than this page...
742  # Several cascading protected pages may include this page...
743  # Check each cascading level
744  # This is only for protection restrictions, not for all actions
745  if ( isset( $restrictions[$action] ) ) {
746  foreach ( $restrictions[$action] as $right ) {
747  // Backwards compatibility, rewrite sysop -> editprotected
748  if ( $right == 'sysop' ) {
749  $right = 'editprotected';
750  }
751  // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
752  if ( $right == 'autoconfirmed' ) {
753  $right = 'editsemiprotected';
754  }
755  if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
756  $wikiPages = '';
757  foreach ( $cascadingSources as $wikiPage ) {
758  $wikiPages .= '* [[:' . $wikiPage->getPrefixedText() . "]]\n";
759  }
760  $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $wikiPages, $action ];
761  }
762  }
763  }
764  }
765 
766  return $errors;
767  }
768 
786  private function checkActionPermissions(
787  $action,
788  User $user,
789  $errors,
790  $rigor,
791  $short,
792  LinkTarget $page
793  ) {
795 
796  // TODO: remove & rework upon further use of LinkTarget
797  $page = Title::newFromLinkTarget( $page );
798 
799  if ( $action == 'protect' ) {
800  if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $page, $rigor, true ) ) ) {
801  // If they can't edit, they shouldn't protect.
802  $errors[] = [ 'protect-cantedit' ];
803  }
804  } elseif ( $action == 'create' ) {
805  $title_protection = $page->getTitleProtection();
806  if ( $title_protection ) {
807  if ( $title_protection['permission'] == ''
808  || !$user->isAllowed( $title_protection['permission'] )
809  ) {
810  $errors[] = [
811  'titleprotected',
812  // TODO: get rid of the User dependency
813  User::whoIs( $title_protection['user'] ),
814  $title_protection['reason']
815  ];
816  }
817  }
818  } elseif ( $action == 'move' ) {
819  // Check for immobile pages
820  if ( !MWNamespace::isMovable( $page->getNamespace() ) ) {
821  // Specific message for this case
822  $errors[] = [ 'immobile-source-namespace', $page->getNsText() ];
823  } elseif ( !$page->isMovable() ) {
824  // Less specific message for rarer cases
825  $errors[] = [ 'immobile-source-page' ];
826  }
827  } elseif ( $action == 'move-target' ) {
828  if ( !MWNamespace::isMovable( $page->getNamespace() ) ) {
829  $errors[] = [ 'immobile-target-namespace', $page->getNsText() ];
830  } elseif ( !$page->isMovable() ) {
831  $errors[] = [ 'immobile-target-page' ];
832  }
833  } elseif ( $action == 'delete' ) {
834  $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true, $page );
835  if ( !$tempErrors ) {
836  $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
837  $user, $tempErrors, $rigor, true, $page );
838  }
839  if ( $tempErrors ) {
840  // If protection keeps them from editing, they shouldn't be able to delete.
841  $errors[] = [ 'deleteprotected' ];
842  }
843  if ( $rigor !== self::RIGOR_QUICK && $wgDeleteRevisionsLimit
844  && !$this->userCan( 'bigdelete', $user, $page ) && $page->isBigDeletion()
845  ) {
846  $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
847  }
848  } elseif ( $action === 'undelete' ) {
849  if ( count( $this->getPermissionErrorsInternal( 'edit', $user, $page, $rigor, true ) ) ) {
850  // Undeleting implies editing
851  $errors[] = [ 'undelete-cantedit' ];
852  }
853  if ( !$page->exists()
854  && count( $this->getPermissionErrorsInternal( 'create', $user, $page, $rigor, true ) )
855  ) {
856  // Undeleting where nothing currently exists implies creating
857  $errors[] = [ 'undelete-cantcreate' ];
858  }
859  }
860  return $errors;
861  }
862 
880  $action,
881  User $user,
882  $errors,
883  $rigor,
884  $short,
885  LinkTarget $page
886  ) {
887  // TODO: remove & rework upon further use of LinkTarget
888  $page = Title::newFromLinkTarget( $page );
889 
890  # Only 'createaccount' can be performed on special pages,
891  # which don't actually exist in the DB.
892  if ( $page->getNamespace() == NS_SPECIAL && $action !== 'createaccount' ) {
893  $errors[] = [ 'ns-specialprotected' ];
894  }
895 
896  # Check $wgNamespaceProtection for restricted namespaces
897  if ( $page->isNamespaceProtected( $user ) ) {
898  $ns = $page->getNamespace() == NS_MAIN ?
899  wfMessage( 'nstab-main' )->text() : $page->getNsText();
900  $errors[] = $page->getNamespace() == NS_MEDIAWIKI ?
901  [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
902  }
903 
904  return $errors;
905  }
906 
923  private function checkSiteConfigPermissions(
924  $action,
925  User $user,
926  $errors,
927  $rigor,
928  $short,
929  LinkTarget $page
930  ) {
931  // TODO: remove & rework upon further use of LinkTarget
932  $page = Title::newFromLinkTarget( $page );
933 
934  if ( $action != 'patrol' ) {
935  $error = null;
936  // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
937  // editinterface right. That's implemented as a restriction so no check needed here.
938  if ( $page->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
939  $error = [ 'sitecssprotected', $action ];
940  } elseif ( $page->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
941  $error = [ 'sitejsonprotected', $action ];
942  } elseif ( $page->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
943  $error = [ 'sitejsprotected', $action ];
944  } elseif ( $page->isRawHtmlMessage() ) {
945  // Raw HTML can be used to deploy CSS or JS so require rights for both.
946  if ( !$user->isAllowed( 'editsitejs' ) ) {
947  $error = [ 'sitejsprotected', $action ];
948  } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
949  $error = [ 'sitecssprotected', $action ];
950  }
951  }
952 
953  if ( $error ) {
954  if ( $user->isAllowed( 'editinterface' ) ) {
955  // Most users / site admins will probably find out about the new, more restrictive
956  // permissions by failing to edit something. Give them more info.
957  // TODO remove this a few release cycles after 1.32
958  $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
959  }
960  $errors[] = $error;
961  }
962  }
963 
964  return $errors;
965  }
966 
983  private function checkUserConfigPermissions(
984  $action,
985  User $user,
986  $errors,
987  $rigor,
988  $short,
989  LinkTarget $page
990  ) {
991  // TODO: remove & rework upon further use of LinkTarget
992  $page = Title::newFromLinkTarget( $page );
993 
994  # Protect css/json/js subpages of user pages
995  # XXX: this might be better using restrictions
996 
997  if ( $action === 'patrol' ) {
998  return $errors;
999  }
1000 
1001  if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $page->getText() ) ) {
1002  // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
1003  if (
1004  $page->isUserCssConfigPage()
1005  && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
1006  ) {
1007  $errors[] = [ 'mycustomcssprotected', $action ];
1008  } elseif (
1009  $page->isUserJsonConfigPage()
1010  && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
1011  ) {
1012  $errors[] = [ 'mycustomjsonprotected', $action ];
1013  } elseif (
1014  $page->isUserJsConfigPage()
1015  && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
1016  ) {
1017  $errors[] = [ 'mycustomjsprotected', $action ];
1018  }
1019  } else {
1020  // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
1021  // deletion/suppression which cannot be used for attacks and we want to avoid the
1022  // situation where an unprivileged user can post abusive content on their subpages
1023  // and only very highly privileged users could remove it.
1024  if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
1025  if (
1026  $page->isUserCssConfigPage()
1027  && !$user->isAllowed( 'editusercss' )
1028  ) {
1029  $errors[] = [ 'customcssprotected', $action ];
1030  } elseif (
1031  $page->isUserJsonConfigPage()
1032  && !$user->isAllowed( 'edituserjson' )
1033  ) {
1034  $errors[] = [ 'customjsonprotected', $action ];
1035  } elseif (
1036  $page->isUserJsConfigPage()
1037  && !$user->isAllowed( 'edituserjs' )
1038  ) {
1039  $errors[] = [ 'customjsprotected', $action ];
1040  }
1041  }
1042  }
1043 
1044  return $errors;
1045  }
1046 
1047 }
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
MediaWiki\Linker\LinkTarget\getText
getText()
Returns the link in text form, without namespace prefix or fragment.
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MWNamespace\isTalk
static isTalk( $index)
Is the given namespace a talk namespace?
Definition: MWNamespace.php:119
MediaWiki\Permissions\PermissionManager\getPermissionErrorsInternal
getPermissionErrorsInternal( $action, User $user, LinkTarget $page, $rigor=self::RIGOR_SECURE, $short=false)
Can $user perform $action on a page? This is an internal function, with multiple levels of checks dep...
Definition: PermissionManager.php:211
User\newFatalPermissionDeniedStatus
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:5688
MediaWiki\Permissions\PermissionManager\userCan
userCan( $action, User $user, LinkTarget $page, $rigor=self::RIGOR_SECURE)
Can $user perform $action on a page?
Definition: PermissionManager.php:110
captcha-old.count
count
Definition: captcha-old.py:249
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1983
MessageSpecifier
Definition: MessageSpecifier.php:21
MediaWiki\Permissions\PermissionManager\checkUserConfigPermissions
checkUserConfigPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check CSS/JSON/JS sub-page permissions.
Definition: PermissionManager.php:983
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:45
MediaWiki\Permissions\PermissionManager\missingPermissionError
missingPermissionError( $action, $short)
Get a description array when the user doesn't have the right to perform $action (i....
Definition: PermissionManager.php:449
MediaWiki\Permissions\PermissionManager\checkPermissionHooks
checkPermissionHooks( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check various permission hooks.
Definition: PermissionManager.php:286
NS_FILE
const NS_FILE
Definition: Defines.php:70
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:82
User
User
Definition: All_system_messages.txt:425
User\groupHasPermission
static groupHasPermission( $group, $role)
Check, if the given group has the given permission.
Definition: User.php:5065
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Action
Actions are things which can be done to pages (edit, delete, rollback, etc).
Definition: Action.php:39
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
MediaWiki\Permissions\PermissionManager\$whitelistReadRegexp
string[] $whitelistReadRegexp
Whitelists publicly readable titles with regular expressions.
Definition: PermissionManager.php:61
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
MediaWiki\Permissions\PermissionManager\resultToError
resultToError( $errors, $result)
Add the resulting error code to the errors array.
Definition: PermissionManager.php:325
MediaWiki\Permissions\PermissionManager\checkCascadingSourcesRestrictions
checkCascadingSourcesRestrictions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check restrictions on cascading pages.
Definition: PermissionManager.php:724
MWException
MediaWiki exception.
Definition: MWException.php:26
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
MediaWiki\Permissions\PermissionManager\$blockDisablesLogin
bool $blockDisablesLogin
If set to true, blocked users will no longer be allowed to log in.
Definition: PermissionManager.php:67
$wgLang
$wgLang
Definition: Setup.php:875
MediaWiki\Permissions\PermissionManager\isSameSpecialPage
isSameSpecialPage( $name, LinkTarget $page)
Returns true if this title resolves to the named special page.
Definition: PermissionManager.php:468
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MWNamespace\hasSubpages
static hasSubpages( $index)
Does the namespace allow subpages?
Definition: MWNamespace.php:366
MWNamespace
This is a utility class with only static functions for dealing with namespaces that encodes all the "...
Definition: MWNamespace.php:33
MediaWiki\Permissions\PermissionManager\checkPageRestrictions
checkPageRestrictions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check against page_restrictions table requirements on this page.
Definition: PermissionManager.php:676
MediaWiki\Permissions\PermissionManager\$specialPageFactory
SpecialPageFactory $specialPageFactory
Definition: PermissionManager.php:51
MWNamespace\isMovable
static isMovable( $index)
Can pages in the given namespace be moved?
Definition: MWNamespace.php:89
MediaWiki\Permissions\PermissionManager\checkQuickPermissions
checkQuickPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Permissions checks that fail most often, and which are easiest to test.
Definition: PermissionManager.php:583
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:78
RequestContext
Group all the pieces relevant to the context of a request into one instance.
Definition: RequestContext.php:32
$wgDeleteRevisionsLimit
$wgDeleteRevisionsLimit
Optional to restrict deletion of pages with higher revision counts to users with the 'bigdelete' perm...
Definition: DefaultSettings.php:5511
MediaWiki\Permissions\PermissionManager\$whitelistRead
string[] $whitelistRead
List of pages names anonymous user may see.
Definition: PermissionManager.php:58
MediaWiki\Permissions\PermissionManager\checkUserBlock
checkUserBlock( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check that the user isn't blocked from editing.
Definition: PermissionManager.php:496
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
MediaWiki\Permissions\PermissionManager\checkActionPermissions
checkActionPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check action permissions not already checked in checkQuickPermissions.
Definition: PermissionManager.php:786
MediaWiki\Permissions\PermissionManager\checkReadPermissions
checkReadPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check that the user is allowed to read this page.
Definition: PermissionManager.php:363
MediaWiki\Permissions\PermissionManager\checkSpecialsAndNSPermissions
checkSpecialsAndNSPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check permissions on special pages & namespaces.
Definition: PermissionManager.php:879
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
MediaWiki\Special\SpecialPageFactory
Factory for handling the special page list and generating SpecialPage objects.
Definition: SpecialPageFactory.php:63
MediaWiki\Permissions\PermissionManager
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Definition: PermissionManager.php:43
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:885
SpecialPage
Parent class for all special pages.
Definition: SpecialPage.php:36
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
MediaWiki\Permissions\PermissionManager\$emailConfirmToEdit
bool $emailConfirmToEdit
Require users to confirm email address before they can edit.
Definition: PermissionManager.php:64
MediaWiki\Permissions\PermissionManager\getPermissionErrors
getPermissionErrors( $action, User $user, LinkTarget $page, $rigor=self::RIGOR_SECURE, $ignoreErrors=[])
Can $user perform $action on a page?
Definition: PermissionManager.php:132
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:269
MediaWiki\Permissions\PermissionManager\checkSiteConfigPermissions
checkSiteConfigPermissions( $action, User $user, $errors, $rigor, $short, LinkTarget $page)
Check sitewide CSS/JSON/JS permissions.
Definition: PermissionManager.php:923
MediaWiki\$action
string $action
Cache what action this request is.
Definition: MediaWiki.php:48
User\isEveryoneAllowed
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:5085
Title
Represents a title within MediaWiki.
Definition: Title.php:40
Action\exists
static exists( $name)
Check if a given action is recognised, even if it's disabled.
Definition: Action.php:170
FatalError
Exception class which takes an HTML error message, and does not produce a backtrace.
Definition: FatalError.php:28
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
NS_USER
const NS_USER
Definition: Defines.php:66
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:72
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
MediaWiki\Permissions\PermissionManager\__construct
__construct(SpecialPageFactory $specialPageFactory, $whitelistRead, $whitelistReadRegexp, $emailConfirmToEdit, $blockDisablesLogin)
Definition: PermissionManager.php:76
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
Action\factory
static factory( $action, Page $page, IContextSource $context=null)
Get an appropriate Action subclass for the given action.
Definition: Action.php:97
Hooks
Hooks class.
Definition: Hooks.php:34
MediaWiki\Permissions
Definition: PermissionManager.php:20
MediaWiki\Permissions\PermissionManager\isBlockedFrom
isBlockedFrom(User $user, LinkTarget $page, $fromReplica=false)
Check if user is blocked from editing a particular article.
Definition: PermissionManager.php:167