Merge "Inject LoadBalancer into GenderCache"
[lhc/web/wiklou.git] / includes / title / NamespaceInfo.php
1 <?php
2 /**
3 * Provide things related to namespaces.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use MediaWiki\Config\ServiceOptions;
24 use MediaWiki\Linker\LinkTarget;
25
26 /**
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.
29 *
30 * @since 1.34
31 */
32 class NamespaceInfo {
33
34 /**
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. :)
38 */
39 private $alwaysCapitalizedNamespaces = [ NS_SPECIAL, NS_USER, NS_MEDIAWIKI ];
40
41 /** @var string[]|null Canonical namespaces cache */
42 private $canonicalNamespaces = null;
43
44 /** @var array|false Canonical namespaces index cache */
45 private $namespaceIndexes = false;
46
47 /** @var int[]|null Valid namespaces cache */
48 private $validNamespaces = null;
49
50 /** @var ServiceOptions */
51 private $options;
52
53 /**
54 * Definitions of the NS_ constants are in Defines.php
55 *
56 * @todo Make this const when HHVM support is dropped (T192166)
57 *
58 * @var array
59 * @internal
60 */
61 public static $canonicalNames = [
62 NS_MEDIA => 'Media',
63 NS_SPECIAL => 'Special',
64 NS_TALK => 'Talk',
65 NS_USER => 'User',
66 NS_USER_TALK => 'User_talk',
67 NS_PROJECT => 'Project',
68 NS_PROJECT_TALK => 'Project_talk',
69 NS_FILE => 'File',
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',
75 NS_HELP => 'Help',
76 NS_HELP_TALK => 'Help_talk',
77 NS_CATEGORY => 'Category',
78 NS_CATEGORY_TALK => 'Category_talk',
79 ];
80
81 /**
82 * TODO Make this const when HHVM support is dropped (T192166)
83 *
84 * @since 1.34
85 * @var array
86 */
87 public static $constructorOptions = [
88 'AllowImageMoving',
89 'CanonicalNamespaceNames',
90 'CapitalLinkOverrides',
91 'CapitalLinks',
92 'ContentNamespaces',
93 'ExtraNamespaces',
94 'ExtraSignatureNamespaces',
95 'NamespaceContentModels',
96 'NamespaceProtection',
97 'NamespacesWithSubpages',
98 'NonincludableNamespaces',
99 'RestrictionLevels',
100 ];
101
102 /**
103 * @param ServiceOptions $options
104 */
105 public function __construct( ServiceOptions $options ) {
106 $options->assertRequiredOptions( self::$constructorOptions );
107 $this->options = $options;
108 }
109
110 /**
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)
115 *
116 * @param int $index
117 * @param string $method
118 *
119 * @throws MWException
120 * @return bool
121 */
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" );
125 }
126 return true;
127 }
128
129 /**
130 * Can pages in the given namespace be moved?
131 *
132 * @param int $index Namespace index
133 * @return bool
134 */
135 public function isMovable( $index ) {
136 $result = $index >= NS_MAIN &&
137 ( $index != NS_FILE || $this->options->get( 'AllowImageMoving' ) );
138
139 /**
140 * @since 1.20
141 */
142 Hooks::run( 'NamespaceIsMovable', [ $index, &$result ] );
143
144 return $result;
145 }
146
147 /**
148 * Is the given namespace is a subject (non-talk) namespace?
149 *
150 * @param int $index Namespace index
151 * @return bool
152 */
153 public function isSubject( $index ) {
154 return !$this->isTalk( $index );
155 }
156
157 /**
158 * Is the given namespace a talk namespace?
159 *
160 * @param int $index Namespace index
161 * @return bool
162 */
163 public function isTalk( $index ) {
164 return $index > NS_MAIN
165 && $index % 2;
166 }
167
168 /**
169 * Get the talk namespace index for a given namespace
170 *
171 * @param int $index Namespace index
172 * @return int
173 * @throws MWException if the given namespace doesn't have an associated talk namespace
174 * (e.g. NS_SPECIAL).
175 */
176 public function getTalk( $index ) {
177 $this->isMethodValidFor( $index, __METHOD__ );
178 return $this->isTalk( $index )
179 ? $index
180 : $index + 1;
181 }
182
183 /**
184 * Get a LinkTarget referring to the talk page of $target.
185 *
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.
191 */
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' );
195 }
196
197 if ( $target->getInterwiki() !== '' ) {
198 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
199 }
200
201 if ( $this->isTalk( $target->getNamespace() ) ) {
202 return $target;
203 }
204
205 // NOTE: getTalk throws on bad namespaces!
206 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
207 }
208
209 /**
210 * Can the title have a corresponding talk page?
211 *
212 * False for relative section-only links (with getText() === ''),
213 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
214 *
215 * @see getTalkPage
216 *
217 * @param LinkTarget $target
218 * @return bool True if this title either is a talk page or can have a talk page associated.
219 */
220 public function canHaveTalkPage( LinkTarget $target ) {
221 if ( $target->getText() === '' || $target->getInterwiki() !== '' ) {
222 return false;
223 }
224
225 if ( $target->getNamespace() < NS_MAIN ) {
226 return false;
227 }
228
229 return true;
230 }
231
232 /**
233 * Get the subject namespace index for a given namespace
234 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
235 *
236 * @param int $index Namespace index
237 * @return int
238 */
239 public function getSubject( $index ) {
240 # Handle special namespaces
241 if ( $index < NS_MAIN ) {
242 return $index;
243 }
244
245 return $this->isTalk( $index )
246 ? $index - 1
247 : $index;
248 }
249
250 /**
251 * @param LinkTarget $target
252 * @return LinkTarget Subject page for $target
253 */
254 public function getSubjectPage( LinkTarget $target ) : LinkTarget {
255 if ( $this->isSubject( $target->getNamespace() ) ) {
256 return $target;
257 }
258 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
259 }
260
261 /**
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
265 *
266 * @param int $index Namespace index
267 * @return int
268 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
269 */
270 public function getAssociated( $index ) {
271 $this->isMethodValidFor( $index, __METHOD__ );
272
273 if ( $this->isSubject( $index ) ) {
274 return $this->getTalk( $index );
275 }
276 return $this->getSubject( $index );
277 }
278
279 /**
280 * @param LinkTarget $target
281 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
282 * page
283 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
284 */
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' );
288 }
289
290 if ( $target->getInterwiki() !== '' ) {
291 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
292 }
293
294 return new TitleValue(
295 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
296 }
297
298 /**
299 * Returns whether the specified namespace exists
300 *
301 * @param int $index
302 *
303 * @return bool
304 */
305 public function exists( $index ) {
306 $nslist = $this->getCanonicalNamespaces();
307 return isset( $nslist[$index] );
308 }
309
310 /**
311 * Returns whether the specified namespaces are the same namespace
312 *
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.
317 *
318 * @param int $ns1 The first namespace index
319 * @param int $ns2 The second namespace index
320 *
321 * @return bool
322 */
323 public function equals( $ns1, $ns2 ) {
324 return $ns1 == $ns2;
325 }
326
327 /**
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.
331 *
332 * @param int $ns1 The first namespace index
333 * @param int $ns2 The second namespace index
334 *
335 * @return bool
336 */
337 public function subjectEquals( $ns1, $ns2 ) {
338 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
339 }
340
341 /**
342 * Returns array of all defined namespaces with their canonical
343 * (English) names.
344 *
345 * @return array
346 */
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' );
355 }
356 Hooks::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces ] );
357 }
358 return $this->canonicalNamespaces;
359 }
360
361 /**
362 * Returns the canonical (English) name for a given index
363 *
364 * @param int $index Namespace index
365 * @return string|bool If no canonical definition.
366 */
367 public function getCanonicalName( $index ) {
368 $nslist = $this->getCanonicalNamespaces();
369 return $nslist[$index] ?? false;
370 }
371
372 /**
373 * Returns the index for a given canonical name, or NULL
374 * The input *must* be converted to lower case first
375 *
376 * @param string $name Namespace name
377 * @return int|null
378 */
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;
384 }
385 }
386 if ( array_key_exists( $name, $this->namespaceIndexes ) ) {
387 return $this->namespaceIndexes[$name];
388 } else {
389 return null;
390 }
391 }
392
393 /**
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.
396 * @return array
397 */
398 public function getValidNamespaces() {
399 if ( is_null( $this->validNamespaces ) ) {
400 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
401 if ( $ns >= 0 ) {
402 $this->validNamespaces[] = $ns;
403 }
404 }
405 // T109137: sort numerically
406 sort( $this->validNamespaces, SORT_NUMERIC );
407 }
408
409 return $this->validNamespaces;
410 }
411
412 /*
413
414 /**
415 * Does this namespace ever have a talk namespace?
416 *
417 * @param int $index Namespace ID
418 * @return bool True if this namespace either is or has a corresponding talk namespace.
419 */
420 public function hasTalkNamespace( $index ) {
421 return $index >= NS_MAIN;
422 }
423
424 /**
425 * Does this namespace contain content, for the purposes of calculating
426 * statistics, etc?
427 *
428 * @param int $index Index to check
429 * @return bool
430 */
431 public function isContent( $index ) {
432 return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
433 }
434
435 /**
436 * Might pages in this namespace require the use of the Signature button on
437 * the edit toolbar?
438 *
439 * @param int $index Index to check
440 * @return bool
441 */
442 public function wantSignatures( $index ) {
443 return $this->isTalk( $index ) ||
444 in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
445 }
446
447 /**
448 * Can pages in a namespace be watched?
449 *
450 * @param int $index
451 * @return bool
452 */
453 public function isWatchable( $index ) {
454 return $index >= NS_MAIN;
455 }
456
457 /**
458 * Does the namespace allow subpages?
459 *
460 * @param int $index Index to check
461 * @return bool
462 */
463 public function hasSubpages( $index ) {
464 return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
465 }
466
467 /**
468 * Get a list of all namespace indices which are considered to contain content
469 * @return array Array of namespace indices
470 */
471 public function getContentNamespaces() {
472 $contentNamespaces = $this->options->get( 'ContentNamespaces' );
473 if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
474 return [ NS_MAIN ];
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 );
478 } else {
479 return $contentNamespaces;
480 }
481 }
482
483 /**
484 * List all namespace indices which are considered subject, aka not a talk
485 * or special namespace. See also NamespaceInfo::isSubject
486 *
487 * @return array Array of namespace indices
488 */
489 public function getSubjectNamespaces() {
490 return array_filter(
491 $this->getValidNamespaces(),
492 [ $this, 'isSubject' ]
493 );
494 }
495
496 /**
497 * List all namespace indices which are considered talks, aka not a subject
498 * or special namespace. See also NamespaceInfo::isTalk
499 *
500 * @return array Array of namespace indices
501 */
502 public function getTalkNamespaces() {
503 return array_filter(
504 $this->getValidNamespaces(),
505 [ $this, 'isTalk' ]
506 );
507 }
508
509 /**
510 * Is the namespace first-letter capitalized?
511 *
512 * @param int $index Index to check
513 * @return bool
514 */
515 public function isCapitalized( $index ) {
516 // Turn NS_MEDIA into NS_FILE
517 $index = $index === NS_MEDIA ? NS_FILE : $index;
518
519 // Make sure to get the subject of our namespace
520 $index = $this->getSubject( $index );
521
522 // Some namespaces are special and should always be upper case
523 if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
524 return true;
525 }
526 $overrides = $this->options->get( 'CapitalLinkOverrides' );
527 if ( isset( $overrides[$index] ) ) {
528 // CapitalLinkOverrides is explicitly set
529 return $overrides[$index];
530 }
531 // Default to the global setting
532 return $this->options->get( 'CapitalLinks' );
533 }
534
535 /**
536 * Does the namespace (potentially) have different aliases for different
537 * genders. Not all languages make a distinction here.
538 *
539 * @param int $index Index to check
540 * @return bool
541 */
542 public function hasGenderDistinction( $index ) {
543 return $index == NS_USER || $index == NS_USER_TALK;
544 }
545
546 /**
547 * It is not possible to use pages from this namespace as template?
548 *
549 * @param int $index Index to check
550 * @return bool
551 */
552 public function isNonincludable( $index ) {
553 $namespaces = $this->options->get( 'NonincludableNamespaces' );
554 return $namespaces && in_array( $index, $namespaces );
555 }
556
557 /**
558 * Get the default content model for a namespace
559 * This does not mean that all pages in that namespace have the model
560 *
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().
563 *
564 * @param int $index Index to check
565 * @return null|string Default model name for the given namespace, if set
566 */
567 public function getNamespaceContentModel( $index ) {
568 return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
569 }
570
571 /**
572 * Determine which restriction levels it makes sense to use in a namespace,
573 * optionally filtered by a user's rights.
574 *
575 * @todo Move this to PermissionManager and remove the dependency here on permissions-related
576 * config settings.
577 *
578 * @param int $index Index to check
579 * @param User|null $user User to check
580 * @return array
581 */
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' );
587 if ( $user ) {
588 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
589 $right = $level;
590 if ( $right == 'sysop' ) {
591 $right = 'editprotected'; // BC
592 }
593 if ( $right == 'autoconfirmed' ) {
594 $right = 'editsemiprotected'; // BC
595 }
596 return ( $right == '' || $user->isAllowed( $right ) );
597 } ) );
598 }
599 return $levels;
600 }
601
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.
608 //
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
614 }
615 if ( $right == 'autoconfirmed' ) {
616 $right = 'editsemiprotected'; // BC
617 }
618 if ( $right != '' ) {
619 $namespaceRightGroups[$right] = User::getGroupsWithPermission( $right );
620 }
621 }
622
623 // Now, go through the protection levels one by one.
624 $usableLevels = [ '' ];
625 foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
626 $right = $level;
627 if ( $right == 'sysop' ) {
628 $right = 'editprotected'; // BC
629 }
630 if ( $right == 'autoconfirmed' ) {
631 $right = 'editsemiprotected'; // BC
632 }
633
634 if ( $right != '' &&
635 !isset( $namespaceRightGroups[$right] ) &&
636 ( !$user || $user->isAllowed( $right ) )
637 ) {
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.
642 continue 2;
643 }
644 }
645 // No, keep the restriction level
646 $usableLevels[] = $level;
647 }
648 }
649
650 return $usableLevels;
651 }
652
653 /**
654 * Returns the link type to be used for categories.
655 *
656 * This determines which section of a category page titles
657 * in the namespace will appear within.
658 *
659 * @param int $index Namespace index
660 * @return string One of 'subcat', 'file', 'page'
661 */
662 public function getCategoryLinkType( $index ) {
663 $this->isMethodValidFor( $index, __METHOD__ );
664
665 if ( $index == NS_CATEGORY ) {
666 return 'subcat';
667 } elseif ( $index == NS_FILE ) {
668 return 'file';
669 } else {
670 return 'page';
671 }
672 }
673
674 /**
675 * Retrieve the indexes for the namespaces defined by core.
676 *
677 * @since 1.34
678 *
679 * @return int[]
680 */
681 public static function getCommonNamespaces() {
682 return array_keys( self::$canonicalNames );
683 }
684 }