Merge "Add .pipeline/ with dev image variant"
[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 use MediaWiki\MediaWikiServices;
26
27 /**
28 * This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of
29 * them based on index. The textual names of the namespaces are handled by Language.php.
30 *
31 * @since 1.34
32 */
33 class NamespaceInfo {
34
35 /**
36 * These namespaces should always be first-letter capitalized, now and
37 * forevermore. Historically, they could've probably been lowercased too,
38 * but some things are just too ingrained now. :)
39 */
40 private $alwaysCapitalizedNamespaces = [ NS_SPECIAL, NS_USER, NS_MEDIAWIKI ];
41
42 /** @var string[]|null Canonical namespaces cache */
43 private $canonicalNamespaces = null;
44
45 /** @var array|false Canonical namespaces index cache */
46 private $namespaceIndexes = false;
47
48 /** @var int[]|null Valid namespaces cache */
49 private $validNamespaces = null;
50
51 /** @var ServiceOptions */
52 private $options;
53
54 /**
55 * Definitions of the NS_ constants are in Defines.php
56 *
57 * @todo Make this const when HHVM support is dropped (T192166)
58 *
59 * @var array
60 * @internal
61 */
62 public static $canonicalNames = [
63 NS_MEDIA => 'Media',
64 NS_SPECIAL => 'Special',
65 NS_MAIN => '',
66 NS_TALK => 'Talk',
67 NS_USER => 'User',
68 NS_USER_TALK => 'User_talk',
69 NS_PROJECT => 'Project',
70 NS_PROJECT_TALK => 'Project_talk',
71 NS_FILE => 'File',
72 NS_FILE_TALK => 'File_talk',
73 NS_MEDIAWIKI => 'MediaWiki',
74 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
75 NS_TEMPLATE => 'Template',
76 NS_TEMPLATE_TALK => 'Template_talk',
77 NS_HELP => 'Help',
78 NS_HELP_TALK => 'Help_talk',
79 NS_CATEGORY => 'Category',
80 NS_CATEGORY_TALK => 'Category_talk',
81 ];
82
83 /**
84 * TODO Make this const when HHVM support is dropped (T192166)
85 *
86 * @since 1.34
87 * @var array
88 */
89 public static $constructorOptions = [
90 'AllowImageMoving',
91 'CanonicalNamespaceNames',
92 'CapitalLinkOverrides',
93 'CapitalLinks',
94 'ContentNamespaces',
95 'ExtraNamespaces',
96 'ExtraSignatureNamespaces',
97 'NamespaceContentModels',
98 'NamespacesWithSubpages',
99 'NonincludableNamespaces',
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 string[]
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 $this->validNamespaces = [];
401 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
402 if ( $ns >= 0 ) {
403 $this->validNamespaces[] = $ns;
404 }
405 }
406 // T109137: sort numerically
407 sort( $this->validNamespaces, SORT_NUMERIC );
408 }
409
410 return $this->validNamespaces;
411 }
412
413 /*
414
415 /**
416 * Does this namespace ever have a talk namespace?
417 *
418 * @param int $index Namespace ID
419 * @return bool True if this namespace either is or has a corresponding talk namespace.
420 */
421 public function hasTalkNamespace( $index ) {
422 return $index >= NS_MAIN;
423 }
424
425 /**
426 * Does this namespace contain content, for the purposes of calculating
427 * statistics, etc?
428 *
429 * @param int $index Index to check
430 * @return bool
431 */
432 public function isContent( $index ) {
433 return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
434 }
435
436 /**
437 * Might pages in this namespace require the use of the Signature button on
438 * the edit toolbar?
439 *
440 * @param int $index Index to check
441 * @return bool
442 */
443 public function wantSignatures( $index ) {
444 return $this->isTalk( $index ) ||
445 in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
446 }
447
448 /**
449 * Can pages in a namespace be watched?
450 *
451 * @param int $index
452 * @return bool
453 */
454 public function isWatchable( $index ) {
455 return $index >= NS_MAIN;
456 }
457
458 /**
459 * Does the namespace allow subpages?
460 *
461 * @param int $index Index to check
462 * @return bool
463 */
464 public function hasSubpages( $index ) {
465 return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
466 }
467
468 /**
469 * Get a list of all namespace indices which are considered to contain content
470 * @return array Array of namespace indices
471 */
472 public function getContentNamespaces() {
473 $contentNamespaces = $this->options->get( 'ContentNamespaces' );
474 if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
475 return [ NS_MAIN ];
476 } elseif ( !in_array( NS_MAIN, $contentNamespaces ) ) {
477 // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
478 return array_merge( [ NS_MAIN ], $contentNamespaces );
479 } else {
480 return $contentNamespaces;
481 }
482 }
483
484 /**
485 * List all namespace indices which are considered subject, aka not a talk
486 * or special namespace. See also NamespaceInfo::isSubject
487 *
488 * @return array Array of namespace indices
489 */
490 public function getSubjectNamespaces() {
491 return array_filter(
492 $this->getValidNamespaces(),
493 [ $this, 'isSubject' ]
494 );
495 }
496
497 /**
498 * List all namespace indices which are considered talks, aka not a subject
499 * or special namespace. See also NamespaceInfo::isTalk
500 *
501 * @return array Array of namespace indices
502 */
503 public function getTalkNamespaces() {
504 return array_filter(
505 $this->getValidNamespaces(),
506 [ $this, 'isTalk' ]
507 );
508 }
509
510 /**
511 * Is the namespace first-letter capitalized?
512 *
513 * @param int $index Index to check
514 * @return bool
515 */
516 public function isCapitalized( $index ) {
517 // Turn NS_MEDIA into NS_FILE
518 $index = $index === NS_MEDIA ? NS_FILE : $index;
519
520 // Make sure to get the subject of our namespace
521 $index = $this->getSubject( $index );
522
523 // Some namespaces are special and should always be upper case
524 if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
525 return true;
526 }
527 $overrides = $this->options->get( 'CapitalLinkOverrides' );
528 if ( isset( $overrides[$index] ) ) {
529 // CapitalLinkOverrides is explicitly set
530 return $overrides[$index];
531 }
532 // Default to the global setting
533 return $this->options->get( 'CapitalLinks' );
534 }
535
536 /**
537 * Does the namespace (potentially) have different aliases for different
538 * genders. Not all languages make a distinction here.
539 *
540 * @param int $index Index to check
541 * @return bool
542 */
543 public function hasGenderDistinction( $index ) {
544 return $index == NS_USER || $index == NS_USER_TALK;
545 }
546
547 /**
548 * It is not possible to use pages from this namespace as template?
549 *
550 * @param int $index Index to check
551 * @return bool
552 */
553 public function isNonincludable( $index ) {
554 $namespaces = $this->options->get( 'NonincludableNamespaces' );
555 return $namespaces && in_array( $index, $namespaces );
556 }
557
558 /**
559 * Get the default content model for a namespace
560 * This does not mean that all pages in that namespace have the model
561 *
562 * @note To determine the default model for a new page's main slot, or any slot in general,
563 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
564 *
565 * @param int $index Index to check
566 * @return null|string Default model name for the given namespace, if set
567 */
568 public function getNamespaceContentModel( $index ) {
569 return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
570 }
571
572 /**
573 * Determine which restriction levels it makes sense to use in a namespace,
574 * optionally filtered by a user's rights.
575 *
576 * @deprecated since 1.34 User PermissionManager::getNamespaceRestrictionLevels instead.
577 * @param int $index Index to check
578 * @param User|null $user User to check
579 * @return array
580 */
581 public function getRestrictionLevels( $index, User $user = null ) {
582 // PermissionManager is not injected because adding an explicit dependency
583 // breaks MW installer by adding a dependency chain on the database before
584 // it was set up. Also, the method is deprecated and will be soon removed.
585 return MediaWikiServices::getInstance()
586 ->getPermissionManager()
587 ->getNamespaceRestrictionLevels( $index, $user );
588 }
589
590 /**
591 * Returns the link type to be used for categories.
592 *
593 * This determines which section of a category page titles
594 * in the namespace will appear within.
595 *
596 * @param int $index Namespace index
597 * @return string One of 'subcat', 'file', 'page'
598 */
599 public function getCategoryLinkType( $index ) {
600 $this->isMethodValidFor( $index, __METHOD__ );
601
602 if ( $index == NS_CATEGORY ) {
603 return 'subcat';
604 } elseif ( $index == NS_FILE ) {
605 return 'file';
606 } else {
607 return 'page';
608 }
609 }
610
611 /**
612 * Retrieve the indexes for the namespaces defined by core.
613 *
614 * @since 1.34
615 *
616 * @return int[]
617 */
618 public static function getCommonNamespaces() {
619 return array_keys( self::$canonicalNames );
620 }
621 }