Allow fragment-only TitleValues
[lhc/web/wiklou.git] / includes / title / MediaWikiTitleCodec.php
1 <?php
2 /**
3 * A codec for MediaWiki page titles.
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 * @author Daniel Kinzler
22 */
23 use MediaWiki\Interwiki\InterwikiLookup;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Linker\LinkTarget;
26
27 /**
28 * A codec for MediaWiki page titles.
29 *
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.
34 *
35 * @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
36 * @since 1.23
37 */
38 class MediaWikiTitleCodec implements TitleFormatter, TitleParser {
39 /**
40 * @var Language
41 */
42 protected $language;
43
44 /**
45 * @var GenderCache
46 */
47 protected $genderCache;
48
49 /**
50 * @var string[]
51 */
52 protected $localInterwikis;
53
54 /**
55 * @var InterwikiLookup
56 */
57 protected $interwikiLookup;
58
59 /**
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
64 */
65 public function __construct( Language $language, GenderCache $genderCache,
66 $localInterwikis = [], $interwikiLookup = null
67 ) {
68 $this->language = $language;
69 $this->genderCache = $genderCache;
70 $this->localInterwikis = (array)$localInterwikis;
71 $this->interwikiLookup = $interwikiLookup ?:
72 MediaWikiServices::getInstance()->getInterwikiLookup();
73 }
74
75 /**
76 * @see TitleFormatter::getNamespaceName()
77 *
78 * @param int $namespace
79 * @param string $text
80 *
81 * @throws InvalidArgumentException If the namespace is invalid
82 * @return string Namespace name with underscores (not spaces)
83 */
84 public function getNamespaceName( $namespace, $text ) {
85 if ( $this->language->needsGenderDistinction() &&
86 MWNamespace::hasGenderDistinction( $namespace )
87 ) {
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 );
91 } else {
92 $name = $this->language->getNsText( $namespace );
93 }
94
95 if ( $name === false ) {
96 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
97 }
98
99 return $name;
100 }
101
102 /**
103 * @see TitleFormatter::formatTitle()
104 *
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).
110 *
111 * @throws InvalidArgumentException If the namespace is invalid
112 * @return string
113 */
114 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
115 $out = '';
116 if ( $interwiki !== '' ) {
117 $out = $interwiki . ':';
118 }
119
120 if ( $namespace != 0 ) {
121 try {
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}";
126 }
127
128 $out .= $nsName . ':';
129 }
130 $out .= $text;
131
132 if ( $fragment !== '' ) {
133 $out .= '#' . $fragment;
134 }
135
136 $out = str_replace( '_', ' ', $out );
137
138 return $out;
139 }
140
141 /**
142 * Parses the given text and constructs a TitleValue. Normalization
143 * is applied according to the rules appropriate for the form specified by $form.
144 *
145 * @param string $text The text to parse
146 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
147 *
148 * @throws MalformedTitleException
149 * @return TitleValue
150 */
151 public function parseTitle( $text, $defaultNamespace = NS_MAIN ) {
152 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
153 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
154
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 );
159
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 );
164 }
165
166 return new TitleValue(
167 $parts['namespace'],
168 $parts['dbkey'],
169 $parts['fragment'],
170 $parts['interwiki']
171 );
172 }
173
174 /**
175 * @see TitleFormatter::getText()
176 *
177 * @param LinkTarget $title
178 *
179 * @return string $title->getText()
180 */
181 public function getText( LinkTarget $title ) {
182 return $title->getText();
183 }
184
185 /**
186 * @see TitleFormatter::getText()
187 *
188 * @param LinkTarget $title
189 *
190 * @return string
191 */
192 public function getPrefixedText( LinkTarget $title ) {
193 if ( !isset( $title->prefixedText ) ) {
194 $title->prefixedText = $this->formatTitle(
195 $title->getNamespace(),
196 $title->getText(),
197 '',
198 $title->getInterwiki()
199 );
200 }
201
202 return $title->prefixedText;
203 }
204
205 /**
206 * @since 1.27
207 * @see TitleFormatter::getPrefixedDBkey()
208 * @param LinkTarget $target
209 * @return string
210 */
211 public function getPrefixedDBkey( LinkTarget $target ) {
212 return strtr( $this->formatTitle(
213 $target->getNamespace(),
214 $target->getDBkey(),
215 '',
216 $target->getInterwiki()
217 ), ' ', '_' );
218 }
219
220 /**
221 * @see TitleFormatter::getText()
222 *
223 * @param LinkTarget $title
224 *
225 * @return string
226 */
227 public function getFullText( LinkTarget $title ) {
228 return $this->formatTitle(
229 $title->getNamespace(),
230 $title->getText(),
231 $title->getFragment(),
232 $title->getInterwiki()
233 );
234 }
235
236 /**
237 * Normalizes and splits a title string.
238 *
239 * This function removes illegal characters, splits off the interwiki and
240 * namespace prefixes, sets the other forms, and canonicalizes
241 * everything.
242 *
243 * @todo this method is only exposed as a temporary measure to ease refactoring.
244 * It was copied with minimal changes from Title::secureAndSplit().
245 *
246 * @todo This method should be split up and an appropriate interface
247 * defined for use by the Title class.
248 *
249 * @param string $text
250 * @param int $defaultNamespace
251 *
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'.
255 */
256 public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
257 $dbkey = str_replace( ' ', '_', $text );
258
259 # Initialisation
260 $parts = [
261 'interwiki' => '',
262 'local_interwiki' => false,
263 'fragment' => '',
264 'namespace' => $defaultNamespace,
265 'dbkey' => $dbkey,
266 'user_case_dbkey' => $dbkey,
267 ];
268
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 );
273
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',
280 '_',
281 $dbkey
282 );
283 $dbkey = trim( $dbkey, '_' );
284
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 );
288 }
289
290 $parts['dbkey'] = $dbkey;
291
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
298 }
299
300 if ( $dbkey == '' ) {
301 throw new MalformedTitleException( 'title-invalid-empty', $text );
302 }
303
304 # Namespace or interwiki prefix
305 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
306 do {
307 $m = [];
308 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
309 $p = $m[1];
310 $ns = $this->language->getNsIndex( $p );
311 if ( $ns !== false ) {
312 # Ordinary namespace
313 $dbkey = $m[2];
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 );
323 }
324 }
325 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
326 # Interwiki link
327 $dbkey = $m[2];
328 $parts['interwiki'] = $this->language->lc( $p );
329
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();
337 return [
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()
344 ];
345 }
346 $parts['interwiki'] = '';
347 # local interwikis should behave like initial-colon links
348 $parts['local_interwiki'] = true;
349
350 # Do another namespace split...
351 continue 2;
352 }
353 }
354
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, '_' );
361 }
362 }
363 # If there's no recognized interwiki or namespace,
364 # then let the colon expression be part of the title.
365 }
366 break;
367 } while ( true );
368
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 );
376 }
377
378 # Reject illegal characters.
379 $rxTc = self::getTitleInvalidRegex();
380 $matches = [];
381 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
382 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
383 }
384
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.
388 if (
389 strpos( $dbkey, '.' ) !== false &&
390 (
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 ) == '/..'
398 )
399 ) {
400 throw new MalformedTitleException( 'title-invalid-relative', $text );
401 }
402
403 # Magic tilde sequences? Nu-uh!
404 if ( strpos( $dbkey, '~~~' ) !== false ) {
405 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
406 }
407
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 ) ] );
416 }
417
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'] );
424 }
425
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 );
430 }
431
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 );
440 }
441
442 // Any remaining initial :s are illegal.
443 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
444 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
445 }
446
447 # Fill fields
448 $parts['dbkey'] = $dbkey;
449
450 return $parts;
451 }
452
453 /**
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()
458 *
459 * @return string Regex string
460 * @since 1.25
461 */
462 public static function getTitleInvalidRegex() {
463 static $rxTc = false;
464 if ( !$rxTc ) {
465 # Matching titles will be held as illegal.
466 $rxTc = '/' .
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.
471 '|%[0-9A-Fa-f]{2}' .
472 # XML/HTML character references produce similar issues.
473 '|&[A-Za-z0-9\x80-\xff]+;' .
474 '|&#[0-9]+;' .
475 '|&#x[0-9A-Fa-f]+;' .
476 '/S';
477 }
478
479 return $rxTc;
480 }
481 }