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
146 public function getTalk( $index ) {
147 $this->isMethodValidFor( $index, __METHOD__
);
148 return $this->isTalk( $index )
154 * @param LinkTarget $target
155 * @return LinkTarget Talk page for $target
156 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
158 public function getTalkPage( LinkTarget
$target ) : LinkTarget
{
159 if ( $this->isTalk( $target->getNamespace() ) ) {
162 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDbKey() );
166 * Get the subject namespace index for a given namespace
167 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
169 * @param int $index Namespace index
172 public function getSubject( $index ) {
173 # Handle special namespaces
174 if ( $index < NS_MAIN
) {
178 return $this->isTalk( $index )
184 * @param LinkTarget $target
185 * @return LinkTarget Subject page for $target
187 public function getSubjectPage( LinkTarget
$target ) : LinkTarget
{
188 if ( $this->isSubject( $target->getNamespace() ) ) {
191 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDbKey() );
195 * Get the associated namespace.
196 * For talk namespaces, returns the subject (non-talk) namespace
197 * For subject (non-talk) namespaces, returns the talk namespace
199 * @param int $index Namespace index
201 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
203 public function getAssociated( $index ) {
204 $this->isMethodValidFor( $index, __METHOD__
);
206 if ( $this->isSubject( $index ) ) {
207 return $this->getTalk( $index );
209 return $this->getSubject( $index );
213 * @param LinkTarget $target
214 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
216 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
218 public function getAssociatedPage( LinkTarget
$target ) : LinkTarget
{
219 return new TitleValue(
220 $this->getAssociated( $target->getNamespace() ), $target->getDbKey() );
224 * Returns whether the specified namespace exists
230 public function exists( $index ) {
231 $nslist = $this->getCanonicalNamespaces();
232 return isset( $nslist[$index] );
236 * Returns whether the specified namespaces are the same namespace
238 * @note It's possible that in the future we may start using something
239 * other than just namespace indexes. Under that circumstance making use
240 * of this function rather than directly doing comparison will make
241 * sure that code will not potentially break.
243 * @param int $ns1 The first namespace index
244 * @param int $ns2 The second namespace index
248 public function equals( $ns1, $ns2 ) {
253 * Returns whether the specified namespaces share the same subject.
254 * eg: NS_USER and NS_USER wil return true, as well
255 * NS_USER and NS_USER_TALK will return true.
257 * @param int $ns1 The first namespace index
258 * @param int $ns2 The second namespace index
262 public function subjectEquals( $ns1, $ns2 ) {
263 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
267 * Returns array of all defined namespaces with their canonical
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' );
281 Hooks
::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces
] );
283 return $this->canonicalNamespaces
;
287 * Returns the canonical (English) name for a given index
289 * @param int $index Namespace index
290 * @return string|bool If no canonical definition.
292 public function getCanonicalName( $index ) {
293 $nslist = $this->getCanonicalNamespaces();
294 return $nslist[$index] ??
false;
298 * Returns the index for a given canonical name, or NULL
299 * The input *must* be converted to lower case first
301 * @param string $name Namespace name
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;
311 if ( array_key_exists( $name, $this->namespaceIndexes
) ) {
312 return $this->namespaceIndexes
[$name];
319 * Returns an array of the namespaces (by integer id) that exist on the wiki. Used primarily by
320 * the API in help documentation. The array is sorted numerically and omits negative namespaces.
323 public function getValidNamespaces() {
324 if ( is_null( $this->validNamespaces
) ) {
325 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
327 $this->validNamespaces
[] = $ns;
330 // T109137: sort numerically
331 sort( $this->validNamespaces
, SORT_NUMERIC
);
334 return $this->validNamespaces
;
340 * Does this namespace ever have a talk namespace?
342 * @param int $index Namespace ID
343 * @return bool True if this namespace either is or has a corresponding talk namespace.
345 public function hasTalkNamespace( $index ) {
346 return $index >= NS_MAIN
;
350 * Does this namespace contain content, for the purposes of calculating
353 * @param int $index Index to check
356 public function isContent( $index ) {
357 return $index == NS_MAIN ||
in_array( $index, $this->options
->get( 'ContentNamespaces' ) );
361 * Might pages in this namespace require the use of the Signature button on
364 * @param int $index Index to check
367 public function wantSignatures( $index ) {
368 return $this->isTalk( $index ) ||
369 in_array( $index, $this->options
->get( 'ExtraSignatureNamespaces' ) );
373 * Can pages in a namespace be watched?
378 public function isWatchable( $index ) {
379 return $index >= NS_MAIN
;
383 * Does the namespace allow subpages?
385 * @param int $index Index to check
388 public function hasSubpages( $index ) {
389 return !empty( $this->options
->get( 'NamespacesWithSubpages' )[$index] );
393 * Get a list of all namespace indices which are considered to contain content
394 * @return array Array of namespace indices
396 public function getContentNamespaces() {
397 $contentNamespaces = $this->options
->get( 'ContentNamespaces' );
398 if ( !is_array( $contentNamespaces ) ||
$contentNamespaces === [] ) {
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 );
404 return $contentNamespaces;
409 * List all namespace indices which are considered subject, aka not a talk
410 * or special namespace. See also NamespaceInfo::isSubject
412 * @return array Array of namespace indices
414 public function getSubjectNamespaces() {
416 $this->getValidNamespaces(),
417 [ $this, 'isSubject' ]
422 * List all namespace indices which are considered talks, aka not a subject
423 * or special namespace. See also NamespaceInfo::isTalk
425 * @return array Array of namespace indices
427 public function getTalkNamespaces() {
429 $this->getValidNamespaces(),
435 * Is the namespace first-letter capitalized?
437 * @param int $index Index to check
440 public function isCapitalized( $index ) {
441 // Turn NS_MEDIA into NS_FILE
442 $index = $index === NS_MEDIA ? NS_FILE
: $index;
444 // Make sure to get the subject of our namespace
445 $index = $this->getSubject( $index );
447 // Some namespaces are special and should always be upper case
448 if ( in_array( $index, $this->alwaysCapitalizedNamespaces
) ) {
451 $overrides = $this->options
->get( 'CapitalLinkOverrides' );
452 if ( isset( $overrides[$index] ) ) {
453 // CapitalLinkOverrides is explicitly set
454 return $overrides[$index];
456 // Default to the global setting
457 return $this->options
->get( 'CapitalLinks' );
461 * Does the namespace (potentially) have different aliases for different
462 * genders. Not all languages make a distinction here.
464 * @param int $index Index to check
467 public function hasGenderDistinction( $index ) {
468 return $index == NS_USER ||
$index == NS_USER_TALK
;
472 * It is not possible to use pages from this namespace as template?
474 * @param int $index Index to check
477 public function isNonincludable( $index ) {
478 $namespaces = $this->options
->get( 'NonincludableNamespaces' );
479 return $namespaces && in_array( $index, $namespaces );
483 * Get the default content model for a namespace
484 * This does not mean that all pages in that namespace have the model
486 * @note To determine the default model for a new page's main slot, or any slot in general,
487 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
489 * @param int $index Index to check
490 * @return null|string Default model name for the given namespace, if set
492 public function getNamespaceContentModel( $index ) {
493 return $this->options
->get( 'NamespaceContentModels' )[$index] ??
null;
497 * Determine which restriction levels it makes sense to use in a namespace,
498 * optionally filtered by a user's rights.
500 * @todo Move this to PermissionManager and remove the dependency here on permissions-related
503 * @param int $index Index to check
504 * @param User|null $user User to check
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' );
513 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
515 if ( $right == 'sysop' ) {
516 $right = 'editprotected'; // BC
518 if ( $right == 'autoconfirmed' ) {
519 $right = 'editsemiprotected'; // BC
521 return ( $right == '' ||
$user->isAllowed( $right ) );
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.
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
540 if ( $right == 'autoconfirmed' ) {
541 $right = 'editsemiprotected'; // BC
543 if ( $right != '' ) {
544 $namespaceRightGroups[$right] = User
::getGroupsWithPermission( $right );
548 // Now, go through the protection levels one by one.
549 $usableLevels = [ '' ];
550 foreach ( $this->options
->get( 'RestrictionLevels' ) as $level ) {
552 if ( $right == 'sysop' ) {
553 $right = 'editprotected'; // BC
555 if ( $right == 'autoconfirmed' ) {
556 $right = 'editsemiprotected'; // BC
560 !isset( $namespaceRightGroups[$right] ) &&
561 ( !$user ||
$user->isAllowed( $right ) )
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.
570 // No, keep the restriction level
571 $usableLevels[] = $level;
575 return $usableLevels;
579 * Returns the link type to be used for categories.
581 * This determines which section of a category page titles
582 * in the namespace will appear within.
584 * @param int $index Namespace index
585 * @return string One of 'subcat', 'file', 'page'
587 public function getCategoryLinkType( $index ) {
588 $this->isMethodValidFor( $index, __METHOD__
);
590 if ( $index == NS_CATEGORY
) {
592 } elseif ( $index == NS_FILE
) {