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 * TODO Make this const when HHVM support is dropped (T192166)
59 public static $constructorOptions = [
61 'CanonicalNamespaceNames',
62 'CapitalLinkOverrides',
66 'ExtraSignatureNamespaces',
67 'NamespaceContentModels',
68 'NamespaceProtection',
69 'NamespacesWithSubpages',
70 'NonincludableNamespaces',
75 * @param ServiceOptions $options
77 public function __construct( ServiceOptions
$options ) {
78 $options->assertRequiredOptions( self
::$constructorOptions );
79 $this->options
= $options;
83 * Throw an exception when trying to get the subject or talk page
84 * for a given namespace where it does not make sense.
85 * Special namespaces are defined in includes/Defines.php and have
86 * a value below 0 (ex: NS_SPECIAL = -1 , NS_MEDIA = -2)
89 * @param string $method
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" );
102 * Can pages in the given namespace be moved?
104 * @param int $index Namespace index
107 public function isMovable( $index ) {
108 $result = $index >= NS_MAIN
&&
109 ( $index != NS_FILE ||
$this->options
->get( 'AllowImageMoving' ) );
114 Hooks
::run( 'NamespaceIsMovable', [ $index, &$result ] );
120 * Is the given namespace is a subject (non-talk) namespace?
122 * @param int $index Namespace index
125 public function isSubject( $index ) {
126 return !$this->isTalk( $index );
130 * Is the given namespace a talk namespace?
132 * @param int $index Namespace index
135 public function isTalk( $index ) {
136 return $index > NS_MAIN
141 * Get the talk namespace index for a given namespace
143 * @param int $index Namespace index
145 * @throws MWException if the given namespace doesn't have an associated talk namespace
148 public function getTalk( $index ) {
149 $this->isMethodValidFor( $index, __METHOD__
);
150 return $this->isTalk( $index )
156 * Get a LinkTarget referring to the talk page of $target.
158 * @see canHaveTalkPage
159 * @param LinkTarget $target
160 * @return LinkTarget Talk page for $target
161 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL,
162 * because it's a relative section-only link, or it's an an interwiki link.
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' );
169 if ( $target->getInterwiki() !== '' ) {
170 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
173 if ( $this->isTalk( $target->getNamespace() ) ) {
177 // NOTE: getTalk throws on bad namespaces!
178 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
182 * Can the title have a corresponding talk page?
184 * False for relative section-only links (with getText() === ''),
185 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
189 * @param LinkTarget $target
190 * @return bool True if this title either is a talk page or can have a talk page associated.
192 public function canHaveTalkPage( LinkTarget
$target ) {
193 if ( $target->getText() === '' ||
$target->getInterwiki() !== '' ) {
197 if ( $target->getNamespace() < NS_MAIN
) {
205 * Get the subject namespace index for a given namespace
206 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
208 * @param int $index Namespace index
211 public function getSubject( $index ) {
212 # Handle special namespaces
213 if ( $index < NS_MAIN
) {
217 return $this->isTalk( $index )
223 * @param LinkTarget $target
224 * @return LinkTarget Subject page for $target
226 public function getSubjectPage( LinkTarget
$target ) : LinkTarget
{
227 if ( $this->isSubject( $target->getNamespace() ) ) {
230 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
234 * Get the associated namespace.
235 * For talk namespaces, returns the subject (non-talk) namespace
236 * For subject (non-talk) namespaces, returns the talk namespace
238 * @param int $index Namespace index
240 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
242 public function getAssociated( $index ) {
243 $this->isMethodValidFor( $index, __METHOD__
);
245 if ( $this->isSubject( $index ) ) {
246 return $this->getTalk( $index );
248 return $this->getSubject( $index );
252 * @param LinkTarget $target
253 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
255 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
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' );
262 if ( $target->getInterwiki() !== '' ) {
263 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
266 return new TitleValue(
267 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
271 * Returns whether the specified namespace exists
277 public function exists( $index ) {
278 $nslist = $this->getCanonicalNamespaces();
279 return isset( $nslist[$index] );
283 * Returns whether the specified namespaces are the same namespace
285 * @note It's possible that in the future we may start using something
286 * other than just namespace indexes. Under that circumstance making use
287 * of this function rather than directly doing comparison will make
288 * sure that code will not potentially break.
290 * @param int $ns1 The first namespace index
291 * @param int $ns2 The second namespace index
295 public function equals( $ns1, $ns2 ) {
300 * Returns whether the specified namespaces share the same subject.
301 * eg: NS_USER and NS_USER wil return true, as well
302 * NS_USER and NS_USER_TALK will return true.
304 * @param int $ns1 The first namespace index
305 * @param int $ns2 The second namespace index
309 public function subjectEquals( $ns1, $ns2 ) {
310 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
314 * Returns array of all defined namespaces with their canonical
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' );
328 Hooks
::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces
] );
330 return $this->canonicalNamespaces
;
334 * Returns the canonical (English) name for a given index
336 * @param int $index Namespace index
337 * @return string|bool If no canonical definition.
339 public function getCanonicalName( $index ) {
340 $nslist = $this->getCanonicalNamespaces();
341 return $nslist[$index] ??
false;
345 * Returns the index for a given canonical name, or NULL
346 * The input *must* be converted to lower case first
348 * @param string $name Namespace name
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;
358 if ( array_key_exists( $name, $this->namespaceIndexes
) ) {
359 return $this->namespaceIndexes
[$name];
366 * Returns an array of the namespaces (by integer id) that exist on the wiki. Used primarily by
367 * the API in help documentation. The array is sorted numerically and omits negative namespaces.
370 public function getValidNamespaces() {
371 if ( is_null( $this->validNamespaces
) ) {
372 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
374 $this->validNamespaces
[] = $ns;
377 // T109137: sort numerically
378 sort( $this->validNamespaces
, SORT_NUMERIC
);
381 return $this->validNamespaces
;
387 * Does this namespace ever have a talk namespace?
389 * @param int $index Namespace ID
390 * @return bool True if this namespace either is or has a corresponding talk namespace.
392 public function hasTalkNamespace( $index ) {
393 return $index >= NS_MAIN
;
397 * Does this namespace contain content, for the purposes of calculating
400 * @param int $index Index to check
403 public function isContent( $index ) {
404 return $index == NS_MAIN ||
in_array( $index, $this->options
->get( 'ContentNamespaces' ) );
408 * Might pages in this namespace require the use of the Signature button on
411 * @param int $index Index to check
414 public function wantSignatures( $index ) {
415 return $this->isTalk( $index ) ||
416 in_array( $index, $this->options
->get( 'ExtraSignatureNamespaces' ) );
420 * Can pages in a namespace be watched?
425 public function isWatchable( $index ) {
426 return $index >= NS_MAIN
;
430 * Does the namespace allow subpages?
432 * @param int $index Index to check
435 public function hasSubpages( $index ) {
436 return !empty( $this->options
->get( 'NamespacesWithSubpages' )[$index] );
440 * Get a list of all namespace indices which are considered to contain content
441 * @return array Array of namespace indices
443 public function getContentNamespaces() {
444 $contentNamespaces = $this->options
->get( 'ContentNamespaces' );
445 if ( !is_array( $contentNamespaces ) ||
$contentNamespaces === [] ) {
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 );
451 return $contentNamespaces;
456 * List all namespace indices which are considered subject, aka not a talk
457 * or special namespace. See also NamespaceInfo::isSubject
459 * @return array Array of namespace indices
461 public function getSubjectNamespaces() {
463 $this->getValidNamespaces(),
464 [ $this, 'isSubject' ]
469 * List all namespace indices which are considered talks, aka not a subject
470 * or special namespace. See also NamespaceInfo::isTalk
472 * @return array Array of namespace indices
474 public function getTalkNamespaces() {
476 $this->getValidNamespaces(),
482 * Is the namespace first-letter capitalized?
484 * @param int $index Index to check
487 public function isCapitalized( $index ) {
488 // Turn NS_MEDIA into NS_FILE
489 $index = $index === NS_MEDIA ? NS_FILE
: $index;
491 // Make sure to get the subject of our namespace
492 $index = $this->getSubject( $index );
494 // Some namespaces are special and should always be upper case
495 if ( in_array( $index, $this->alwaysCapitalizedNamespaces
) ) {
498 $overrides = $this->options
->get( 'CapitalLinkOverrides' );
499 if ( isset( $overrides[$index] ) ) {
500 // CapitalLinkOverrides is explicitly set
501 return $overrides[$index];
503 // Default to the global setting
504 return $this->options
->get( 'CapitalLinks' );
508 * Does the namespace (potentially) have different aliases for different
509 * genders. Not all languages make a distinction here.
511 * @param int $index Index to check
514 public function hasGenderDistinction( $index ) {
515 return $index == NS_USER ||
$index == NS_USER_TALK
;
519 * It is not possible to use pages from this namespace as template?
521 * @param int $index Index to check
524 public function isNonincludable( $index ) {
525 $namespaces = $this->options
->get( 'NonincludableNamespaces' );
526 return $namespaces && in_array( $index, $namespaces );
530 * Get the default content model for a namespace
531 * This does not mean that all pages in that namespace have the model
533 * @note To determine the default model for a new page's main slot, or any slot in general,
534 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
536 * @param int $index Index to check
537 * @return null|string Default model name for the given namespace, if set
539 public function getNamespaceContentModel( $index ) {
540 return $this->options
->get( 'NamespaceContentModels' )[$index] ??
null;
544 * Determine which restriction levels it makes sense to use in a namespace,
545 * optionally filtered by a user's rights.
547 * @todo Move this to PermissionManager and remove the dependency here on permissions-related
550 * @param int $index Index to check
551 * @param User|null $user User to check
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' );
560 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
562 if ( $right == 'sysop' ) {
563 $right = 'editprotected'; // BC
565 if ( $right == 'autoconfirmed' ) {
566 $right = 'editsemiprotected'; // BC
568 return ( $right == '' ||
$user->isAllowed( $right ) );
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.
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
587 if ( $right == 'autoconfirmed' ) {
588 $right = 'editsemiprotected'; // BC
590 if ( $right != '' ) {
591 $namespaceRightGroups[$right] = User
::getGroupsWithPermission( $right );
595 // Now, go through the protection levels one by one.
596 $usableLevels = [ '' ];
597 foreach ( $this->options
->get( 'RestrictionLevels' ) as $level ) {
599 if ( $right == 'sysop' ) {
600 $right = 'editprotected'; // BC
602 if ( $right == 'autoconfirmed' ) {
603 $right = 'editsemiprotected'; // BC
607 !isset( $namespaceRightGroups[$right] ) &&
608 ( !$user ||
$user->isAllowed( $right ) )
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.
617 // No, keep the restriction level
618 $usableLevels[] = $level;
622 return $usableLevels;
626 * Returns the link type to be used for categories.
628 * This determines which section of a category page titles
629 * in the namespace will appear within.
631 * @param int $index Namespace index
632 * @return string One of 'subcat', 'file', 'page'
634 public function getCategoryLinkType( $index ) {
635 $this->isMethodValidFor( $index, __METHOD__
);
637 if ( $index == NS_CATEGORY
) {
639 } elseif ( $index == NS_FILE
) {