Special case opus mime detction
[mediawiki.git] / includes / title / MediaWikiTitleCodec.php
blob7a71714bca08de9605b9c6297aed54dca86a3ada
1 <?php
2 /**
3 * A codec for %MediaWiki page titles.
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
20 * @file
21 * @license GPL 2+
22 * @author Daniel Kinzler
24 use MediaWiki\Interwiki\InterwikiLookup;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Linker\LinkTarget;
28 /**
29 * A codec for %MediaWiki page titles.
31 * @note Normalization and validation is applied while parsing, not when formatting.
32 * It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
33 * to generate an (invalid) title string from it. TitleValues should be constructed only
34 * via parseTitle() or from a (semi)trusted source, such as the database.
36 * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
37 * @since 1.23
39 class MediaWikiTitleCodec implements TitleFormatter, TitleParser {
40 /**
41 * @var Language
43 protected $language;
45 /**
46 * @var GenderCache
48 protected $genderCache;
50 /**
51 * @var string[]
53 protected $localInterwikis;
55 /**
56 * @var InterwikiLookup
58 protected $interwikiLookup;
60 /**
61 * @param Language $language The language object to use for localizing namespace names.
62 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
63 * @param string[]|string $localInterwikis
64 * @param InterwikiLookup|null $interwikiLookup
66 public function __construct( Language $language, GenderCache $genderCache,
67 $localInterwikis = [], $interwikiLookup = null
68 ) {
69 $this->language = $language;
70 $this->genderCache = $genderCache;
71 $this->localInterwikis = (array)$localInterwikis;
72 $this->interwikiLookup = $interwikiLookup ?:
73 MediaWikiServices::getInstance()->getInterwikiLookup();
76 /**
77 * @see TitleFormatter::getNamespaceName()
79 * @param int $namespace
80 * @param string $text
82 * @throws InvalidArgumentException If the namespace is invalid
83 * @return string
85 public function getNamespaceName( $namespace, $text ) {
86 if ( $this->language->needsGenderDistinction() &&
87 MWNamespace::hasGenderDistinction( $namespace )
88 ) {
90 // NOTE: we are assuming here that the title text is a user name!
91 $gender = $this->genderCache->getGenderOf( $text, __METHOD__ );
92 $name = $this->language->getGenderNsText( $namespace, $gender );
93 } else {
94 $name = $this->language->getNsText( $namespace );
97 if ( $name === false ) {
98 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
101 return $name;
105 * @see TitleFormatter::formatTitle()
107 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
108 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
109 * Underscores will be replaced.
110 * @param string $fragment The fragment name (may be empty).
111 * @param string $interwiki The interwiki name (may be empty).
113 * @throws InvalidArgumentException If the namespace is invalid
114 * @return string
116 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
117 if ( $namespace !== false ) {
118 // Try to get a namespace name, but fallback
119 // to empty string if it doesn't exist
120 try {
121 $nsName = $this->getNamespaceName( $namespace, $text );
122 } catch ( InvalidArgumentException $e ) {
123 $nsName = '';
126 if ( $namespace !== 0 ) {
127 $text = $nsName . ':' . $text;
131 if ( $fragment !== '' ) {
132 $text = $text . '#' . $fragment;
135 if ( $interwiki !== '' ) {
136 $text = $interwiki . ':' . $text;
139 $text = str_replace( '_', ' ', $text );
141 return $text;
145 * Parses the given text and constructs a TitleValue. Normalization
146 * is applied according to the rules appropriate for the form specified by $form.
148 * @param string $text The text to parse
149 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
151 * @throws MalformedTitleException
152 * @return TitleValue
154 public function parseTitle( $text, $defaultNamespace ) {
155 // NOTE: this is an ugly cludge that allows this class to share the
156 // code for parsing with the old Title class. The parser code should
157 // be refactored to avoid this.
158 $parts = $this->splitTitleString( $text, $defaultNamespace );
160 // Relative fragment links are not supported by TitleValue
161 if ( $parts['dbkey'] === '' ) {
162 throw new MalformedTitleException( 'title-invalid-empty', $text );
165 return new TitleValue(
166 $parts['namespace'],
167 $parts['dbkey'],
168 $parts['fragment'],
169 $parts['interwiki']
174 * @see TitleFormatter::getText()
176 * @param LinkTarget $title
178 * @return string $title->getText()
180 public function getText( LinkTarget $title ) {
181 return $this->formatTitle( false, $title->getText(), '' );
185 * @see TitleFormatter::getText()
187 * @param LinkTarget $title
189 * @return string
191 public function getPrefixedText( LinkTarget $title ) {
192 return $this->formatTitle(
193 $title->getNamespace(),
194 $title->getText(),
196 $title->getInterwiki()
201 * @since 1.27
202 * @see TitleFormatter::getPrefixedDBkey()
203 * @param LinkTarget $target
204 * @return string
206 public function getPrefixedDBkey( LinkTarget $target ) {
207 $key = '';
208 if ( $target->isExternal() ) {
209 $key .= $target->getInterwiki() . ':';
211 // Try to get a namespace name, but fallback
212 // to empty string if it doesn't exist
213 try {
214 $nsName = $this->getNamespaceName(
215 $target->getNamespace(),
216 $target->getText()
218 } catch ( InvalidArgumentException $e ) {
219 $nsName = '';
222 if ( $target->getNamespace() !== 0 ) {
223 $key .= $nsName . ':';
226 $key .= $target->getText();
228 return strtr( $key, ' ', '_' );
232 * @see TitleFormatter::getText()
234 * @param LinkTarget $title
236 * @return string
238 public function getFullText( LinkTarget $title ) {
239 return $this->formatTitle(
240 $title->getNamespace(),
241 $title->getText(),
242 $title->getFragment(),
243 $title->getInterwiki()
248 * Normalizes and splits a title string.
250 * This function removes illegal characters, splits off the interwiki and
251 * namespace prefixes, sets the other forms, and canonicalizes
252 * everything.
254 * @todo this method is only exposed as a temporary measure to ease refactoring.
255 * It was copied with minimal changes from Title::secureAndSplit().
257 * @todo This method should be split up and an appropriate interface
258 * defined for use by the Title class.
260 * @param string $text
261 * @param int $defaultNamespace
263 * @throws MalformedTitleException If $text is not a valid title string.
264 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
265 * 'user_case_dbkey', and 'dbkey'.
267 public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
268 $dbkey = str_replace( ' ', '_', $text );
270 # Initialisation
271 $parts = [
272 'interwiki' => '',
273 'local_interwiki' => false,
274 'fragment' => '',
275 'namespace' => $defaultNamespace,
276 'dbkey' => $dbkey,
277 'user_case_dbkey' => $dbkey,
280 # Strip Unicode bidi override characters.
281 # Sometimes they slip into cut-n-pasted page titles, where the
282 # override chars get included in list displays.
283 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
285 # Clean up whitespace
286 # Note: use of the /u option on preg_replace here will cause
287 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
288 # conveniently disabling them.
289 $dbkey = preg_replace(
290 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
291 '_',
292 $dbkey
294 $dbkey = trim( $dbkey, '_' );
296 if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
297 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
298 throw new MalformedTitleException( 'title-invalid-utf8', $text );
301 $parts['dbkey'] = $dbkey;
303 # Initial colon indicates main namespace rather than specified default
304 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
305 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
306 $parts['namespace'] = NS_MAIN;
307 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
308 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
311 if ( $dbkey == '' ) {
312 throw new MalformedTitleException( 'title-invalid-empty', $text );
315 # Namespace or interwiki prefix
316 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
317 do {
318 $m = [];
319 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
320 $p = $m[1];
321 $ns = $this->language->getNsIndex( $p );
322 if ( $ns !== false ) {
323 # Ordinary namespace
324 $dbkey = $m[2];
325 $parts['namespace'] = $ns;
326 # For Talk:X pages, check if X has a "namespace" prefix
327 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
328 if ( $this->language->getNsIndex( $x[1] ) ) {
329 # Disallow Talk:File:x type titles...
330 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
331 } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
332 // TODO: get rid of global state!
333 # Disallow Talk:Interwiki:x type titles...
334 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
337 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
338 # Interwiki link
339 $dbkey = $m[2];
340 $parts['interwiki'] = $this->language->lc( $p );
342 # Redundant interwiki prefix to the local wiki
343 foreach ( $this->localInterwikis as $localIW ) {
344 if ( 0 == strcasecmp( $parts['interwiki'], $localIW ) ) {
345 if ( $dbkey == '' ) {
346 # Empty self-links should point to the Main Page, to ensure
347 # compatibility with cross-wiki transclusions and the like.
348 $mainPage = Title::newMainPage();
349 return [
350 'interwiki' => $mainPage->getInterwiki(),
351 'local_interwiki' => true,
352 'fragment' => $mainPage->getFragment(),
353 'namespace' => $mainPage->getNamespace(),
354 'dbkey' => $mainPage->getDBkey(),
355 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
358 $parts['interwiki'] = '';
359 # local interwikis should behave like initial-colon links
360 $parts['local_interwiki'] = true;
362 # Do another namespace split...
363 continue 2;
367 # If there's an initial colon after the interwiki, that also
368 # resets the default namespace
369 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
370 $parts['namespace'] = NS_MAIN;
371 $dbkey = substr( $dbkey, 1 );
374 # If there's no recognized interwiki or namespace,
375 # then let the colon expression be part of the title.
377 break;
378 } while ( true );
380 $fragment = strstr( $dbkey, '#' );
381 if ( false !== $fragment ) {
382 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
383 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
384 # remove whitespace again: prevents "Foo_bar_#"
385 # becoming "Foo_bar_"
386 $dbkey = preg_replace( '/_*$/', '', $dbkey );
389 # Reject illegal characters.
390 $rxTc = self::getTitleInvalidRegex();
391 $matches = [];
392 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
393 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
396 # Pages with "/./" or "/../" appearing in the URLs will often be un-
397 # reachable due to the way web browsers deal with 'relative' URLs.
398 # Also, they conflict with subpage syntax. Forbid them explicitly.
399 if (
400 strpos( $dbkey, '.' ) !== false &&
402 $dbkey === '.' || $dbkey === '..' ||
403 strpos( $dbkey, './' ) === 0 ||
404 strpos( $dbkey, '../' ) === 0 ||
405 strpos( $dbkey, '/./' ) !== false ||
406 strpos( $dbkey, '/../' ) !== false ||
407 substr( $dbkey, -2 ) == '/.' ||
408 substr( $dbkey, -3 ) == '/..'
411 throw new MalformedTitleException( 'title-invalid-relative', $text );
414 # Magic tilde sequences? Nu-uh!
415 if ( strpos( $dbkey, '~~~' ) !== false ) {
416 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
419 # Limit the size of titles to 255 bytes. This is typically the size of the
420 # underlying database field. We make an exception for special pages, which
421 # don't need to be stored in the database, and may edge over 255 bytes due
422 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
423 $maxLength = ( $parts['namespace'] != NS_SPECIAL ) ? 255 : 512;
424 if ( strlen( $dbkey ) > $maxLength ) {
425 throw new MalformedTitleException( 'title-invalid-too-long', $text,
426 [ Message::numParam( $maxLength ) ] );
429 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
430 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
431 # other site might be case-sensitive.
432 $parts['user_case_dbkey'] = $dbkey;
433 if ( $parts['interwiki'] === '' ) {
434 $dbkey = Title::capitalize( $dbkey, $parts['namespace'] );
437 # Can't make a link to a namespace alone... "empty" local links can only be
438 # self-links with a fragment identifier.
439 if ( $dbkey == '' && $parts['interwiki'] === '' ) {
440 if ( $parts['namespace'] != NS_MAIN ) {
441 throw new MalformedTitleException( 'title-invalid-empty', $text );
445 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
446 // IP names are not allowed for accounts, and can only be referring to
447 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
448 // there are numerous ways to present the same IP. Having sp:contribs scan
449 // them all is silly and having some show the edits and others not is
450 // inconsistent. Same for talk/userpages. Keep them normalized instead.
451 if ( $parts['namespace'] == NS_USER || $parts['namespace'] == NS_USER_TALK ) {
452 $dbkey = IP::sanitizeIP( $dbkey );
455 // Any remaining initial :s are illegal.
456 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
457 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
460 # Fill fields
461 $parts['dbkey'] = $dbkey;
463 return $parts;
467 * Returns a simple regex that will match on characters and sequences invalid in titles.
468 * Note that this doesn't pick up many things that could be wrong with titles, but that
469 * replacing this regex with something valid will make many titles valid.
470 * Previously Title::getTitleInvalidRegex()
472 * @return string Regex string
473 * @since 1.25
475 public static function getTitleInvalidRegex() {
476 static $rxTc = false;
477 if ( !$rxTc ) {
478 # Matching titles will be held as illegal.
479 $rxTc = '/' .
480 # Any character not allowed is forbidden...
481 '[^' . Title::legalChars() . ']' .
482 # URL percent encoding sequences interfere with the ability
483 # to round-trip titles -- you can't link to them consistently.
484 '|%[0-9A-Fa-f]{2}' .
485 # XML/HTML character references produce similar issues.
486 '|&[A-Za-z0-9\x80-\xff]+;' .
487 '|&#[0-9]+;' .
488 '|&#x[0-9A-Fa-f]+;' .
489 '/S';
492 return $rxTc;