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 use MediaWiki\Config\ServiceOptions
;
24 use MediaWiki\Linker\LinkTarget
;
27 * This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of
28 * them based on index. The textual names of the namespaces are handled by Language.php.
35 * These namespaces should always be first-letter capitalized, now and
36 * forevermore. Historically, they could've probably been lowercased too,
37 * but some things are just too ingrained now. :)
39 private $alwaysCapitalizedNamespaces = [ NS_SPECIAL
, NS_USER
, NS_MEDIAWIKI
];
41 /** @var string[]|null Canonical namespaces cache */
42 private $canonicalNamespaces = null;
44 /** @var array|false Canonical namespaces index cache */
45 private $namespaceIndexes = false;
47 /** @var int[]|null Valid namespaces cache */
48 private $validNamespaces = null;
50 /** @var ServiceOptions */
54 * Definitions of the NS_ constants are in Defines.php
56 * @todo Make this const when HHVM support is dropped (T192166)
61 public static $canonicalNames = [
63 NS_SPECIAL
=> 'Special',
66 NS_USER_TALK
=> 'User_talk',
67 NS_PROJECT
=> 'Project',
68 NS_PROJECT_TALK
=> 'Project_talk',
70 NS_FILE_TALK
=> 'File_talk',
71 NS_MEDIAWIKI
=> 'MediaWiki',
72 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
73 NS_TEMPLATE
=> 'Template',
74 NS_TEMPLATE_TALK
=> 'Template_talk',
76 NS_HELP_TALK
=> 'Help_talk',
77 NS_CATEGORY
=> 'Category',
78 NS_CATEGORY_TALK
=> 'Category_talk',
82 * TODO Make this const when HHVM support is dropped (T192166)
87 public static $constructorOptions = [
89 'CanonicalNamespaceNames',
90 'CapitalLinkOverrides',
94 'ExtraSignatureNamespaces',
95 'NamespaceContentModels',
96 'NamespaceProtection',
97 'NamespacesWithSubpages',
98 'NonincludableNamespaces',
103 * @param ServiceOptions $options
105 public function __construct( ServiceOptions
$options ) {
106 $options->assertRequiredOptions( self
::$constructorOptions );
107 $this->options
= $options;
111 * Throw an exception when trying to get the subject or talk page
112 * for a given namespace where it does not make sense.
113 * Special namespaces are defined in includes/Defines.php and have
114 * a value below 0 (ex: NS_SPECIAL = -1 , NS_MEDIA = -2)
117 * @param string $method
119 * @throws MWException
122 private function isMethodValidFor( $index, $method ) {
123 if ( $index < NS_MAIN
) {
124 throw new MWException( "$method does not make any sense for given namespace $index" );
130 * Can pages in the given namespace be moved?
132 * @param int $index Namespace index
135 public function isMovable( $index ) {
136 $result = $index >= NS_MAIN
&&
137 ( $index != NS_FILE ||
$this->options
->get( 'AllowImageMoving' ) );
142 Hooks
::run( 'NamespaceIsMovable', [ $index, &$result ] );
148 * Is the given namespace is a subject (non-talk) namespace?
150 * @param int $index Namespace index
153 public function isSubject( $index ) {
154 return !$this->isTalk( $index );
158 * Is the given namespace a talk namespace?
160 * @param int $index Namespace index
163 public function isTalk( $index ) {
164 return $index > NS_MAIN
169 * Get the talk namespace index for a given namespace
171 * @param int $index Namespace index
173 * @throws MWException if the given namespace doesn't have an associated talk namespace
176 public function getTalk( $index ) {
177 $this->isMethodValidFor( $index, __METHOD__
);
178 return $this->isTalk( $index )
184 * Get a LinkTarget referring to the talk page of $target.
186 * @see canHaveTalkPage
187 * @param LinkTarget $target
188 * @return LinkTarget Talk page for $target
189 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL,
190 * because it's a relative section-only link, or it's an an interwiki link.
192 public function getTalkPage( LinkTarget
$target ) : LinkTarget
{
193 if ( $target->getText() === '' ) {
194 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
197 if ( $target->getInterwiki() !== '' ) {
198 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
201 if ( $this->isTalk( $target->getNamespace() ) ) {
205 // NOTE: getTalk throws on bad namespaces!
206 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
210 * Can the title have a corresponding talk page?
212 * False for relative section-only links (with getText() === ''),
213 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
217 * @param LinkTarget $target
218 * @return bool True if this title either is a talk page or can have a talk page associated.
220 public function canHaveTalkPage( LinkTarget
$target ) {
221 if ( $target->getText() === '' ||
$target->getInterwiki() !== '' ) {
225 if ( $target->getNamespace() < NS_MAIN
) {
233 * Get the subject namespace index for a given namespace
234 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
236 * @param int $index Namespace index
239 public function getSubject( $index ) {
240 # Handle special namespaces
241 if ( $index < NS_MAIN
) {
245 return $this->isTalk( $index )
251 * @param LinkTarget $target
252 * @return LinkTarget Subject page for $target
254 public function getSubjectPage( LinkTarget
$target ) : LinkTarget
{
255 if ( $this->isSubject( $target->getNamespace() ) ) {
258 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
262 * Get the associated namespace.
263 * For talk namespaces, returns the subject (non-talk) namespace
264 * For subject (non-talk) namespaces, returns the talk namespace
266 * @param int $index Namespace index
268 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
270 public function getAssociated( $index ) {
271 $this->isMethodValidFor( $index, __METHOD__
);
273 if ( $this->isSubject( $index ) ) {
274 return $this->getTalk( $index );
276 return $this->getSubject( $index );
280 * @param LinkTarget $target
281 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
283 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
285 public function getAssociatedPage( LinkTarget
$target ) : LinkTarget
{
286 if ( $target->getText() === '' ) {
287 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
290 if ( $target->getInterwiki() !== '' ) {
291 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
294 return new TitleValue(
295 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
299 * Returns whether the specified namespace exists
305 public function exists( $index ) {
306 $nslist = $this->getCanonicalNamespaces();
307 return isset( $nslist[$index] );
311 * Returns whether the specified namespaces are the same namespace
313 * @note It's possible that in the future we may start using something
314 * other than just namespace indexes. Under that circumstance making use
315 * of this function rather than directly doing comparison will make
316 * sure that code will not potentially break.
318 * @param int $ns1 The first namespace index
319 * @param int $ns2 The second namespace index
323 public function equals( $ns1, $ns2 ) {
328 * Returns whether the specified namespaces share the same subject.
329 * eg: NS_USER and NS_USER wil return true, as well
330 * NS_USER and NS_USER_TALK will return true.
332 * @param int $ns1 The first namespace index
333 * @param int $ns2 The second namespace index
337 public function subjectEquals( $ns1, $ns2 ) {
338 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
342 * Returns array of all defined namespaces with their canonical
347 public function getCanonicalNamespaces() {
348 if ( $this->canonicalNamespaces
=== null ) {
349 $this->canonicalNamespaces
=
350 [ NS_MAIN
=> '' ] +
$this->options
->get( 'CanonicalNamespaceNames' );
351 $this->canonicalNamespaces +
=
352 ExtensionRegistry
::getInstance()->getAttribute( 'ExtensionNamespaces' );
353 if ( is_array( $this->options
->get( 'ExtraNamespaces' ) ) ) {
354 $this->canonicalNamespaces +
= $this->options
->get( 'ExtraNamespaces' );
356 Hooks
::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces
] );
358 return $this->canonicalNamespaces
;
362 * Returns the canonical (English) name for a given index
364 * @param int $index Namespace index
365 * @return string|bool If no canonical definition.
367 public function getCanonicalName( $index ) {
368 $nslist = $this->getCanonicalNamespaces();
369 return $nslist[$index] ??
false;
373 * Returns the index for a given canonical name, or NULL
374 * The input *must* be converted to lower case first
376 * @param string $name Namespace name
379 public function getCanonicalIndex( $name ) {
380 if ( $this->namespaceIndexes
=== false ) {
381 $this->namespaceIndexes
= [];
382 foreach ( $this->getCanonicalNamespaces() as $i => $text ) {
383 $this->namespaceIndexes
[strtolower( $text )] = $i;
386 if ( array_key_exists( $name, $this->namespaceIndexes
) ) {
387 return $this->namespaceIndexes
[$name];
394 * Returns an array of the namespaces (by integer id) that exist on the wiki. Used primarily by
395 * the API in help documentation. The array is sorted numerically and omits negative namespaces.
398 public function getValidNamespaces() {
399 if ( is_null( $this->validNamespaces
) ) {
400 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
402 $this->validNamespaces
[] = $ns;
405 // T109137: sort numerically
406 sort( $this->validNamespaces
, SORT_NUMERIC
);
409 return $this->validNamespaces
;
415 * Does this namespace ever have a talk namespace?
417 * @param int $index Namespace ID
418 * @return bool True if this namespace either is or has a corresponding talk namespace.
420 public function hasTalkNamespace( $index ) {
421 return $index >= NS_MAIN
;
425 * Does this namespace contain content, for the purposes of calculating
428 * @param int $index Index to check
431 public function isContent( $index ) {
432 return $index == NS_MAIN ||
in_array( $index, $this->options
->get( 'ContentNamespaces' ) );
436 * Might pages in this namespace require the use of the Signature button on
439 * @param int $index Index to check
442 public function wantSignatures( $index ) {
443 return $this->isTalk( $index ) ||
444 in_array( $index, $this->options
->get( 'ExtraSignatureNamespaces' ) );
448 * Can pages in a namespace be watched?
453 public function isWatchable( $index ) {
454 return $index >= NS_MAIN
;
458 * Does the namespace allow subpages?
460 * @param int $index Index to check
463 public function hasSubpages( $index ) {
464 return !empty( $this->options
->get( 'NamespacesWithSubpages' )[$index] );
468 * Get a list of all namespace indices which are considered to contain content
469 * @return array Array of namespace indices
471 public function getContentNamespaces() {
472 $contentNamespaces = $this->options
->get( 'ContentNamespaces' );
473 if ( !is_array( $contentNamespaces ) ||
$contentNamespaces === [] ) {
475 } elseif ( !in_array( NS_MAIN
, $contentNamespaces ) ) {
476 // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
477 return array_merge( [ NS_MAIN
], $contentNamespaces );
479 return $contentNamespaces;
484 * List all namespace indices which are considered subject, aka not a talk
485 * or special namespace. See also NamespaceInfo::isSubject
487 * @return array Array of namespace indices
489 public function getSubjectNamespaces() {
491 $this->getValidNamespaces(),
492 [ $this, 'isSubject' ]
497 * List all namespace indices which are considered talks, aka not a subject
498 * or special namespace. See also NamespaceInfo::isTalk
500 * @return array Array of namespace indices
502 public function getTalkNamespaces() {
504 $this->getValidNamespaces(),
510 * Is the namespace first-letter capitalized?
512 * @param int $index Index to check
515 public function isCapitalized( $index ) {
516 // Turn NS_MEDIA into NS_FILE
517 $index = $index === NS_MEDIA ? NS_FILE
: $index;
519 // Make sure to get the subject of our namespace
520 $index = $this->getSubject( $index );
522 // Some namespaces are special and should always be upper case
523 if ( in_array( $index, $this->alwaysCapitalizedNamespaces
) ) {
526 $overrides = $this->options
->get( 'CapitalLinkOverrides' );
527 if ( isset( $overrides[$index] ) ) {
528 // CapitalLinkOverrides is explicitly set
529 return $overrides[$index];
531 // Default to the global setting
532 return $this->options
->get( 'CapitalLinks' );
536 * Does the namespace (potentially) have different aliases for different
537 * genders. Not all languages make a distinction here.
539 * @param int $index Index to check
542 public function hasGenderDistinction( $index ) {
543 return $index == NS_USER ||
$index == NS_USER_TALK
;
547 * It is not possible to use pages from this namespace as template?
549 * @param int $index Index to check
552 public function isNonincludable( $index ) {
553 $namespaces = $this->options
->get( 'NonincludableNamespaces' );
554 return $namespaces && in_array( $index, $namespaces );
558 * Get the default content model for a namespace
559 * This does not mean that all pages in that namespace have the model
561 * @note To determine the default model for a new page's main slot, or any slot in general,
562 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
564 * @param int $index Index to check
565 * @return null|string Default model name for the given namespace, if set
567 public function getNamespaceContentModel( $index ) {
568 return $this->options
->get( 'NamespaceContentModels' )[$index] ??
null;
572 * Determine which restriction levels it makes sense to use in a namespace,
573 * optionally filtered by a user's rights.
575 * @todo Move this to PermissionManager and remove the dependency here on permissions-related
578 * @param int $index Index to check
579 * @param User|null $user User to check
582 public function getRestrictionLevels( $index, User
$user = null ) {
583 if ( !isset( $this->options
->get( 'NamespaceProtection' )[$index] ) ) {
584 // All levels are valid if there's no namespace restriction.
585 // But still filter by user, if necessary
586 $levels = $this->options
->get( 'RestrictionLevels' );
588 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
590 if ( $right == 'sysop' ) {
591 $right = 'editprotected'; // BC
593 if ( $right == 'autoconfirmed' ) {
594 $right = 'editsemiprotected'; // BC
596 return ( $right == '' ||
$user->isAllowed( $right ) );
602 // $wgNamespaceProtection can require one or more rights to edit the namespace, which
603 // may be satisfied by membership in multiple groups each giving a subset of those rights.
604 // A restriction level is redundant if, for any one of the namespace rights, all groups
605 // giving that right also give the restriction level's right. Or, conversely, a
606 // restriction level is not redundant if, for every namespace right, there's at least one
607 // group giving that right without the restriction level's right.
609 // First, for each right, get a list of groups with that right.
610 $namespaceRightGroups = [];
611 foreach ( (array)$this->options
->get( 'NamespaceProtection' )[$index] as $right ) {
612 if ( $right == 'sysop' ) {
613 $right = 'editprotected'; // BC
615 if ( $right == 'autoconfirmed' ) {
616 $right = 'editsemiprotected'; // BC
618 if ( $right != '' ) {
619 $namespaceRightGroups[$right] = User
::getGroupsWithPermission( $right );
623 // Now, go through the protection levels one by one.
624 $usableLevels = [ '' ];
625 foreach ( $this->options
->get( 'RestrictionLevels' ) as $level ) {
627 if ( $right == 'sysop' ) {
628 $right = 'editprotected'; // BC
630 if ( $right == 'autoconfirmed' ) {
631 $right = 'editsemiprotected'; // BC
635 !isset( $namespaceRightGroups[$right] ) &&
636 ( !$user ||
$user->isAllowed( $right ) )
638 // Do any of the namespace rights imply the restriction right? (see explanation above)
639 foreach ( $namespaceRightGroups as $groups ) {
640 if ( !array_diff( $groups, User
::getGroupsWithPermission( $right ) ) ) {
641 // Yes, this one does.
645 // No, keep the restriction level
646 $usableLevels[] = $level;
650 return $usableLevels;
654 * Returns the link type to be used for categories.
656 * This determines which section of a category page titles
657 * in the namespace will appear within.
659 * @param int $index Namespace index
660 * @return string One of 'subcat', 'file', 'page'
662 public function getCategoryLinkType( $index ) {
663 $this->isMethodValidFor( $index, __METHOD__
);
665 if ( $index == NS_CATEGORY
) {
667 } elseif ( $index == NS_FILE
) {
675 * Retrieve the indexes for the namespaces defined by core.
681 public static function getCommonNamespaces() {
682 return array_keys( self
::$canonicalNames );