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
21 * @author Daniel Kinzler
23 use MediaWiki\Interwiki\InterwikiLookup
;
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 * @var InterwikiLookup
57 protected $interwikiLookup;
60 * @param Language $language The language object to use for localizing namespace names.
61 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
62 * @param string[]|string $localInterwikis
63 * @param InterwikiLookup|null $interwikiLookup
65 public function __construct( Language
$language, GenderCache
$genderCache,
66 $localInterwikis = [], $interwikiLookup = null
68 $this->language
= $language;
69 $this->genderCache
= $genderCache;
70 $this->localInterwikis
= (array)$localInterwikis;
71 $this->interwikiLookup
= $interwikiLookup ?
:
72 MediaWikiServices
::getInstance()->getInterwikiLookup();
76 * @see TitleFormatter::getNamespaceName()
78 * @param int $namespace
81 * @throws InvalidArgumentException If the namespace is invalid
82 * @return string Namespace name with underscores (not spaces)
84 public function getNamespaceName( $namespace, $text ) {
85 if ( $this->language
->needsGenderDistinction() &&
86 MWNamespace
::hasGenderDistinction( $namespace )
88 // NOTE: we are assuming here that the title text is a user name!
89 $gender = $this->genderCache
->getGenderOf( $text, __METHOD__
);
90 $name = $this->language
->getGenderNsText( $namespace, $gender );
92 $name = $this->language
->getNsText( $namespace );
95 if ( $name === false ) {
96 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
103 * @see TitleFormatter::formatTitle()
105 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
106 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
107 * Underscores will be replaced.
108 * @param string $fragment The fragment name (may be empty).
109 * @param string $interwiki The interwiki name (may be empty).
111 * @throws InvalidArgumentException If the namespace is invalid
114 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
116 if ( $interwiki !== '' ) {
117 $out = $interwiki . ':';
120 if ( $namespace != 0 ) {
122 $nsName = $this->getNamespaceName( $namespace, $text );
123 } catch ( InvalidArgumentException
$e ) {
124 // See T165149. Awkward, but better than erroneously linking to the main namespace.
125 $nsName = $this->language
->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$namespace}";
128 $out .= $nsName . ':';
132 if ( $fragment !== '' ) {
133 $out .= '#' . $fragment;
136 $out = str_replace( '_', ' ', $out );
142 * Parses the given text and constructs a TitleValue. Normalization
143 * is applied according to the rules appropriate for the form specified by $form.
145 * @param string $text The text to parse
146 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
148 * @throws MalformedTitleException
151 public function parseTitle( $text, $defaultNamespace = NS_MAIN
) {
152 // Convert things like é ā or 〗 into normalized (T16952) text
153 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
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( $filteredText, $defaultNamespace );
160 // Fragment-only is okay, but only with no namespace
161 if ( $parts['dbkey'] === '' &&
162 ( $parts['fragment'] === '' ||
$parts['namespace'] !== NS_MAIN
) ) {
163 throw new MalformedTitleException( 'title-invalid-empty', $text );
166 return new TitleValue(
175 * @see TitleFormatter::getText()
177 * @param LinkTarget $title
179 * @return string $title->getText()
181 public function getText( LinkTarget
$title ) {
182 return $title->getText();
186 * @see TitleFormatter::getText()
188 * @param LinkTarget $title
192 public function getPrefixedText( LinkTarget
$title ) {
193 if ( !isset( $title->prefixedText
) ) {
194 $title->prefixedText
= $this->formatTitle(
195 $title->getNamespace(),
198 $title->getInterwiki()
202 return $title->prefixedText
;
207 * @see TitleFormatter::getPrefixedDBkey()
208 * @param LinkTarget $target
211 public function getPrefixedDBkey( LinkTarget
$target ) {
212 return strtr( $this->formatTitle(
213 $target->getNamespace(),
216 $target->getInterwiki()
221 * @see TitleFormatter::getText()
223 * @param LinkTarget $title
227 public function getFullText( LinkTarget
$title ) {
228 return $this->formatTitle(
229 $title->getNamespace(),
231 $title->getFragment(),
232 $title->getInterwiki()
237 * Normalizes and splits a title string.
239 * This function removes illegal characters, splits off the interwiki and
240 * namespace prefixes, sets the other forms, and canonicalizes
243 * @todo this method is only exposed as a temporary measure to ease refactoring.
244 * It was copied with minimal changes from Title::secureAndSplit().
246 * @todo This method should be split up and an appropriate interface
247 * defined for use by the Title class.
249 * @param string $text
250 * @param int $defaultNamespace
252 * @throws MalformedTitleException If $text is not a valid title string.
253 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
254 * 'user_case_dbkey', and 'dbkey'.
256 public function splitTitleString( $text, $defaultNamespace = NS_MAIN
) {
257 $dbkey = str_replace( ' ', '_', $text );
262 'local_interwiki' => false,
264 'namespace' => $defaultNamespace,
266 'user_case_dbkey' => $dbkey,
269 # Strip Unicode bidi override characters.
270 # Sometimes they slip into cut-n-pasted page titles, where the
271 # override chars get included in list displays.
272 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
274 # Clean up whitespace
275 # Note: use of the /u option on preg_replace here will cause
276 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
277 # conveniently disabling them.
278 $dbkey = preg_replace(
279 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
283 $dbkey = trim( $dbkey, '_' );
285 if ( strpos( $dbkey, UtfNormal\Constants
::UTF8_REPLACEMENT
) !== false ) {
286 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
287 throw new MalformedTitleException( 'title-invalid-utf8', $text );
290 $parts['dbkey'] = $dbkey;
292 # Initial colon indicates main namespace rather than specified default
293 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
294 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
295 $parts['namespace'] = NS_MAIN
;
296 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
297 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
300 if ( $dbkey == '' ) {
301 throw new MalformedTitleException( 'title-invalid-empty', $text );
304 # Namespace or interwiki prefix
305 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
308 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
310 $ns = $this->language
->getNsIndex( $p );
311 if ( $ns !== false ) {
314 $parts['namespace'] = $ns;
315 # For Talk:X pages, check if X has a "namespace" prefix
316 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
317 if ( $this->language
->getNsIndex( $x[1] ) ) {
318 # Disallow Talk:File:x type titles...
319 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
320 } elseif ( $this->interwikiLookup
->isValidInterwiki( $x[1] ) ) {
321 # Disallow Talk:Interwiki:x type titles...
322 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
325 } elseif ( $this->interwikiLookup
->isValidInterwiki( $p ) ) {
328 $parts['interwiki'] = $this->language
->lc( $p );
330 # Redundant interwiki prefix to the local wiki
331 foreach ( $this->localInterwikis
as $localIW ) {
332 if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
333 if ( $dbkey == '' ) {
334 # Empty self-links should point to the Main Page, to ensure
335 # compatibility with cross-wiki transclusions and the like.
336 $mainPage = Title
::newMainPage();
338 'interwiki' => $mainPage->getInterwiki(),
339 'local_interwiki' => true,
340 'fragment' => $mainPage->getFragment(),
341 'namespace' => $mainPage->getNamespace(),
342 'dbkey' => $mainPage->getDBkey(),
343 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
346 $parts['interwiki'] = '';
347 # local interwikis should behave like initial-colon links
348 $parts['local_interwiki'] = true;
350 # Do another namespace split...
355 # If there's an initial colon after the interwiki, that also
356 # resets the default namespace
357 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
358 $parts['namespace'] = NS_MAIN
;
359 $dbkey = substr( $dbkey, 1 );
360 $dbkey = trim( $dbkey, '_' );
363 # If there's no recognized interwiki or namespace,
364 # then let the colon expression be part of the title.
369 $fragment = strstr( $dbkey, '#' );
370 if ( $fragment !== false ) {
371 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
372 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
373 # remove whitespace again: prevents "Foo_bar_#"
374 # becoming "Foo_bar_"
375 $dbkey = preg_replace( '/_*$/', '', $dbkey );
378 # Reject illegal characters.
379 $rxTc = self
::getTitleInvalidRegex();
381 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
382 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
385 # Pages with "/./" or "/../" appearing in the URLs will often be un-
386 # reachable due to the way web browsers deal with 'relative' URLs.
387 # Also, they conflict with subpage syntax. Forbid them explicitly.
389 strpos( $dbkey, '.' ) !== false &&
391 $dbkey === '.' ||
$dbkey === '..' ||
392 strpos( $dbkey, './' ) === 0 ||
393 strpos( $dbkey, '../' ) === 0 ||
394 strpos( $dbkey, '/./' ) !== false ||
395 strpos( $dbkey, '/../' ) !== false ||
396 substr( $dbkey, -2 ) == '/.' ||
397 substr( $dbkey, -3 ) == '/..'
400 throw new MalformedTitleException( 'title-invalid-relative', $text );
403 # Magic tilde sequences? Nu-uh!
404 if ( strpos( $dbkey, '~~~' ) !== false ) {
405 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
408 # Limit the size of titles to 255 bytes. This is typically the size of the
409 # underlying database field. We make an exception for special pages, which
410 # don't need to be stored in the database, and may edge over 255 bytes due
411 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
412 $maxLength = ( $parts['namespace'] != NS_SPECIAL
) ?
255 : 512;
413 if ( strlen( $dbkey ) > $maxLength ) {
414 throw new MalformedTitleException( 'title-invalid-too-long', $text,
415 [ Message
::numParam( $maxLength ) ] );
418 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
419 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
420 # other site might be case-sensitive.
421 $parts['user_case_dbkey'] = $dbkey;
422 if ( $parts['interwiki'] === '' ) {
423 $dbkey = Title
::capitalize( $dbkey, $parts['namespace'] );
426 # Can't make a link to a namespace alone... "empty" local links can only be
427 # self-links with a fragment identifier.
428 if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] != NS_MAIN
) {
429 throw new MalformedTitleException( 'title-invalid-empty', $text );
432 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
433 // IP names are not allowed for accounts, and can only be referring to
434 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
435 // there are numerous ways to present the same IP. Having sp:contribs scan
436 // them all is silly and having some show the edits and others not is
437 // inconsistent. Same for talk/userpages. Keep them normalized instead.
438 if ( $parts['namespace'] == NS_USER ||
$parts['namespace'] == NS_USER_TALK
) {
439 $dbkey = IP
::sanitizeIP( $dbkey );
442 // Any remaining initial :s are illegal.
443 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
444 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
448 $parts['dbkey'] = $dbkey;
454 * Returns a simple regex that will match on characters and sequences invalid in titles.
455 * Note that this doesn't pick up many things that could be wrong with titles, but that
456 * replacing this regex with something valid will make many titles valid.
457 * Previously Title::getTitleInvalidRegex()
459 * @return string Regex string
462 public static function getTitleInvalidRegex() {
463 static $rxTc = false;
465 # Matching titles will be held as illegal.
467 # Any character not allowed is forbidden...
468 '[^' . Title
::legalChars() . ']' .
469 # URL percent encoding sequences interfere with the ability
470 # to round-trip titles -- you can't link to them consistently.
472 # XML/HTML character references produce similar issues.
473 '|&[A-Za-z0-9\x80-\xff]+;' .
475 '|&#x[0-9A-Fa-f]+;' .