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
22 * @author Daniel Kinzler
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Linker\LinkTarget
;
28 * A codec for %MediaWiki page titles.
30 * @note Normalization and validation is applied while parsing, not when formatting.
31 * It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
32 * to generate an (invalid) title string from it. TitleValues should be constructed only
33 * via parseTitle() or from a (semi)trusted source, such as the database.
35 * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
38 class MediaWikiTitleCodec
implements TitleFormatter
, TitleParser
{
47 protected $genderCache;
52 protected $localInterwikis;
55 * @param Language $language The language object to use for localizing namespace names.
56 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
57 * @param string[]|string $localInterwikis
59 public function __construct( Language
$language, GenderCache
$genderCache,
62 $this->language
= $language;
63 $this->genderCache
= $genderCache;
64 $this->localInterwikis
= (array)$localInterwikis;
68 * @see TitleFormatter::getNamespaceName()
70 * @param int $namespace
73 * @throws InvalidArgumentException If the namespace is invalid
76 public function getNamespaceName( $namespace, $text ) {
77 if ( $this->language
->needsGenderDistinction() &&
78 MWNamespace
::hasGenderDistinction( $namespace )
81 // NOTE: we are assuming here that the title text is a user name!
82 $gender = $this->genderCache
->getGenderOf( $text, __METHOD__
);
83 $name = $this->language
->getGenderNsText( $namespace, $gender );
85 $name = $this->language
->getNsText( $namespace );
88 if ( $name === false ) {
89 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
96 * @see TitleFormatter::formatTitle()
98 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
99 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
100 * Underscores will be replaced.
101 * @param string $fragment The fragment name (may be empty).
102 * @param string $interwiki The interwiki name (may be empty).
104 * @throws InvalidArgumentException If the namespace is invalid
107 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
108 if ( $namespace !== false ) {
109 // Try to get a namespace name, but fallback
110 // to empty string if it doesn't exist
112 $nsName = $this->getNamespaceName( $namespace, $text );
113 } catch ( InvalidArgumentException
$e ) {
117 if ( $namespace !== 0 ) {
118 $text = $nsName . ':' . $text;
122 if ( $fragment !== '' ) {
123 $text = $text . '#' . $fragment;
126 if ( $interwiki !== '' ) {
127 $text = $interwiki . ':' . $text;
130 $text = str_replace( '_', ' ', $text );
136 * Parses the given text and constructs a TitleValue. Normalization
137 * is applied according to the rules appropriate for the form specified by $form.
139 * @param string $text The text to parse
140 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
142 * @throws MalformedTitleException
145 public function parseTitle( $text, $defaultNamespace ) {
146 // NOTE: this is an ugly cludge that allows this class to share the
147 // code for parsing with the old Title class. The parser code should
148 // be refactored to avoid this.
149 $parts = $this->splitTitleString( $text, $defaultNamespace );
151 // Relative fragment links are not supported by TitleValue
152 if ( $parts['dbkey'] === '' ) {
153 throw new MalformedTitleException( 'title-invalid-empty', $text );
156 return new TitleValue(
165 * @see TitleFormatter::getText()
167 * @param LinkTarget $title
169 * @return string $title->getText()
171 public function getText( LinkTarget
$title ) {
172 return $this->formatTitle( false, $title->getText(), '' );
176 * @see TitleFormatter::getText()
178 * @param LinkTarget $title
182 public function getPrefixedText( LinkTarget
$title ) {
183 return $this->formatTitle(
184 $title->getNamespace(),
187 $title->getInterwiki()
193 * @see TitleFormatter::getPrefixedDBkey()
194 * @param LinkTarget $target
197 public function getPrefixedDBkey( LinkTarget
$target ) {
199 if ( $target->isExternal() ) {
200 $key .= $target->getInterwiki() . ':';
202 // Try to get a namespace name, but fallback
203 // to empty string if it doesn't exist
205 $nsName = $this->getNamespaceName(
206 $target->getNamespace(),
209 } catch ( InvalidArgumentException
$e ) {
213 if ( $target->getNamespace() !== 0 ) {
214 $key .= $nsName . ':';
217 $key .= $target->getText();
219 return strtr( $key, ' ', '_' );
223 * @see TitleFormatter::getText()
225 * @param LinkTarget $title
229 public function getFullText( LinkTarget
$title ) {
230 return $this->formatTitle(
231 $title->getNamespace(),
233 $title->getFragment(),
234 $title->getInterwiki()
239 * Normalizes and splits a title string.
241 * This function removes illegal characters, splits off the interwiki and
242 * namespace prefixes, sets the other forms, and canonicalizes
245 * @todo this method is only exposed as a temporary measure to ease refactoring.
246 * It was copied with minimal changes from Title::secureAndSplit().
248 * @todo This method should be split up and an appropriate interface
249 * defined for use by the Title class.
251 * @param string $text
252 * @param int $defaultNamespace
254 * @throws MalformedTitleException If $text is not a valid title string.
255 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
256 * 'user_case_dbkey', and 'dbkey'.
258 public function splitTitleString( $text, $defaultNamespace = NS_MAIN
) {
259 $dbkey = str_replace( ' ', '_', $text );
264 'local_interwiki' => false,
266 'namespace' => $defaultNamespace,
268 'user_case_dbkey' => $dbkey,
271 # Strip Unicode bidi override characters.
272 # Sometimes they slip into cut-n-pasted page titles, where the
273 # override chars get included in list displays.
274 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
276 # Clean up whitespace
277 # Note: use of the /u option on preg_replace here will cause
278 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
279 # conveniently disabling them.
280 $dbkey = preg_replace(
281 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
285 $dbkey = trim( $dbkey, '_' );
287 if ( strpos( $dbkey, UtfNormal\Constants
::UTF8_REPLACEMENT
) !== false ) {
288 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
289 throw new MalformedTitleException( 'title-invalid-utf8', $text );
292 $parts['dbkey'] = $dbkey;
294 # Initial colon indicates main namespace rather than specified default
295 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
296 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
297 $parts['namespace'] = NS_MAIN
;
298 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
299 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
302 if ( $dbkey == '' ) {
303 throw new MalformedTitleException( 'title-invalid-empty', $text );
306 # Namespace or interwiki prefix
307 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
310 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
312 $ns = $this->language
->getNsIndex( $p );
313 $interwikiLookup = MediaWikiServices
::getInstance()->getInterwikiLookup();
314 if ( $ns !== false ) {
317 $parts['namespace'] = $ns;
318 # For Talk:X pages, check if X has a "namespace" prefix
319 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
320 if ( $this->language
->getNsIndex( $x[1] ) ) {
321 # Disallow Talk:File:x type titles...
322 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
323 } elseif ( $interwikiLookup->isValidInterwiki( $x[1] ) ) {
324 // TODO: get rid of global state!
325 # Disallow Talk:Interwiki:x type titles...
326 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
329 } elseif ( $interwikiLookup->isValidInterwiki( $p ) ) {
332 $parts['interwiki'] = $this->language
->lc( $p );
334 # Redundant interwiki prefix to the local wiki
335 foreach ( $this->localInterwikis
as $localIW ) {
336 if ( 0 == strcasecmp( $parts['interwiki'], $localIW ) ) {
337 if ( $dbkey == '' ) {
338 # Empty self-links should point to the Main Page, to ensure
339 # compatibility with cross-wiki transclusions and the like.
340 $mainPage = Title
::newMainPage();
342 'interwiki' => $mainPage->getInterwiki(),
343 'local_interwiki' => true,
344 'fragment' => $mainPage->getFragment(),
345 'namespace' => $mainPage->getNamespace(),
346 'dbkey' => $mainPage->getDBkey(),
347 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
350 $parts['interwiki'] = '';
351 # local interwikis should behave like initial-colon links
352 $parts['local_interwiki'] = true;
354 # Do another namespace split...
359 # If there's an initial colon after the interwiki, that also
360 # resets the default namespace
361 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
362 $parts['namespace'] = NS_MAIN
;
363 $dbkey = substr( $dbkey, 1 );
366 # If there's no recognized interwiki or namespace,
367 # then let the colon expression be part of the title.
372 $fragment = strstr( $dbkey, '#' );
373 if ( false !== $fragment ) {
374 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
375 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
376 # remove whitespace again: prevents "Foo_bar_#"
377 # becoming "Foo_bar_"
378 $dbkey = preg_replace( '/_*$/', '', $dbkey );
381 # Reject illegal characters.
382 $rxTc = self
::getTitleInvalidRegex();
384 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
385 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
388 # Pages with "/./" or "/../" appearing in the URLs will often be un-
389 # reachable due to the way web browsers deal with 'relative' URLs.
390 # Also, they conflict with subpage syntax. Forbid them explicitly.
392 strpos( $dbkey, '.' ) !== false &&
394 $dbkey === '.' ||
$dbkey === '..' ||
395 strpos( $dbkey, './' ) === 0 ||
396 strpos( $dbkey, '../' ) === 0 ||
397 strpos( $dbkey, '/./' ) !== false ||
398 strpos( $dbkey, '/../' ) !== false ||
399 substr( $dbkey, -2 ) == '/.' ||
400 substr( $dbkey, -3 ) == '/..'
403 throw new MalformedTitleException( 'title-invalid-relative', $text );
406 # Magic tilde sequences? Nu-uh!
407 if ( strpos( $dbkey, '~~~' ) !== false ) {
408 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
411 # Limit the size of titles to 255 bytes. This is typically the size of the
412 # underlying database field. We make an exception for special pages, which
413 # don't need to be stored in the database, and may edge over 255 bytes due
414 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
415 $maxLength = ( $parts['namespace'] != NS_SPECIAL
) ?
255 : 512;
416 if ( strlen( $dbkey ) > $maxLength ) {
417 throw new MalformedTitleException( 'title-invalid-too-long', $text,
418 [ Message
::numParam( $maxLength ) ] );
421 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
422 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
423 # other site might be case-sensitive.
424 $parts['user_case_dbkey'] = $dbkey;
425 if ( $parts['interwiki'] === '' ) {
426 $dbkey = Title
::capitalize( $dbkey, $parts['namespace'] );
429 # Can't make a link to a namespace alone... "empty" local links can only be
430 # self-links with a fragment identifier.
431 if ( $dbkey == '' && $parts['interwiki'] === '' ) {
432 if ( $parts['namespace'] != NS_MAIN
) {
433 throw new MalformedTitleException( 'title-invalid-empty', $text );
437 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
438 // IP names are not allowed for accounts, and can only be referring to
439 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
440 // there are numerous ways to present the same IP. Having sp:contribs scan
441 // them all is silly and having some show the edits and others not is
442 // inconsistent. Same for talk/userpages. Keep them normalized instead.
443 if ( $parts['namespace'] == NS_USER ||
$parts['namespace'] == NS_USER_TALK
) {
444 $dbkey = IP
::sanitizeIP( $dbkey );
447 // Any remaining initial :s are illegal.
448 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
449 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
453 $parts['dbkey'] = $dbkey;
459 * Returns a simple regex that will match on characters and sequences invalid in titles.
460 * Note that this doesn't pick up many things that could be wrong with titles, but that
461 * replacing this regex with something valid will make many titles valid.
462 * Previously Title::getTitleInvalidRegex()
464 * @return string Regex string
467 public static function getTitleInvalidRegex() {
468 static $rxTc = false;
470 # Matching titles will be held as illegal.
472 # Any character not allowed is forbidden...
473 '[^' . Title
::legalChars() . ']' .
474 # URL percent encoding sequences interfere with the ability
475 # to round-trip titles -- you can't link to them consistently.
477 # XML/HTML character references produce similar issues.
478 '|&[A-Za-z0-9\x80-\xff]+;' .
480 '|&#x[0-9A-Fa-f]+;' .