Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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 * TODO Make this const when HHVM support is dropped (T192166)
55 *
56 * @since 1.34
57 * @var array
58 */
59 public static $constructorOptions = [
60 'AllowImageMoving',
61 'CanonicalNamespaceNames',
62 'CapitalLinkOverrides',
63 'CapitalLinks',
64 'ContentNamespaces',
65 'ExtraNamespaces',
66 'ExtraSignatureNamespaces',
67 'NamespaceContentModels',
68 'NamespaceProtection',
69 'NamespacesWithSubpages',
70 'NonincludableNamespaces',
71 'RestrictionLevels',
72 ];
73
74 /**
75 * @param ServiceOptions $options
76 */
77 public function __construct( ServiceOptions $options ) {
78 $options->assertRequiredOptions( self::$constructorOptions );
79 $this->options = $options;
80 }
81
82 /**
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)
87 *
88 * @param int $index
89 * @param string $method
90 *
91 * @throws MWException
92 * @return bool
93 */
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" );
97 }
98 return true;
99 }
100
101 /**
102 * Can pages in the given namespace be moved?
103 *
104 * @param int $index Namespace index
105 * @return bool
106 */
107 public function isMovable( $index ) {
108 $result = $index >= NS_MAIN &&
109 ( $index != NS_FILE || $this->options->get( 'AllowImageMoving' ) );
110
111 /**
112 * @since 1.20
113 */
114 Hooks::run( 'NamespaceIsMovable', [ $index, &$result ] );
115
116 return $result;
117 }
118
119 /**
120 * Is the given namespace is a subject (non-talk) namespace?
121 *
122 * @param int $index Namespace index
123 * @return bool
124 */
125 public function isSubject( $index ) {
126 return !$this->isTalk( $index );
127 }
128
129 /**
130 * Is the given namespace a talk namespace?
131 *
132 * @param int $index Namespace index
133 * @return bool
134 */
135 public function isTalk( $index ) {
136 return $index > NS_MAIN
137 && $index % 2;
138 }
139
140 /**
141 * Get the talk namespace index for a given namespace
142 *
143 * @param int $index Namespace index
144 * @return int
145 * @throws MWException if the given namespace doesn't have an associated talk namespace
146 * (e.g. NS_SPECIAL).
147 */
148 public function getTalk( $index ) {
149 $this->isMethodValidFor( $index, __METHOD__ );
150 return $this->isTalk( $index )
151 ? $index
152 : $index + 1;
153 }
154
155 /**
156 * Get a LinkTarget referring to the talk page of $target.
157 *
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.
163 */
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' );
167 }
168
169 if ( $target->getInterwiki() !== '' ) {
170 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
171 }
172
173 if ( $this->isTalk( $target->getNamespace() ) ) {
174 return $target;
175 }
176
177 // NOTE: getTalk throws on bad namespaces!
178 return new TitleValue( $this->getTalk( $target->getNamespace() ), $target->getDBkey() );
179 }
180
181 /**
182 * Can the title have a corresponding talk page?
183 *
184 * False for relative section-only links (with getText() === ''),
185 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
186 *
187 * @see getTalkPage
188 *
189 * @param LinkTarget $target
190 * @return bool True if this title either is a talk page or can have a talk page associated.
191 */
192 public function canHaveTalkPage( LinkTarget $target ) {
193 if ( $target->getText() === '' || $target->getInterwiki() !== '' ) {
194 return false;
195 }
196
197 if ( $target->getNamespace() < NS_MAIN ) {
198 return false;
199 }
200
201 return true;
202 }
203
204 /**
205 * Get the subject namespace index for a given namespace
206 * Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
207 *
208 * @param int $index Namespace index
209 * @return int
210 */
211 public function getSubject( $index ) {
212 # Handle special namespaces
213 if ( $index < NS_MAIN ) {
214 return $index;
215 }
216
217 return $this->isTalk( $index )
218 ? $index - 1
219 : $index;
220 }
221
222 /**
223 * @param LinkTarget $target
224 * @return LinkTarget Subject page for $target
225 */
226 public function getSubjectPage( LinkTarget $target ) : LinkTarget {
227 if ( $this->isSubject( $target->getNamespace() ) ) {
228 return $target;
229 }
230 return new TitleValue( $this->getSubject( $target->getNamespace() ), $target->getDBkey() );
231 }
232
233 /**
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
237 *
238 * @param int $index Namespace index
239 * @return int
240 * @throws MWException if called on a namespace that has no talk pages (e.g., NS_SPECIAL)
241 */
242 public function getAssociated( $index ) {
243 $this->isMethodValidFor( $index, __METHOD__ );
244
245 if ( $this->isSubject( $index ) ) {
246 return $this->getTalk( $index );
247 }
248 return $this->getSubject( $index );
249 }
250
251 /**
252 * @param LinkTarget $target
253 * @return LinkTarget Talk page for $target if it's a subject page, subject page if it's a talk
254 * page
255 * @throws MWException if $target's namespace doesn't have talk pages (e.g., NS_SPECIAL)
256 */
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' );
260 }
261
262 if ( $target->getInterwiki() !== '' ) {
263 throw new MWException( 'Can\'t determine talk page associated with interwiki link' );
264 }
265
266 return new TitleValue(
267 $this->getAssociated( $target->getNamespace() ), $target->getDBkey() );
268 }
269
270 /**
271 * Returns whether the specified namespace exists
272 *
273 * @param int $index
274 *
275 * @return bool
276 */
277 public function exists( $index ) {
278 $nslist = $this->getCanonicalNamespaces();
279 return isset( $nslist[$index] );
280 }
281
282 /**
283 * Returns whether the specified namespaces are the same namespace
284 *
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.
289 *
290 * @param int $ns1 The first namespace index
291 * @param int $ns2 The second namespace index
292 *
293 * @return bool
294 */
295 public function equals( $ns1, $ns2 ) {
296 return $ns1 == $ns2;
297 }
298
299 /**
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.
303 *
304 * @param int $ns1 The first namespace index
305 * @param int $ns2 The second namespace index
306 *
307 * @return bool
308 */
309 public function subjectEquals( $ns1, $ns2 ) {
310 return $this->getSubject( $ns1 ) == $this->getSubject( $ns2 );
311 }
312
313 /**
314 * Returns array of all defined namespaces with their canonical
315 * (English) names.
316 *
317 * @return array
318 */
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' );
327 }
328 Hooks::run( 'CanonicalNamespaces', [ &$this->canonicalNamespaces ] );
329 }
330 return $this->canonicalNamespaces;
331 }
332
333 /**
334 * Returns the canonical (English) name for a given index
335 *
336 * @param int $index Namespace index
337 * @return string|bool If no canonical definition.
338 */
339 public function getCanonicalName( $index ) {
340 $nslist = $this->getCanonicalNamespaces();
341 return $nslist[$index] ?? false;
342 }
343
344 /**
345 * Returns the index for a given canonical name, or NULL
346 * The input *must* be converted to lower case first
347 *
348 * @param string $name Namespace name
349 * @return int|null
350 */
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;
356 }
357 }
358 if ( array_key_exists( $name, $this->namespaceIndexes ) ) {
359 return $this->namespaceIndexes[$name];
360 } else {
361 return null;
362 }
363 }
364
365 /**
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.
368 * @return array
369 */
370 public function getValidNamespaces() {
371 if ( is_null( $this->validNamespaces ) ) {
372 foreach ( array_keys( $this->getCanonicalNamespaces() ) as $ns ) {
373 if ( $ns >= 0 ) {
374 $this->validNamespaces[] = $ns;
375 }
376 }
377 // T109137: sort numerically
378 sort( $this->validNamespaces, SORT_NUMERIC );
379 }
380
381 return $this->validNamespaces;
382 }
383
384 /*
385
386 /**
387 * Does this namespace ever have a talk namespace?
388 *
389 * @param int $index Namespace ID
390 * @return bool True if this namespace either is or has a corresponding talk namespace.
391 */
392 public function hasTalkNamespace( $index ) {
393 return $index >= NS_MAIN;
394 }
395
396 /**
397 * Does this namespace contain content, for the purposes of calculating
398 * statistics, etc?
399 *
400 * @param int $index Index to check
401 * @return bool
402 */
403 public function isContent( $index ) {
404 return $index == NS_MAIN || in_array( $index, $this->options->get( 'ContentNamespaces' ) );
405 }
406
407 /**
408 * Might pages in this namespace require the use of the Signature button on
409 * the edit toolbar?
410 *
411 * @param int $index Index to check
412 * @return bool
413 */
414 public function wantSignatures( $index ) {
415 return $this->isTalk( $index ) ||
416 in_array( $index, $this->options->get( 'ExtraSignatureNamespaces' ) );
417 }
418
419 /**
420 * Can pages in a namespace be watched?
421 *
422 * @param int $index
423 * @return bool
424 */
425 public function isWatchable( $index ) {
426 return $index >= NS_MAIN;
427 }
428
429 /**
430 * Does the namespace allow subpages?
431 *
432 * @param int $index Index to check
433 * @return bool
434 */
435 public function hasSubpages( $index ) {
436 return !empty( $this->options->get( 'NamespacesWithSubpages' )[$index] );
437 }
438
439 /**
440 * Get a list of all namespace indices which are considered to contain content
441 * @return array Array of namespace indices
442 */
443 public function getContentNamespaces() {
444 $contentNamespaces = $this->options->get( 'ContentNamespaces' );
445 if ( !is_array( $contentNamespaces ) || $contentNamespaces === [] ) {
446 return [ NS_MAIN ];
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 );
450 } else {
451 return $contentNamespaces;
452 }
453 }
454
455 /**
456 * List all namespace indices which are considered subject, aka not a talk
457 * or special namespace. See also NamespaceInfo::isSubject
458 *
459 * @return array Array of namespace indices
460 */
461 public function getSubjectNamespaces() {
462 return array_filter(
463 $this->getValidNamespaces(),
464 [ $this, 'isSubject' ]
465 );
466 }
467
468 /**
469 * List all namespace indices which are considered talks, aka not a subject
470 * or special namespace. See also NamespaceInfo::isTalk
471 *
472 * @return array Array of namespace indices
473 */
474 public function getTalkNamespaces() {
475 return array_filter(
476 $this->getValidNamespaces(),
477 [ $this, 'isTalk' ]
478 );
479 }
480
481 /**
482 * Is the namespace first-letter capitalized?
483 *
484 * @param int $index Index to check
485 * @return bool
486 */
487 public function isCapitalized( $index ) {
488 // Turn NS_MEDIA into NS_FILE
489 $index = $index === NS_MEDIA ? NS_FILE : $index;
490
491 // Make sure to get the subject of our namespace
492 $index = $this->getSubject( $index );
493
494 // Some namespaces are special and should always be upper case
495 if ( in_array( $index, $this->alwaysCapitalizedNamespaces ) ) {
496 return true;
497 }
498 $overrides = $this->options->get( 'CapitalLinkOverrides' );
499 if ( isset( $overrides[$index] ) ) {
500 // CapitalLinkOverrides is explicitly set
501 return $overrides[$index];
502 }
503 // Default to the global setting
504 return $this->options->get( 'CapitalLinks' );
505 }
506
507 /**
508 * Does the namespace (potentially) have different aliases for different
509 * genders. Not all languages make a distinction here.
510 *
511 * @param int $index Index to check
512 * @return bool
513 */
514 public function hasGenderDistinction( $index ) {
515 return $index == NS_USER || $index == NS_USER_TALK;
516 }
517
518 /**
519 * It is not possible to use pages from this namespace as template?
520 *
521 * @param int $index Index to check
522 * @return bool
523 */
524 public function isNonincludable( $index ) {
525 $namespaces = $this->options->get( 'NonincludableNamespaces' );
526 return $namespaces && in_array( $index, $namespaces );
527 }
528
529 /**
530 * Get the default content model for a namespace
531 * This does not mean that all pages in that namespace have the model
532 *
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().
535 *
536 * @param int $index Index to check
537 * @return null|string Default model name for the given namespace, if set
538 */
539 public function getNamespaceContentModel( $index ) {
540 return $this->options->get( 'NamespaceContentModels' )[$index] ?? null;
541 }
542
543 /**
544 * Determine which restriction levels it makes sense to use in a namespace,
545 * optionally filtered by a user's rights.
546 *
547 * @todo Move this to PermissionManager and remove the dependency here on permissions-related
548 * config settings.
549 *
550 * @param int $index Index to check
551 * @param User|null $user User to check
552 * @return array
553 */
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' );
559 if ( $user ) {
560 $levels = array_values( array_filter( $levels, function ( $level ) use ( $user ) {
561 $right = $level;
562 if ( $right == 'sysop' ) {
563 $right = 'editprotected'; // BC
564 }
565 if ( $right == 'autoconfirmed' ) {
566 $right = 'editsemiprotected'; // BC
567 }
568 return ( $right == '' || $user->isAllowed( $right ) );
569 } ) );
570 }
571 return $levels;
572 }
573
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.
580 //
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
586 }
587 if ( $right == 'autoconfirmed' ) {
588 $right = 'editsemiprotected'; // BC
589 }
590 if ( $right != '' ) {
591 $namespaceRightGroups[$right] = User::getGroupsWithPermission( $right );
592 }
593 }
594
595 // Now, go through the protection levels one by one.
596 $usableLevels = [ '' ];
597 foreach ( $this->options->get( 'RestrictionLevels' ) as $level ) {
598 $right = $level;
599 if ( $right == 'sysop' ) {
600 $right = 'editprotected'; // BC
601 }
602 if ( $right == 'autoconfirmed' ) {
603 $right = 'editsemiprotected'; // BC
604 }
605
606 if ( $right != '' &&
607 !isset( $namespaceRightGroups[$right] ) &&
608 ( !$user || $user->isAllowed( $right ) )
609 ) {
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.
614 continue 2;
615 }
616 }
617 // No, keep the restriction level
618 $usableLevels[] = $level;
619 }
620 }
621
622 return $usableLevels;
623 }
624
625 /**
626 * Returns the link type to be used for categories.
627 *
628 * This determines which section of a category page titles
629 * in the namespace will appear within.
630 *
631 * @param int $index Namespace index
632 * @return string One of 'subcat', 'file', 'page'
633 */
634 public function getCategoryLinkType( $index ) {
635 $this->isMethodValidFor( $index, __METHOD__ );
636
637 if ( $index == NS_CATEGORY ) {
638 return 'subcat';
639 } elseif ( $index == NS_FILE ) {
640 return 'file';
641 } else {
642 return 'page';
643 }
644 }
645 }