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\Linker\LinkTarget
;
27 * A codec for %MediaWiki page titles.
29 * @note Normalization and validation is applied while parsing, not when formatting.
30 * It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
31 * to generate an (invalid) title string from it. TitleValues should be constructed only
32 * via parseTitle() or from a (semi)trusted source, such as the database.
34 * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
37 class MediaWikiTitleCodec
implements TitleFormatter
, TitleParser
{
46 protected $genderCache;
51 protected $localInterwikis;
54 * @param Language $language The language object to use for localizing namespace names.
55 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
56 * @param string[]|string $localInterwikis
58 public function __construct( Language
$language, GenderCache
$genderCache,
61 $this->language
= $language;
62 $this->genderCache
= $genderCache;
63 $this->localInterwikis
= (array)$localInterwikis;
67 * @see TitleFormatter::getNamespaceName()
69 * @param int $namespace
72 * @throws InvalidArgumentException If the namespace is invalid
75 public function getNamespaceName( $namespace, $text ) {
76 if ( $this->language
->needsGenderDistinction() &&
77 MWNamespace
::hasGenderDistinction( $namespace )
80 // NOTE: we are assuming here that the title text is a user name!
81 $gender = $this->genderCache
->getGenderOf( $text, __METHOD__
);
82 $name = $this->language
->getGenderNsText( $namespace, $gender );
84 $name = $this->language
->getNsText( $namespace );
87 if ( $name === false ) {
88 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
95 * @see TitleFormatter::formatTitle()
97 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
98 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
99 * Underscores will be replaced.
100 * @param string $fragment The fragment name (may be empty).
102 * @throws InvalidArgumentException If the namespace is invalid
105 public function formatTitle( $namespace, $text, $fragment = '' ) {
106 if ( $namespace !== false ) {
107 $namespace = $this->getNamespaceName( $namespace, $text );
109 if ( $namespace !== '' ) {
110 $text = $namespace . ':' . $text;
114 if ( $fragment !== '' ) {
115 $text = $text . '#' . $fragment;
118 $text = str_replace( '_', ' ', $text );
124 * Parses the given text and constructs a TitleValue. Normalization
125 * is applied according to the rules appropriate for the form specified by $form.
127 * @param string $text The text to parse
128 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
130 * @throws MalformedTitleException
133 public function parseTitle( $text, $defaultNamespace ) {
134 // NOTE: this is an ugly cludge that allows this class to share the
135 // code for parsing with the old Title class. The parser code should
136 // be refactored to avoid this.
137 $parts = $this->splitTitleString( $text, $defaultNamespace );
139 // Interwiki links are not supported by TitleValue
140 if ( $parts['interwiki'] !== '' ) {
141 throw new MalformedTitleException( 'title-invalid-interwiki', $text );
144 // Relative fragment links are not supported by TitleValue
145 if ( $parts['dbkey'] === '' ) {
146 throw new MalformedTitleException( 'title-invalid-empty', $text );
149 return new TitleValue( $parts['namespace'], $parts['dbkey'], $parts['fragment'] );
153 * @see TitleFormatter::getText()
155 * @param LinkTarget $title
157 * @return string $title->getText()
159 public function getText( LinkTarget
$title ) {
160 return $this->formatTitle( false, $title->getText(), '' );
164 * @see TitleFormatter::getText()
166 * @param LinkTarget $title
170 public function getPrefixedText( LinkTarget
$title ) {
171 return $this->formatTitle( $title->getNamespace(), $title->getText(), '' );
175 * @see TitleFormatter::getText()
177 * @param LinkTarget $title
181 public function getFullText( LinkTarget
$title ) {
182 return $this->formatTitle( $title->getNamespace(), $title->getText(), $title->getFragment() );
186 * Normalizes and splits a title string.
188 * This function removes illegal characters, splits off the interwiki and
189 * namespace prefixes, sets the other forms, and canonicalizes
192 * @todo this method is only exposed as a temporary measure to ease refactoring.
193 * It was copied with minimal changes from Title::secureAndSplit().
195 * @todo This method should be split up and an appropriate interface
196 * defined for use by the Title class.
198 * @param string $text
199 * @param int $defaultNamespace
201 * @throws MalformedTitleException If $text is not a valid title string.
202 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
203 * 'user_case_dbkey', and 'dbkey'.
205 public function splitTitleString( $text, $defaultNamespace = NS_MAIN
) {
206 $dbkey = str_replace( ' ', '_', $text );
211 'local_interwiki' => false,
213 'namespace' => $defaultNamespace,
215 'user_case_dbkey' => $dbkey,
218 # Strip Unicode bidi override characters.
219 # Sometimes they slip into cut-n-pasted page titles, where the
220 # override chars get included in list displays.
221 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
223 # Clean up whitespace
224 # Note: use of the /u option on preg_replace here will cause
225 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
226 # conveniently disabling them.
227 $dbkey = preg_replace(
228 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
232 $dbkey = trim( $dbkey, '_' );
234 if ( strpos( $dbkey, UtfNormal\Constants
::UTF8_REPLACEMENT
) !== false ) {
235 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
236 throw new MalformedTitleException( 'title-invalid-utf8', $text );
239 $parts['dbkey'] = $dbkey;
241 # Initial colon indicates main namespace rather than specified default
242 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
243 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
244 $parts['namespace'] = NS_MAIN
;
245 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
246 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
249 if ( $dbkey == '' ) {
250 throw new MalformedTitleException( 'title-invalid-empty', $text );
253 # Namespace or interwiki prefix
254 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
257 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
259 $ns = $this->language
->getNsIndex( $p );
260 if ( $ns !== false ) {
263 $parts['namespace'] = $ns;
264 # For Talk:X pages, check if X has a "namespace" prefix
265 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
266 if ( $this->language
->getNsIndex( $x[1] ) ) {
267 # Disallow Talk:File:x type titles...
268 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
269 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
270 // TODO: get rid of global state!
271 # Disallow Talk:Interwiki:x type titles...
272 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
275 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
278 $parts['interwiki'] = $this->language
->lc( $p );
280 # Redundant interwiki prefix to the local wiki
281 foreach ( $this->localInterwikis
as $localIW ) {
282 if ( 0 == strcasecmp( $parts['interwiki'], $localIW ) ) {
283 if ( $dbkey == '' ) {
284 # Empty self-links should point to the Main Page, to ensure
285 # compatibility with cross-wiki transclusions and the like.
286 $mainPage = Title
::newMainPage();
288 'interwiki' => $mainPage->getInterwiki(),
289 'local_interwiki' => true,
290 'fragment' => $mainPage->getFragment(),
291 'namespace' => $mainPage->getNamespace(),
292 'dbkey' => $mainPage->getDBkey(),
293 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
296 $parts['interwiki'] = '';
297 # local interwikis should behave like initial-colon links
298 $parts['local_interwiki'] = true;
300 # Do another namespace split...
305 # If there's an initial colon after the interwiki, that also
306 # resets the default namespace
307 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
308 $parts['namespace'] = NS_MAIN
;
309 $dbkey = substr( $dbkey, 1 );
312 # If there's no recognized interwiki or namespace,
313 # then let the colon expression be part of the title.
318 $fragment = strstr( $dbkey, '#' );
319 if ( false !== $fragment ) {
320 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
321 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
322 # remove whitespace again: prevents "Foo_bar_#"
323 # becoming "Foo_bar_"
324 $dbkey = preg_replace( '/_*$/', '', $dbkey );
327 # Reject illegal characters.
328 $rxTc = self
::getTitleInvalidRegex();
330 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
331 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
334 # Pages with "/./" or "/../" appearing in the URLs will often be un-
335 # reachable due to the way web browsers deal with 'relative' URLs.
336 # Also, they conflict with subpage syntax. Forbid them explicitly.
338 strpos( $dbkey, '.' ) !== false &&
340 $dbkey === '.' ||
$dbkey === '..' ||
341 strpos( $dbkey, './' ) === 0 ||
342 strpos( $dbkey, '../' ) === 0 ||
343 strpos( $dbkey, '/./' ) !== false ||
344 strpos( $dbkey, '/../' ) !== false ||
345 substr( $dbkey, -2 ) == '/.' ||
346 substr( $dbkey, -3 ) == '/..'
349 throw new MalformedTitleException( 'title-invalid-relative', $text );
352 # Magic tilde sequences? Nu-uh!
353 if ( strpos( $dbkey, '~~~' ) !== false ) {
354 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
357 # Limit the size of titles to 255 bytes. This is typically the size of the
358 # underlying database field. We make an exception for special pages, which
359 # don't need to be stored in the database, and may edge over 255 bytes due
360 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
361 $maxLength = ( $parts['namespace'] != NS_SPECIAL
) ?
255 : 512;
362 if ( strlen( $dbkey ) > $maxLength ) {
363 throw new MalformedTitleException( 'title-invalid-too-long', $text,
364 [ Message
::numParam( $maxLength ) ] );
367 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
368 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
369 # other site might be case-sensitive.
370 $parts['user_case_dbkey'] = $dbkey;
371 if ( $parts['interwiki'] === '' ) {
372 $dbkey = Title
::capitalize( $dbkey, $parts['namespace'] );
375 # Can't make a link to a namespace alone... "empty" local links can only be
376 # self-links with a fragment identifier.
377 if ( $dbkey == '' && $parts['interwiki'] === '' ) {
378 if ( $parts['namespace'] != NS_MAIN
) {
379 throw new MalformedTitleException( 'title-invalid-empty', $text );
383 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
384 // IP names are not allowed for accounts, and can only be referring to
385 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
386 // there are numerous ways to present the same IP. Having sp:contribs scan
387 // them all is silly and having some show the edits and others not is
388 // inconsistent. Same for talk/userpages. Keep them normalized instead.
389 if ( $parts['namespace'] == NS_USER ||
$parts['namespace'] == NS_USER_TALK
) {
390 $dbkey = IP
::sanitizeIP( $dbkey );
393 // Any remaining initial :s are illegal.
394 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
395 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
399 $parts['dbkey'] = $dbkey;
405 * Returns a simple regex that will match on characters and sequences invalid in titles.
406 * Note that this doesn't pick up many things that could be wrong with titles, but that
407 * replacing this regex with something valid will make many titles valid.
408 * Previously Title::getTitleInvalidRegex()
410 * @return string Regex string
413 public static function getTitleInvalidRegex() {
414 static $rxTc = false;
416 # Matching titles will be held as illegal.
418 # Any character not allowed is forbidden...
419 '[^' . Title
::legalChars() . ']' .
420 # URL percent encoding sequences interfere with the ability
421 # to round-trip titles -- you can't link to them consistently.
423 # XML/HTML character references produce similar issues.
424 '|&[A-Za-z0-9\x80-\xff]+;' .
426 '|&#x[0-9A-Fa-f]+;' .