Merge "Fix call to non-existing TempFSFileFactory::getTempFSFile()"
[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_TALK => 'Talk',
66 NS_USER => 'User',
67 NS_USER_TALK => 'User_talk',
68 NS_PROJECT => 'Project',
69 NS_PROJECT_TALK => 'Project_talk',
70 NS_FILE => 'File',
71 NS_FILE_TALK => 'File_talk',
72 NS_MEDIAWIKI => 'MediaWiki',
73 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
74 NS_TEMPLATE => 'Template',
75 NS_TEMPLATE_TALK => 'Template_talk',
76 NS_HELP => 'Help',
77 NS_HELP_TALK => 'Help_talk',
78 NS_CATEGORY => 'Category',
79 NS_CATEGORY_TALK => 'Category_talk',
80 ];
81
82 /**
83 * TODO Make this const when HHVM support is dropped (T192166)
84 *
85 * @since 1.34
86 * @var array
87 */
88 public static $constructorOptions = [
89 'AllowImageMoving',
90 'CanonicalNamespaceNames',
91 'CapitalLinkOverrides',
92 'CapitalLinks',
93 'ContentNamespaces',
94 'ExtraNamespaces',
95 'ExtraSignatureNamespaces',
96 'NamespaceContentModels',
97 'NamespacesWithSubpages',
98 'NonincludableNamespaces',
99 ];
100
101 /**
102 * @param ServiceOptions $options
103 */
104 public function __construct( ServiceOptions $options ) {
105 $options->assertRequiredOptions( self::$constructorOptions );
106 $this->options = $options;
107 }
108
109 /**
110 * Throw an exception when trying to get the subject or talk page
111 * for a given namespace where it does not make sense.
112 * Special namespaces are defined in includes/Defines.php and have
113 * a value below 0 (ex: NS_SPECIAL = -1 , NS_MEDIA = -2)
114 *
115 * @param int $index
116 * @param string $method
117 *
118 * @throws MWException
119 * @return bool
120 */
121 private function isMethodValidFor( $index, $method ) {
122 if ( $index < NS_MAIN ) {
123 throw new MWException( "$method does not make any sense for given namespace $index" );
124 }
125 return true;
126 }
127
128 /**
129 * Can pages in the given namespace be moved?
130 *
131 * @param int $index Namespace index
132 * @return bool
133 */
134 public function isMovable( $index ) {
135 $result = $index >= NS_MAIN &&
136 ( $index != NS_FILE || $this->options->get( 'AllowImageMoving' ) );
137
138 /**
139 * @since 1.20
140 */
141 Hooks::run( 'NamespaceIsMovable', [ $index, &$result ] );
142
143 return $result;
144 }
145
146 /**
147 * Is the given namespace is a subject (non-talk) namespace?
148 *
149 * @param int $index Namespace index
150 * @return bool
151 */
152 public function isSubject( $index ) {
153 return !$this->isTalk( $index );
154 }
155
156 /**
157 * Is the given namespace a talk namespace?
158 *
159 * @param int $index Namespace index
160 * @return bool
161 */
162 public function isTalk( $index ) {
163 return $index > NS_MAIN
164 && $index % 2;
165 }
166
167 /**
168 * Get the talk namespace index for a given namespace
169 *
170 * @param int $index Namespace index
171 * @return int
172 * @throws MWException if the given namespace doesn't have an associated talk namespace
173 * (e.g. NS_SPECIAL).
174 */
175 public function getTalk( $index ) {
176 $this->isMethodValidFor( $index, __METHOD__ );
177 return $this->isTalk( $index )
178 ? $index
179 : $index + 1;
180 }
181
182 /**
183 * Get a LinkTarget referring to the talk page of $target.
184 *
185 * @see canHaveTalkPage
186 * @param LinkTarget $target
187 * @return LinkTarget Talk page for $target
188 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL,
189 * because it's a relative section-only link, or it's an an interwiki link.
190 */
191 public function getTalkPage( LinkTarget $target ) : LinkTarget {
192 if ( $target->getText() === '' ) {
193 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
194 }
195
196 if ( $target->getInterwiki() !== '' ) {
197 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
198 }
199
200 if ( $this->isTalk( $target->getNamespace() ) ) {
201 return $target;
202 }
203
204 // NOTE: getTalk throws on bad namespaces!
205 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
206 }
207
208 /**
209 * Can the title have a corresponding talk page?
210 *
211 * False for relative section-only links (with getText() === ''),
212 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
213 *
214 * @see getTalkPage
215 *
216 * @param LinkTarget $target
217 * @return bool True if this title either is a talk page or can have a talk page associated.
218 */
219 public function canHaveTalkPage( LinkTarget $target ) {
220 if ( $target->getText() === '' || $target->getInterwiki() !== '' ) {
221 return false;
222 }
223
224 if ( $target->getNamespace() < NS_MAIN ) {
225 return false;
226 }
227
228 return true;
229 }
230
231 /**
232 * Get the subject namespace index for a given namespace
233 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
234 *
235 * @param int $index Namespace index
236 * @return int
237 */
238 public function getSubject( $index ) {
239 # Handle special namespaces
240 if ( $index < NS_MAIN ) {
241 return $index;
242 }
243
244 return $this->isTalk( $index )
245 ? $index - 1
246 : $index;
247 }
248
249 /**
250 * @param LinkTarget $target
251 * @return LinkTarget Subject page for $target
252 */
253 public function getSubjectPage( LinkTarget $target ) : LinkTarget {
254 if ( $this->isSubject( $target->getNamespace() ) ) {
255 return $target;
256 }
257 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
258 }
259
260 /**
261 * Get the associated namespace.
262 * For talk namespaces, returns the subject (non-talk) namespace
263 * For subject (non-talk) namespaces, returns the talk namespace
264 *
265 * @param int $index Namespace index
266 * @return int
267 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
268 */
269 public function getAssociated( $index ) {
270 $this->isMethodValidFor( $index, __METHOD__ );
271
272 if ( $this->isSubject( $index ) ) {
273 return $this->getTalk( $index );
274 }
275 return $this->getSubject( $index );
276 }
277
278 /**
279 * @param LinkTarget $target
280 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
281 * page
282 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
283 */
284 public function getAssociatedPage( LinkTarget $target ) : LinkTarget {
285 if ( $target->getText() === '' ) {
286 throw new MWException( 'Can\'t determine talk page associated with relative section link' );
287 }
288
289 if ( $target->getInterwiki() !== '' ) {
290 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
291 }
292
293 return new TitleValue(
294 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
295 }
296
297 /**
298 * Returns whether the specified namespace exists
299 *
300 * @param int $index
301 *
302 * @return bool
303 */
304 public function exists( $index ) {
305 $nslist = $this->getCanonicalNamespaces();
306 return isset( $nslist[$index] );
307 }
308
309 /**
310 * Returns whether the specified namespaces are the same namespace
311 *
312 * @note It's possible that in the future we may start using something
313 * other than just namespace indexes. Under that circumstance making use
314 * of this function rather than directly doing comparison will make
315 * sure that code will not potentially break.
316 *
317 * @param int $ns1 The first namespace index
318 * @param int $ns2 The second namespace index
319 *
320 * @return bool
321 */
322 public function equals( $ns1, $ns2 ) {
323 return $ns1 == $ns2;
324 }
325
326 /**
327 * Returns whether the specified namespaces share the same subject.
328 * eg: NS_USER and NS_USER wil return true, as well
329 * NS_USER and NS_USER_TALK will return true.
330 *
331 * @param int $ns1 The first namespace index
332 * @param int $ns2 The second namespace index
333 *
334 * @return bool
335 */
336 public function subjectEquals( $ns1, $ns2 ) {
337 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
338 }
339
340 /**
341 * Returns array of all defined namespaces with their canonical
342 * (English) names.
343 *
344 * @return array
345 */
346 public function getCanonicalNamespaces() {
347 if ( $this->canonicalNamespaces === null ) {
348 $this->canonicalNamespaces =
349 [ NS_MAIN => '' ] + $this->options->get( 'CanonicalNamespaceNames' );
350 $this->canonicalNamespaces +=
351 ExtensionRegistry::getInstance()->getAttribute( 'ExtensionNamespaces' );
352 if ( is_array( $this->options->get( 'ExtraNamespaces' ) ) ) {
353 $this->canonicalNamespaces += $this->options->get( 'ExtraNamespaces' );
354 }
355 Hooks::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces ] );
356 }
357 return $this->canonicalNamespaces;
358 }
359
360 /**
361 * Returns the canonical (English) name for a given index
362 *
363 * @param int $index Namespace index
364 * @return string|bool If no canonical definition.
365 */
366 public function getCanonicalName( $index ) {
367 $nslist = $this->getCanonicalNamespaces();
368 return $nslist[$index] ?? false;
369 }
370
371 /**
372 * Returns the index for a given canonical name, or NULL
373 * The input *must* be converted to lower case first
374 *
375 * @param string $name Namespace name
376 * @return int|null
377 */
378 public function getCanonicalIndex( $name ) {
379 if ( $this->namespaceIndexes === false ) {
380 $this->namespaceIndexes = [];
381 foreach ( $this->getCanonicalNamespaces() as $i => $text ) {
382 $this->namespaceIndexes[strtolower( $text )] = $i;
383 }
384 }
385 if ( array_key_exists( $name, $this->namespaceIndexes ) ) {
386 return $this->namespaceIndexes[$name];
387 } else {
388 return null;
389 }
390 }
391
392 /**
393 * Returns an array of the namespaces (by integer id) that exist on the wiki. Used primarily by
394 * the API in help documentation. The array is sorted numerically and omits negative namespaces.
395 * @return array
396 */
397 public function getValidNamespaces() {
398 if ( is_null( $this->validNamespaces ) ) {
399 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
400 if ( $ns >= 0 ) {
401 $this->validNamespaces[] = $ns;
402 }
403 }
404 // T109137: sort numerically
405 sort( $this->validNamespaces, SORT_NUMERIC );
406 }
407
408 return $this->validNamespaces;
409 }
410
411 /*
412
413 /**
414 * Does this namespace ever have a talk namespace?
415 *
416 * @param int $index Namespace ID
417 * @return bool True if this namespace either is or has a corresponding talk namespace.
418 */
419 public function hasTalkNamespace( $index ) {
420 return $index >= NS_MAIN;
421 }
422
423 /**
424 * Does this namespace contain content, for the purposes of calculating
425 * statistics, etc?
426 *
427 * @param int $index Index to check
428 * @return bool
429 */
430 public function isContent( $index ) {
431 return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
432 }
433
434 /**
435 * Might pages in this namespace require the use of the Signature button on
436 * the edit toolbar?
437 *
438 * @param int $index Index to check
439 * @return bool
440 */
441 public function wantSignatures( $index ) {
442 return $this->isTalk( $index ) ||
443 in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
444 }
445
446 /**
447 * Can pages in a namespace be watched?
448 *
449 * @param int $index
450 * @return bool
451 */
452 public function isWatchable( $index ) {
453 return $index >= NS_MAIN;
454 }
455
456 /**
457 * Does the namespace allow subpages?
458 *
459 * @param int $index Index to check
460 * @return bool
461 */
462 public function hasSubpages( $index ) {
463 return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
464 }
465
466 /**
467 * Get a list of all namespace indices which are considered to contain content
468 * @return array Array of namespace indices
469 */
470 public function getContentNamespaces() {
471 $contentNamespaces = $this->options->get( 'ContentNamespaces' );
472 if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
473 return [ NS_MAIN ];
474 } elseif ( !in_array( NS_MAIN, $contentNamespaces ) ) {
475 // always force NS_MAIN to be part of array (to match the algorithm used by isContent)
476 return array_merge( [ NS_MAIN ], $contentNamespaces );
477 } else {
478 return $contentNamespaces;
479 }
480 }
481
482 /**
483 * List all namespace indices which are considered subject, aka not a talk
484 * or special namespace. See also NamespaceInfo::isSubject
485 *
486 * @return array Array of namespace indices
487 */
488 public function getSubjectNamespaces() {
489 return array_filter(
490 $this->getValidNamespaces(),
491 [ $this, 'isSubject' ]
492 );
493 }
494
495 /**
496 * List all namespace indices which are considered talks, aka not a subject
497 * or special namespace. See also NamespaceInfo::isTalk
498 *
499 * @return array Array of namespace indices
500 */
501 public function getTalkNamespaces() {
502 return array_filter(
503 $this->getValidNamespaces(),
504 [ $this, 'isTalk' ]
505 );
506 }
507
508 /**
509 * Is the namespace first-letter capitalized?
510 *
511 * @param int $index Index to check
512 * @return bool
513 */
514 public function isCapitalized( $index ) {
515 // Turn NS_MEDIA into NS_FILE
516 $index = $index === NS_MEDIA ? NS_FILE : $index;
517
518 // Make sure to get the subject of our namespace
519 $index = $this->getSubject( $index );
520
521 // Some namespaces are special and should always be upper case
522 if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
523 return true;
524 }
525 $overrides = $this->options->get( 'CapitalLinkOverrides' );
526 if ( isset( $overrides[$index] ) ) {
527 // CapitalLinkOverrides is explicitly set
528 return $overrides[$index];
529 }
530 // Default to the global setting
531 return $this->options->get( 'CapitalLinks' );
532 }
533
534 /**
535 * Does the namespace (potentially) have different aliases for different
536 * genders. Not all languages make a distinction here.
537 *
538 * @param int $index Index to check
539 * @return bool
540 */
541 public function hasGenderDistinction( $index ) {
542 return $index == NS_USER || $index == NS_USER_TALK;
543 }
544
545 /**
546 * It is not possible to use pages from this namespace as template?
547 *
548 * @param int $index Index to check
549 * @return bool
550 */
551 public function isNonincludable( $index ) {
552 $namespaces = $this->options->get( 'NonincludableNamespaces' );
553 return $namespaces && in_array( $index, $namespaces );
554 }
555
556 /**
557 * Get the default content model for a namespace
558 * This does not mean that all pages in that namespace have the model
559 *
560 * @note To determine the default model for a new page's main slot, or any slot in general,
561 * use SlotRoleHandler::getDefaultModel() together with SlotRoleRegistry::getRoleHandler().
562 *
563 * @param int $index Index to check
564 * @return null|string Default model name for the given namespace, if set
565 */
566 public function getNamespaceContentModel( $index ) {
567 return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
568 }
569
570 /**
571 * Determine which restriction levels it makes sense to use in a namespace,
572 * optionally filtered by a user's rights.
573 *
574 * @deprecated since 1.34 User PermissionManager::getNamespaceRestrictionLevels instead.
575 * @param int $index Index to check
576 * @param User|null $user User to check
577 * @return array
578 */
579 public function getRestrictionLevels( $index, User $user = null ) {
580 // PermissionManager is not injected because adding an explicit dependency
581 // breaks MW installer by adding a dependency chain on the database before
582 // it was set up. Also, the method is deprecated and will be soon removed.
583 return MediaWikiServices::getInstance()
584 ->getPermissionManager()
585 ->getNamespaceRestrictionLevels( $index, $user );
586 }
587
588 /**
589 * Returns the link type to be used for categories.
590 *
591 * This determines which section of a category page titles
592 * in the namespace will appear within.
593 *
594 * @param int $index Namespace index
595 * @return string One of 'subcat', 'file', 'page'
596 */
597 public function getCategoryLinkType( $index ) {
598 $this->isMethodValidFor( $index, __METHOD__ );
599
600 if ( $index == NS_CATEGORY ) {
601 return 'subcat';
602 } elseif ( $index == NS_FILE ) {
603 return 'file';
604 } else {
605 return 'page';
606 }
607 }
608
609 /**
610 * Retrieve the indexes for the namespaces defined by core.
611 *
612 * @since 1.34
613 *
614 * @return int[]
615 */
616 public static function getCommonNamespaces() {
617 return array_keys( self::$canonicalNames );
618 }
619 }