MediaWiki  master
NamespaceInfo.php
Go to the documentation of this file.
1 <?php
25 
33 
40 
42  private $canonicalNamespaces = null;
43 
45  private $namespaceIndexes = false;
46 
48  private $validNamespaces = null;
49 
51  private $options;
52 
59  public static $constructorOptions = [
60  'AllowImageMoving',
61  'CanonicalNamespaceNames',
62  'CapitalLinkOverrides',
63  'CapitalLinks',
64  'ContentNamespaces',
65  'ExtraNamespaces',
66  'ExtraSignatureNamespaces',
67  'NamespaceContentModels',
68  'NamespaceProtection',
69  'NamespacesWithSubpages',
70  'NonincludableNamespaces',
71  'RestrictionLevels',
72  ];
73 
77  public function __construct( ServiceOptions $options ) {
78  $options->assertRequiredOptions( self::$constructorOptions );
79  $this->options = $options;
80  }
81 
94  private function isMethodValidFor( $index, $method ) {
95  if ( $index < NS_MAIN ) {
96  throw new MWException( "$method does not make any sense for given namespace $index" );
97  }
98  return true;
99  }
100 
107  public function isMovable( $index ) {
108  $result = $index >= NS_MAIN &&
109  ( $index != NS_FILE || $this->options->get( 'AllowImageMoving' ) );
110 
114  Hooks::run( 'NamespaceIsMovable', [ $index, &$result ] );
115 
116  return $result;
117  }
118 
125  public function isSubject( $index ) {
126  return !$this->isTalk( $index );
127  }
128 
135  public function isTalk( $index ) {
136  return $index > NS_MAIN
137  && $index % 2;
138  }
139 
146  public function getTalk( $index ) {
147  $this->isMethodValidFor( $index, __METHOD__ );
148  return $this->isTalk( $index )
149  ? $index
150  : $index + 1;
151  }
152 
158  public function getTalkPage( LinkTarget $target ) : LinkTarget {
159  if ( $this->isTalk( $target->getNamespace() ) ) {
160  return $target;
161  }
162  return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDbKey() );
163  }
164 
172  public function getSubject( $index ) {
173  # Handle special namespaces
174  if ( $index < NS_MAIN ) {
175  return $index;
176  }
177 
178  return $this->isTalk( $index )
179  ? $index - 1
180  : $index;
181  }
182 
187  public function getSubjectPage( LinkTarget $target ) : LinkTarget {
188  if ( $this->isSubject( $target->getNamespace() ) ) {
189  return $target;
190  }
191  return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDbKey() );
192  }
193 
203  public function getAssociated( $index ) {
204  $this->isMethodValidFor( $index, __METHOD__ );
205 
206  if ( $this->isSubject( $index ) ) {
207  return $this->getTalk( $index );
208  }
209  return $this->getSubject( $index );
210  }
211 
218  public function getAssociatedPage( LinkTarget $target ) : LinkTarget {
219  return new TitleValue(
220  $this->getAssociated( $target->getNamespace() ), $target->getDbKey() );
221  }
222 
230  public function exists( $index ) {
231  $nslist = $this->getCanonicalNamespaces();
232  return isset( $nslist[$index] );
233  }
234 
248  public function equals( $ns1, $ns2 ) {
249  return $ns1 == $ns2;
250  }
251 
262  public function subjectEquals( $ns1, $ns2 ) {
263  return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
264  }
265 
272  public function getCanonicalNamespaces() {
273  if ( $this->canonicalNamespaces === null ) {
274  $this->canonicalNamespaces =
275  [ NS_MAIN => '' ] + $this->options->get( 'CanonicalNamespaceNames' );
276  $this->canonicalNamespaces +=
277  ExtensionRegistry::getInstance()->getAttribute( 'ExtensionNamespaces' );
278  if ( is_array( $this->options->get( 'ExtraNamespaces' ) ) ) {
279  $this->canonicalNamespaces += $this->options->get( 'ExtraNamespaces' );
280  }
281  Hooks::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces ] );
282  }
284  }
285 
292  public function getCanonicalName( $index ) {
293  $nslist = $this->getCanonicalNamespaces();
294  return $nslist[$index] ?? false;
295  }
296 
304  public function getCanonicalIndex( $name ) {
305  if ( $this->namespaceIndexes === false ) {
306  $this->namespaceIndexes = [];
307  foreach ( $this->getCanonicalNamespaces() as $i => $text ) {
308  $this->namespaceIndexes[strtolower( $text )] = $i;
309  }
310  }
311  if ( array_key_exists( $name, $this->namespaceIndexes ) ) {
312  return $this->namespaceIndexes[$name];
313  } else {
314  return null;
315  }
316  }
317 
323  public function getValidNamespaces() {
324  if ( is_null( $this->validNamespaces ) ) {
325  foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
326  if ( $ns >= 0 ) {
327  $this->validNamespaces[] = $ns;
328  }
329  }
330  // T109137: sort numerically
331  sort( $this->validNamespaces, SORT_NUMERIC );
332  }
333 
334  return $this->validNamespaces;
335  }
336 
337  /*
338 
345  public function hasTalkNamespace( $index ) {
346  return $index >= NS_MAIN;
347  }
348 
356  public function isContent( $index ) {
357  return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
358  }
359 
367  public function wantSignatures( $index ) {
368  return $this->isTalk( $index ) ||
369  in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
370  }
371 
378  public function isWatchable( $index ) {
379  return $index >= NS_MAIN;
380  }
381 
388  public function hasSubpages( $index ) {
389  return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
390  }
391 
396  public function getContentNamespaces() {
397  $contentNamespaces = $this->options->get( 'ContentNamespaces' );
398  if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
399  return [ NS_MAIN ];
400  } elseif ( !in_array( NS_MAIN, $contentNamespaces ) ) {
401  // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
402  return array_merge( [ NS_MAIN ], $contentNamespaces );
403  } else {
404  return $contentNamespaces;
405  }
406  }
407 
414  public function getSubjectNamespaces() {
415  return array_filter(
416  $this->getValidNamespaces(),
417  [ $this, 'isSubject' ]
418  );
419  }
420 
427  public function getTalkNamespaces() {
428  return array_filter(
429  $this->getValidNamespaces(),
430  [ $this, 'isTalk' ]
431  );
432  }
433 
440  public function isCapitalized( $index ) {
441  // Turn NS_MEDIA into NS_FILE
442  $index = $index === NS_MEDIA ? NS_FILE : $index;
443 
444  // Make sure to get the subject of our namespace
445  $index = $this->getSubject( $index );
446 
447  // Some namespaces are special and should always be upper case
448  if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
449  return true;
450  }
451  $overrides = $this->options->get( 'CapitalLinkOverrides' );
452  if ( isset( $overrides[$index] ) ) {
453  // CapitalLinkOverrides is explicitly set
454  return $overrides[$index];
455  }
456  // Default to the global setting
457  return $this->options->get( 'CapitalLinks' );
458  }
459 
467  public function hasGenderDistinction( $index ) {
468  return $index == NS_USER || $index == NS_USER_TALK;
469  }
470 
477  public function isNonincludable( $index ) {
478  $namespaces = $this->options->get( 'NonincludableNamespaces' );
479  return $namespaces && in_array( $index, $namespaces );
480  }
481 
492  public function getNamespaceContentModel( $index ) {
493  return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
494  }
495 
507  public function getRestrictionLevels( $index, User $user = null ) {
508  if ( !isset( $this->options->get( 'NamespaceProtection' )[$index] ) ) {
509  // All levels are valid if there's no namespace restriction.
510  // But still filter by user, if necessary
511  $levels = $this->options->get( 'RestrictionLevels' );
512  if ( $user ) {
513  $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
514  $right = $level;
515  if ( $right == 'sysop' ) {
516  $right = 'editprotected'; // BC
517  }
518  if ( $right == 'autoconfirmed' ) {
519  $right = 'editsemiprotected'; // BC
520  }
521  return ( $right == '' || $user->isAllowed( $right ) );
522  } ) );
523  }
524  return $levels;
525  }
526 
527  // $wgNamespaceProtection can require one or more rights to edit the namespace, which
528  // may be satisfied by membership in multiple groups each giving a subset of those rights.
529  // A restriction level is redundant if, for any one of the namespace rights, all groups
530  // giving that right also give the restriction level's right. Or, conversely, a
531  // restriction level is not redundant if, for every namespace right, there's at least one
532  // group giving that right without the restriction level's right.
533  //
534  // First, for each right, get a list of groups with that right.
535  $namespaceRightGroups = [];
536  foreach ( (array)$this->options->get( 'NamespaceProtection' )[$index] as $right ) {
537  if ( $right == 'sysop' ) {
538  $right = 'editprotected'; // BC
539  }
540  if ( $right == 'autoconfirmed' ) {
541  $right = 'editsemiprotected'; // BC
542  }
543  if ( $right != '' ) {
544  $namespaceRightGroups[$right] = User::getGroupsWithPermission( $right );
545  }
546  }
547 
548  // Now, go through the protection levels one by one.
549  $usableLevels = [ '' ];
550  foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
551  $right = $level;
552  if ( $right == 'sysop' ) {
553  $right = 'editprotected'; // BC
554  }
555  if ( $right == 'autoconfirmed' ) {
556  $right = 'editsemiprotected'; // BC
557  }
558 
559  if ( $right != '' &&
560  !isset( $namespaceRightGroups[$right] ) &&
561  ( !$user || $user->isAllowed( $right ) )
562  ) {
563  // Do any of the namespace rights imply the restriction right? (see explanation above)
564  foreach ( $namespaceRightGroups as $groups ) {
565  if ( !array_diff( $groups, User::getGroupsWithPermission( $right ) ) ) {
566  // Yes, this one does.
567  continue 2;
568  }
569  }
570  // No, keep the restriction level
571  $usableLevels[] = $level;
572  }
573  }
574 
575  return $usableLevels;
576  }
577 
587  public function getCategoryLinkType( $index ) {
588  $this->isMethodValidFor( $index, __METHOD__ );
589 
590  if ( $index == NS_CATEGORY ) {
591  return 'subcat';
592  } elseif ( $index == NS_FILE ) {
593  return 'file';
594  } else {
595  return 'page';
596  }
597  }
598 }
array false $namespaceIndexes
Canonical namespaces index cache.
isMovable( $index)
Can pages in the given namespace be moved?
const NS_MAIN
Definition: Defines.php:64
__construct(ServiceOptions $options)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
exists( $index)
Returns whether the specified namespace exists.
getSubjectPage(LinkTarget $target)
const NS_SPECIAL
Definition: Defines.php:53
string [] null $canonicalNamespaces
Canonical namespaces cache.
getNamespace()
Get the namespace index.
getSubject( $index)
Get the subject namespace index for a given namespace Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
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:1980
A class for passing options to services.
getAssociatedPage(LinkTarget $target)
getTalk( $index)
Get the talk namespace index for a given namespace.
getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
getCanonicalIndex( $name)
Returns the index for a given canonical name, or NULL The input must be converted to lower case first...
equals( $ns1, $ns2)
Returns whether the specified namespaces are the same namespace.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
subjectEquals( $ns1, $ns2)
Returns whether the specified namespaces share the same subject.
const NS_FILE
Definition: Defines.php:70
ServiceOptions $options
int [] null $validNamespaces
Valid namespaces cache.
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
const NS_MEDIAWIKI
Definition: Defines.php:72
isMethodValidFor( $index, $method)
Throw an exception when trying to get the subject or talk page for a given namespace where it does no...
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys, without regard for order.
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
getAssociated( $index)
Get the associated namespace.
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place. Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
getTalkPage(LinkTarget $target)
isTalk( $index)
Is the given namespace a talk namespace?
getCanonicalName( $index)
Returns the canonical (English) name for a given index.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$alwaysCapitalizedNamespaces
These namespaces should always be first-letter capitalized, now and forevermore.
getCanonicalNamespaces()
Returns array of all defined namespaces with their canonical (English) names.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
isSubject( $index)
Is the given namespace is a subject (non-talk) namespace?