3 * Provide things related to namespaces.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace MediaWiki\Title
;
25 use InvalidArgumentException
;
26 use MediaWiki\Config\ServiceOptions
;
27 use MediaWiki\HookContainer\HookContainer
;
28 use MediaWiki\HookContainer\HookRunner
;
29 use MediaWiki\Linker\LinkTarget
;
30 use MediaWiki\MainConfigNames
;
34 * This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of
35 * them based on index. The textual names of the namespaces are handled by Language.php.
42 * These namespaces should always be first-letter capitalized, now and
43 * forevermore. Historically, they could've probably been lowercased too,
44 * but some things are just too ingrained now. :)
46 private const ALWAYS_CAPITALIZED_NAMESPACES
= [ NS_SPECIAL
, NS_USER
, NS_MEDIAWIKI
];
48 /** @var string[]|null Canonical namespaces cache */
49 private $canonicalNamespaces = null;
51 /** @var array|false Canonical namespaces index cache */
52 private $namespaceIndexes = false;
54 /** @var int[]|null Valid namespaces cache */
55 private $validNamespaces = null;
57 private ServiceOptions
$options;
58 private HookRunner
$hookRunner;
59 private array $extensionNamespaces;
60 private array $extensionImmovableNamespaces;
63 * Definitions of the NS_ constants are in Defines.php
67 public const CANONICAL_NAMES
= [
69 NS_SPECIAL
=> 'Special',
73 NS_USER_TALK
=> 'User_talk',
74 NS_PROJECT
=> 'Project',
75 NS_PROJECT_TALK
=> 'Project_talk',
77 NS_FILE_TALK
=> 'File_talk',
78 NS_MEDIAWIKI
=> 'MediaWiki',
79 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
80 NS_TEMPLATE
=> 'Template',
81 NS_TEMPLATE_TALK
=> 'Template_talk',
83 NS_HELP_TALK
=> 'Help_talk',
84 NS_CATEGORY
=> 'Category',
85 NS_CATEGORY_TALK
=> 'Category_talk',
89 * @internal For use by ServiceWiring
91 public const CONSTRUCTOR_OPTIONS
= [
92 MainConfigNames
::CanonicalNamespaceNames
,
93 MainConfigNames
::CapitalLinkOverrides
,
94 MainConfigNames
::CapitalLinks
,
95 MainConfigNames
::ContentNamespaces
,
96 MainConfigNames
::ExtraNamespaces
,
97 MainConfigNames
::ExtraSignatureNamespaces
,
98 MainConfigNames
::NamespaceContentModels
,
99 MainConfigNames
::NamespacesWithSubpages
,
100 MainConfigNames
::NonincludableNamespaces
,
103 public function __construct(
104 ServiceOptions
$options,
105 HookContainer
$hookContainer,
106 array $extensionNamespaces,
107 array $extensionImmovableNamespaces
109 $options->assertRequiredOptions( self
::CONSTRUCTOR_OPTIONS
);
110 $this->options
= $options;
111 $this->hookRunner
= new HookRunner( $hookContainer );
112 $this->extensionNamespaces
= $extensionNamespaces;
113 $this->extensionImmovableNamespaces
= $extensionImmovableNamespaces;
117 * Throw an exception when trying to get the subject or talk page
118 * for a given namespace where it does not make sense.
119 * Special namespaces are defined in includes/Defines.php and have
120 * a value below 0 (ex: NS_SPECIAL = -1 , NS_MEDIA = -2)
123 * @param string $method
125 * @throws MWException
128 private function isMethodValidFor( $index, $method ) {
129 if ( $index < NS_MAIN
) {
130 throw new MWException( "$method does not make any sense for given namespace $index" );
136 * Throw if given index isn't an integer or integer-like string and so can't be a valid namespace.
138 * @param int|string $index
139 * @param string $method
141 * @throws InvalidArgumentException
142 * @return int Cleaned up namespace index
144 private function makeValidNamespace( $index, $method ) {
147 // Namespace index numbers as strings
148 ||
ctype_digit( $index )
149 // Negative numbers as strings
150 ||
( $index[0] === '-' && ctype_digit( substr( $index, 1 ) ) )
152 throw new InvalidArgumentException(
153 "$method called with non-integer (" . get_debug_type( $index ) . ") namespace '$index'"
157 return intval( $index );
161 * Can pages in the given namespace be moved?
163 * @param int $index Namespace index
166 public function isMovable( $index ) {
167 $result = $index >= NS_MAIN
&& !in_array( $index, $this->extensionImmovableNamespaces
);
172 $this->hookRunner
->onNamespaceIsMovable( $index, $result );
178 * Is the given namespace is a subject (non-talk) namespace?
180 * @param int $index Namespace index
183 public function isSubject( $index ) {
184 return !$this->isTalk( $index );
188 * Is the given namespace a talk namespace?
190 * @param int $index Namespace index
193 public function isTalk( $index ) {
194 $index = $this->makeValidNamespace( $index, __METHOD__
);
196 return $index > NS_MAIN
201 * Get the talk namespace index for a given namespace
203 * @param int $index Namespace index
205 * @throws MWException if the given namespace doesn't have an associated talk namespace
208 public function getTalk( $index ) {
209 $index = $this->makeValidNamespace( $index, __METHOD__
);
211 $this->isMethodValidFor( $index, __METHOD__
);
212 return $this->isTalk( $index )
218 * Get a LinkTarget referring to the talk page of $target.
220 * @see canHaveTalkPage
221 * @param LinkTarget $target
222 * @return LinkTarget Talk page for $target
223 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL,
224 * because it's a relative section-only link, or it's an interwiki link.
226 public function getTalkPage( LinkTarget
$target ): LinkTarget
{
227 if ( $target->getText() === '' ) {
228 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
231 if ( $target->getInterwiki() !== '' ) {
232 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
235 if ( $this->isTalk( $target->getNamespace() ) ) {
239 // NOTE: getTalk throws on bad namespaces!
240 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
244 * Can the title have a corresponding talk page?
246 * False for relative section-only links (with getText() === ''),
247 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
251 * @param LinkTarget $target
252 * @return bool True if this title either is a talk page or can have a talk page associated.
254 public function canHaveTalkPage( LinkTarget
$target ) {
255 return $target->getNamespace() >= NS_MAIN
&&
256 !$target->isExternal() &&
257 $target->getText() !== '';
261 * Get the subject namespace index for a given namespace
262 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
264 * @param int $index Namespace index
267 public function getSubject( $index ) {
268 $index = $this->makeValidNamespace( $index, __METHOD__
);
270 # Handle special namespaces
271 if ( $index < NS_MAIN
) {
275 return $this->isTalk( $index )
281 * @param LinkTarget $target
282 * @return LinkTarget Subject page for $target
284 public function getSubjectPage( LinkTarget
$target ): LinkTarget
{
285 if ( $this->isSubject( $target->getNamespace() ) ) {
288 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
292 * Get the associated namespace.
293 * For talk namespaces, returns the subject (non-talk) namespace
294 * For subject (non-talk) namespaces, returns the talk namespace
296 * @param int $index Namespace index
298 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
300 public function getAssociated( $index ) {
301 $this->isMethodValidFor( $index, __METHOD__
);
303 if ( $this->isSubject( $index ) ) {
304 return $this->getTalk( $index );
306 return $this->getSubject( $index );
310 * @param LinkTarget $target
311 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
313 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
315 public function getAssociatedPage( LinkTarget
$target ): LinkTarget
{
316 if ( $target->getText() === '' ) {
317 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
320 if ( $target->getInterwiki() !== '' ) {
321 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
324 return new TitleValue(
325 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
329 * Returns whether the specified namespace exists
335 public function exists( $index ) {
336 $nslist = $this->getCanonicalNamespaces();
337 return isset( $nslist[$index] );
341 * Returns whether the specified namespaces are the same namespace
343 * @note It's possible that in the future we may start using something
344 * other than just namespace indexes. Under that circumstance making use
345 * of this function rather than directly doing comparison will make
346 * sure that code will not potentially break.
348 * @param int $ns1 The first namespace index
349 * @param int $ns2 The second namespace index
353 public function equals( $ns1, $ns2 ) {
358 * Returns whether the specified namespaces share the same subject.
359 * eg: NS_USER and NS_USER wil return true, as well
360 * NS_USER and NS_USER_TALK will return true.
362 * @param int $ns1 The first namespace index
363 * @param int $ns2 The second namespace index
367 public function subjectEquals( $ns1, $ns2 ) {
368 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
372 * Returns array of all defined namespaces with their canonical
377 public function getCanonicalNamespaces() {
378 if ( $this->canonicalNamespaces
=== null ) {
379 $this->canonicalNamespaces
=
380 [ NS_MAIN
=> '' ] +
$this->options
->get( MainConfigNames
::CanonicalNamespaceNames
);
381 $this->canonicalNamespaces +
= $this->extensionNamespaces
;
382 if ( is_array( $this->options
->get( MainConfigNames
::ExtraNamespaces
) ) ) {
383 $this->canonicalNamespaces +
= $this->options
->get( MainConfigNames
::ExtraNamespaces
);
385 $this->hookRunner
->onCanonicalNamespaces( $this->canonicalNamespaces
);
387 return $this->canonicalNamespaces
;
391 * Returns the canonical (English) name for a given index
393 * @param int $index Namespace index
394 * @return string|false If no canonical definition.
396 public function getCanonicalName( $index ) {
397 $nslist = $this->getCanonicalNamespaces();
398 return $nslist[$index] ??
false;
402 * Returns the index for a given canonical name, or NULL
403 * The input *must* be converted to lower case first
405 * @param string $name Namespace name
408 public function getCanonicalIndex( $name ) {
409 if ( $this->namespaceIndexes
=== false ) {
410 $this->namespaceIndexes
= [];
411 foreach ( $this->getCanonicalNamespaces() as $i => $text ) {
412 $this->namespaceIndexes
[strtolower( $text )] = $i;
415 if ( array_key_exists( $name, $this->namespaceIndexes
) ) {
416 return $this->namespaceIndexes
[$name];
423 * Returns an array of the namespaces (by integer id) that exist on the wiki. Used primarily by
424 * the API in help documentation. The array is sorted numerically and omits negative namespaces.
427 public function getValidNamespaces() {
428 if ( $this->validNamespaces
=== null ) {
429 $this->validNamespaces
= [];
430 foreach ( $this->getCanonicalNamespaces() as $ns => $_ ) {
432 $this->validNamespaces
[] = $ns;
435 // T109137: sort numerically
436 sort( $this->validNamespaces
, SORT_NUMERIC
);
439 return $this->validNamespaces
;
443 * Does this namespace ever have a talk namespace?
445 * @param int $index Namespace ID
446 * @return bool True if this namespace either is or has a corresponding talk namespace.
448 public function hasTalkNamespace( $index ) {
449 return $index >= NS_MAIN
;
453 * Does this namespace contain content, for the purposes of calculating
456 * @param int $index Index to check
459 public function isContent( $index ) {
460 return $index == NS_MAIN ||
461 in_array( $index, $this->options
->get( MainConfigNames
::ContentNamespaces
) );
465 * Might pages in this namespace require the use of the Signature button on
468 * @param int $index Index to check
471 public function wantSignatures( $index ) {
472 return $this->isTalk( $index ) ||
473 in_array( $index, $this->options
->get( MainConfigNames
::ExtraSignatureNamespaces
) );
477 * Can pages in a namespace be watched?
482 public function isWatchable( $index ) {
483 return $index >= NS_MAIN
;
487 * Does the namespace allow subpages? Note that this refers to structured
488 * handling of subpages, and does not include SpecialPage subpage parameters.
490 * @param int $index Index to check
493 public function hasSubpages( $index ) {
494 return !empty( $this->options
->get( MainConfigNames
::NamespacesWithSubpages
)[$index] );
498 * Get a list of all namespace indices which are considered to contain content
499 * @return int[] Array of namespace indices
501 public function getContentNamespaces() {
502 $contentNamespaces = $this->options
->get( MainConfigNames
::ContentNamespaces
);
503 if ( !is_array( $contentNamespaces ) ||
$contentNamespaces === [] ) {
505 } elseif ( !in_array( NS_MAIN
, $contentNamespaces ) ) {
506 // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
507 return array_merge( [ NS_MAIN
], $contentNamespaces );
509 return $contentNamespaces;
514 * List all namespace indices which are considered subject, aka not a talk
515 * or special namespace. See also NamespaceInfo::isSubject
517 * @return int[] Array of namespace indices
519 public function getSubjectNamespaces() {
521 $this->getValidNamespaces(),
522 [ $this, 'isSubject' ]
527 * List all namespace indices which are considered talks, aka not a subject
528 * or special namespace. See also NamespaceInfo::isTalk
530 * @return int[] Array of namespace indices
532 public function getTalkNamespaces() {
534 $this->getValidNamespaces(),
540 * Is the namespace first-letter capitalized?
542 * @param int $index Index to check
545 public function isCapitalized( $index ) {
546 // Turn NS_MEDIA into NS_FILE
547 $index = $index === NS_MEDIA ? NS_FILE
: $index;
549 // Make sure to get the subject of our namespace
550 $index = $this->getSubject( $index );
552 // Some namespaces are special and should always be upper case
553 if ( in_array( $index, self
::ALWAYS_CAPITALIZED_NAMESPACES
) ) {
556 $overrides = $this->options
->get( MainConfigNames
::CapitalLinkOverrides
);
557 if ( isset( $overrides[$index] ) ) {
558 // CapitalLinkOverrides is explicitly set
559 return $overrides[$index];
561 // Default to the global setting
562 return $this->options
->get( MainConfigNames
::CapitalLinks
);
566 * Does the namespace (potentially) have different aliases for different
567 * genders. Not all languages make a distinction here.
569 * @param int $index Index to check
572 public function hasGenderDistinction( $index ) {
573 return $index == NS_USER ||
$index == NS_USER_TALK
;
577 * It is not possible to use pages from this namespace as template?
579 * @param int $index Index to check
582 public function isNonincludable( $index ) {
583 $namespaces = $this->options
->get( MainConfigNames
::NonincludableNamespaces
);
584 return $namespaces && in_array( $index, $namespaces );
588 * Get the default content model for a namespace
589 * This does not mean that all pages in that namespace have the model
591 * @note To determine the default model for a new page's main slot, or any slot in general,
592 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
594 * @param int $index Index to check
595 * @return null|string Default model name for the given namespace, if set
597 public function getNamespaceContentModel( $index ) {
598 return $this->options
->get( MainConfigNames
::NamespaceContentModels
)[$index] ??
null;
602 * Returns the link type to be used for categories.
604 * This determines which section of a category page titles
605 * in the namespace will appear within.
607 * @param int $index Namespace index
608 * @return string One of 'subcat', 'file', 'page'
610 public function getCategoryLinkType( $index ) {
611 $this->isMethodValidFor( $index, __METHOD__
);
613 if ( $index == NS_CATEGORY
) {
615 } elseif ( $index == NS_FILE
) {
623 * Retrieve the indexes for the namespaces defined by core.
629 public static function getCommonNamespaces() {
630 return array_keys( self
::CANONICAL_NAMES
);
634 /** @deprecated class alias since 1.41 */
635 class_alias( NamespaceInfo
::class, 'NamespaceInfo' );