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 
148  public function getTalk( $index ) {
149  $this->isMethodValidFor( $index, __METHOD__ );
150  return $this->isTalk( $index )
151  ? $index
152  : $index + 1;
153  }
154 
164  public function getTalkPage( LinkTarget $target ) : LinkTarget {
165  if ( $target->getText() === '' ) {
166  throw new MWException( 'Can\'t determine talk page associated with relative section link' );
167  }
168 
169  if ( $target->getInterwiki() !== '' ) {
170  throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
171  }
172 
173  if ( $this->isTalk( $target->getNamespace() ) ) {
174  return $target;
175  }
176 
177  // NOTE: getTalk throws on bad namespaces!
178  return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
179  }
180 
192  public function canHaveTalkPage( LinkTarget $target ) {
193  if ( $target->getText() === '' || $target->getInterwiki() !== '' ) {
194  return false;
195  }
196 
197  if ( $target->getNamespace() < NS_MAIN ) {
198  return false;
199  }
200 
201  return true;
202  }
203 
211  public function getSubject( $index ) {
212  # Handle special namespaces
213  if ( $index < NS_MAIN ) {
214  return $index;
215  }
216 
217  return $this->isTalk( $index )
218  ? $index - 1
219  : $index;
220  }
221 
226  public function getSubjectPage( LinkTarget $target ) : LinkTarget {
227  if ( $this->isSubject( $target->getNamespace() ) ) {
228  return $target;
229  }
230  return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
231  }
232 
242  public function getAssociated( $index ) {
243  $this->isMethodValidFor( $index, __METHOD__ );
244 
245  if ( $this->isSubject( $index ) ) {
246  return $this->getTalk( $index );
247  }
248  return $this->getSubject( $index );
249  }
250 
257  public function getAssociatedPage( LinkTarget $target ) : LinkTarget {
258  if ( $target->getText() === '' ) {
259  throw new MWException( 'Can\'t determine talk page associated with relative section link' );
260  }
261 
262  if ( $target->getInterwiki() !== '' ) {
263  throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
264  }
265 
266  return new TitleValue(
267  $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
268  }
269 
277  public function exists( $index ) {
278  $nslist = $this->getCanonicalNamespaces();
279  return isset( $nslist[$index] );
280  }
281 
295  public function equals( $ns1, $ns2 ) {
296  return $ns1 == $ns2;
297  }
298 
309  public function subjectEquals( $ns1, $ns2 ) {
310  return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
311  }
312 
319  public function getCanonicalNamespaces() {
320  if ( $this->canonicalNamespaces === null ) {
321  $this->canonicalNamespaces =
322  [ NS_MAIN => '' ] + $this->options->get( 'CanonicalNamespaceNames' );
323  $this->canonicalNamespaces +=
324  ExtensionRegistry::getInstance()->getAttribute( 'ExtensionNamespaces' );
325  if ( is_array( $this->options->get( 'ExtraNamespaces' ) ) ) {
326  $this->canonicalNamespaces += $this->options->get( 'ExtraNamespaces' );
327  }
328  Hooks::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces ] );
329  }
331  }
332 
339  public function getCanonicalName( $index ) {
340  $nslist = $this->getCanonicalNamespaces();
341  return $nslist[$index] ?? false;
342  }
343 
351  public function getCanonicalIndex( $name ) {
352  if ( $this->namespaceIndexes === false ) {
353  $this->namespaceIndexes = [];
354  foreach ( $this->getCanonicalNamespaces() as $i => $text ) {
355  $this->namespaceIndexes[strtolower( $text )] = $i;
356  }
357  }
358  if ( array_key_exists( $name, $this->namespaceIndexes ) ) {
359  return $this->namespaceIndexes[$name];
360  } else {
361  return null;
362  }
363  }
364 
370  public function getValidNamespaces() {
371  if ( is_null( $this->validNamespaces ) ) {
372  foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
373  if ( $ns >= 0 ) {
374  $this->validNamespaces[] = $ns;
375  }
376  }
377  // T109137: sort numerically
378  sort( $this->validNamespaces, SORT_NUMERIC );
379  }
380 
381  return $this->validNamespaces;
382  }
383 
384  /*
385 
392  public function hasTalkNamespace( $index ) {
393  return $index >= NS_MAIN;
394  }
395 
403  public function isContent( $index ) {
404  return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
405  }
406 
414  public function wantSignatures( $index ) {
415  return $this->isTalk( $index ) ||
416  in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
417  }
418 
425  public function isWatchable( $index ) {
426  return $index >= NS_MAIN;
427  }
428 
435  public function hasSubpages( $index ) {
436  return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
437  }
438 
443  public function getContentNamespaces() {
444  $contentNamespaces = $this->options->get( 'ContentNamespaces' );
445  if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
446  return [ NS_MAIN ];
447  } elseif ( !in_array( NS_MAIN, $contentNamespaces ) ) {
448  // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
449  return array_merge( [ NS_MAIN ], $contentNamespaces );
450  } else {
451  return $contentNamespaces;
452  }
453  }
454 
461  public function getSubjectNamespaces() {
462  return array_filter(
463  $this->getValidNamespaces(),
464  [ $this, 'isSubject' ]
465  );
466  }
467 
474  public function getTalkNamespaces() {
475  return array_filter(
476  $this->getValidNamespaces(),
477  [ $this, 'isTalk' ]
478  );
479  }
480 
487  public function isCapitalized( $index ) {
488  // Turn NS_MEDIA into NS_FILE
489  $index = $index === NS_MEDIA ? NS_FILE : $index;
490 
491  // Make sure to get the subject of our namespace
492  $index = $this->getSubject( $index );
493 
494  // Some namespaces are special and should always be upper case
495  if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
496  return true;
497  }
498  $overrides = $this->options->get( 'CapitalLinkOverrides' );
499  if ( isset( $overrides[$index] ) ) {
500  // CapitalLinkOverrides is explicitly set
501  return $overrides[$index];
502  }
503  // Default to the global setting
504  return $this->options->get( 'CapitalLinks' );
505  }
506 
514  public function hasGenderDistinction( $index ) {
515  return $index == NS_USER || $index == NS_USER_TALK;
516  }
517 
524  public function isNonincludable( $index ) {
525  $namespaces = $this->options->get( 'NonincludableNamespaces' );
526  return $namespaces && in_array( $index, $namespaces );
527  }
528 
539  public function getNamespaceContentModel( $index ) {
540  return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
541  }
542 
554  public function getRestrictionLevels( $index, User $user = null ) {
555  if ( !isset( $this->options->get( 'NamespaceProtection' )[$index] ) ) {
556  // All levels are valid if there's no namespace restriction.
557  // But still filter by user, if necessary
558  $levels = $this->options->get( 'RestrictionLevels' );
559  if ( $user ) {
560  $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
561  $right = $level;
562  if ( $right == 'sysop' ) {
563  $right = 'editprotected'; // BC
564  }
565  if ( $right == 'autoconfirmed' ) {
566  $right = 'editsemiprotected'; // BC
567  }
568  return ( $right == '' || $user->isAllowed( $right ) );
569  } ) );
570  }
571  return $levels;
572  }
573 
574  // $wgNamespaceProtection can require one or more rights to edit the namespace, which
575  // may be satisfied by membership in multiple groups each giving a subset of those rights.
576  // A restriction level is redundant if, for any one of the namespace rights, all groups
577  // giving that right also give the restriction level's right. Or, conversely, a
578  // restriction level is not redundant if, for every namespace right, there's at least one
579  // group giving that right without the restriction level's right.
580  //
581  // First, for each right, get a list of groups with that right.
582  $namespaceRightGroups = [];
583  foreach ( (array)$this->options->get( 'NamespaceProtection' )[$index] as $right ) {
584  if ( $right == 'sysop' ) {
585  $right = 'editprotected'; // BC
586  }
587  if ( $right == 'autoconfirmed' ) {
588  $right = 'editsemiprotected'; // BC
589  }
590  if ( $right != '' ) {
591  $namespaceRightGroups[$right] = User::getGroupsWithPermission( $right );
592  }
593  }
594 
595  // Now, go through the protection levels one by one.
596  $usableLevels = [ '' ];
597  foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
598  $right = $level;
599  if ( $right == 'sysop' ) {
600  $right = 'editprotected'; // BC
601  }
602  if ( $right == 'autoconfirmed' ) {
603  $right = 'editsemiprotected'; // BC
604  }
605 
606  if ( $right != '' &&
607  !isset( $namespaceRightGroups[$right] ) &&
608  ( !$user || $user->isAllowed( $right ) )
609  ) {
610  // Do any of the namespace rights imply the restriction right? (see explanation above)
611  foreach ( $namespaceRightGroups as $groups ) {
612  if ( !array_diff( $groups, User::getGroupsWithPermission( $right ) ) ) {
613  // Yes, this one does.
614  continue 2;
615  }
616  }
617  // No, keep the restriction level
618  $usableLevels[] = $level;
619  }
620  }
621 
622  return $usableLevels;
623  }
624 
634  public function getCategoryLinkType( $index ) {
635  $this->isMethodValidFor( $index, __METHOD__ );
636 
637  if ( $index == NS_CATEGORY ) {
638  return 'subcat';
639  } elseif ( $index == NS_FILE ) {
640  return 'file';
641  } else {
642  return 'page';
643  }
644  }
645 }
array false $namespaceIndexes
Canonical namespaces index cache.
isMovable( $index)
Can pages in the given namespace be moved?
const NS_MAIN
Definition: Defines.php:60
__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:49
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. '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:1969
A class for passing options to services.
canHaveTalkPage(LinkTarget $target)
Can the title have a corresponding talk page?
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.
getDBkey()
Get the main part with underscores.
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:767
subjectEquals( $ns1, $ns2)
Returns whether the specified namespaces share the same subject.
const NS_FILE
Definition: Defines.php:66
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:68
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)
Get a LinkTarget referring to the talk page of $target.
getInterwiki()
The interwiki component of this LinkTarget.
getText()
Returns the link in text form, without namespace prefix or fragment.
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?