Merge "Warn if stateful ParserOutput transforms are used"
[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
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 if ( $namespace !== false ) {
116 // Try to get a namespace name, but fallback
117 // to empty string if it doesn't exist
118 try {
119 $nsName = $this->getNamespaceName( $namespace, $text );
120 } catch ( InvalidArgumentException $e ) {
121 $nsName = '';
122 }
123
124 if ( $namespace !== 0 ) {
125 $text = $nsName . ':' . $text;
126 }
127 }
128
129 if ( $fragment !== '' ) {
130 $text = $text . '#' . $fragment;
131 }
132
133 if ( $interwiki !== '' ) {
134 $text = $interwiki . ':' . $text;
135 }
136
137 $text = str_replace( '_', ' ', $text );
138
139 return $text;
140 }
141
142 /**
143 * Parses the given text and constructs a TitleValue. Normalization
144 * is applied according to the rules appropriate for the form specified by $form.
145 *
146 * @param string $text The text to parse
147 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
148 *
149 * @throws MalformedTitleException
150 * @return TitleValue
151 */
152 public function parseTitle( $text, $defaultNamespace ) {
153 // NOTE: this is an ugly cludge that allows this class to share the
154 // code for parsing with the old Title class. The parser code should
155 // be refactored to avoid this.
156 $parts = $this->splitTitleString( $text, $defaultNamespace );
157
158 // Relative fragment links are not supported by TitleValue
159 if ( $parts['dbkey'] === '' ) {
160 throw new MalformedTitleException( 'title-invalid-empty', $text );
161 }
162
163 return new TitleValue(
164 $parts['namespace'],
165 $parts['dbkey'],
166 $parts['fragment'],
167 $parts['interwiki']
168 );
169 }
170
171 /**
172 * @see TitleFormatter::getText()
173 *
174 * @param LinkTarget $title
175 *
176 * @return string $title->getText()
177 */
178 public function getText( LinkTarget $title ) {
179 return $this->formatTitle( false, $title->getText(), '' );
180 }
181
182 /**
183 * @see TitleFormatter::getText()
184 *
185 * @param LinkTarget $title
186 *
187 * @return string
188 */
189 public function getPrefixedText( LinkTarget $title ) {
190 return $this->formatTitle(
191 $title->getNamespace(),
192 $title->getText(),
193 '',
194 $title->getInterwiki()
195 );
196 }
197
198 /**
199 * @since 1.27
200 * @see TitleFormatter::getPrefixedDBkey()
201 * @param LinkTarget $target
202 * @return string
203 */
204 public function getPrefixedDBkey( LinkTarget $target ) {
205 $key = '';
206 if ( $target->isExternal() ) {
207 $key .= $target->getInterwiki() . ':';
208 }
209 // Try to get a namespace name, but fallback
210 // to empty string if it doesn't exist
211 try {
212 $nsName = $this->getNamespaceName(
213 $target->getNamespace(),
214 $target->getText()
215 );
216 } catch ( InvalidArgumentException $e ) {
217 $nsName = '';
218 }
219
220 if ( $target->getNamespace() !== 0 ) {
221 $key .= $nsName . ':';
222 }
223
224 $key .= $target->getText();
225
226 return strtr( $key, ' ', '_' );
227 }
228
229 /**
230 * @see TitleFormatter::getText()
231 *
232 * @param LinkTarget $title
233 *
234 * @return string
235 */
236 public function getFullText( LinkTarget $title ) {
237 return $this->formatTitle(
238 $title->getNamespace(),
239 $title->getText(),
240 $title->getFragment(),
241 $title->getInterwiki()
242 );
243 }
244
245 /**
246 * Normalizes and splits a title string.
247 *
248 * This function removes illegal characters, splits off the interwiki and
249 * namespace prefixes, sets the other forms, and canonicalizes
250 * everything.
251 *
252 * @todo this method is only exposed as a temporary measure to ease refactoring.
253 * It was copied with minimal changes from Title::secureAndSplit().
254 *
255 * @todo This method should be split up and an appropriate interface
256 * defined for use by the Title class.
257 *
258 * @param string $text
259 * @param int $defaultNamespace
260 *
261 * @throws MalformedTitleException If $text is not a valid title string.
262 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
263 * 'user_case_dbkey', and 'dbkey'.
264 */
265 public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
266 $dbkey = str_replace( ' ', '_', $text );
267
268 # Initialisation
269 $parts = [
270 'interwiki' => '',
271 'local_interwiki' => false,
272 'fragment' => '',
273 'namespace' => $defaultNamespace,
274 'dbkey' => $dbkey,
275 'user_case_dbkey' => $dbkey,
276 ];
277
278 # Strip Unicode bidi override characters.
279 # Sometimes they slip into cut-n-pasted page titles, where the
280 # override chars get included in list displays.
281 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
282
283 # Clean up whitespace
284 # Note: use of the /u option on preg_replace here will cause
285 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
286 # conveniently disabling them.
287 $dbkey = preg_replace(
288 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
289 '_',
290 $dbkey
291 );
292 $dbkey = trim( $dbkey, '_' );
293
294 if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
295 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
296 throw new MalformedTitleException( 'title-invalid-utf8', $text );
297 }
298
299 $parts['dbkey'] = $dbkey;
300
301 # Initial colon indicates main namespace rather than specified default
302 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
303 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
304 $parts['namespace'] = NS_MAIN;
305 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
306 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
307 }
308
309 if ( $dbkey == '' ) {
310 throw new MalformedTitleException( 'title-invalid-empty', $text );
311 }
312
313 # Namespace or interwiki prefix
314 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
315 do {
316 $m = [];
317 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
318 $p = $m[1];
319 $ns = $this->language->getNsIndex( $p );
320 if ( $ns !== false ) {
321 # Ordinary namespace
322 $dbkey = $m[2];
323 $parts['namespace'] = $ns;
324 # For Talk:X pages, check if X has a "namespace" prefix
325 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
326 if ( $this->language->getNsIndex( $x[1] ) ) {
327 # Disallow Talk:File:x type titles...
328 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
329 } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
330 # Disallow Talk:Interwiki:x type titles...
331 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
332 }
333 }
334 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
335 # Interwiki link
336 $dbkey = $m[2];
337 $parts['interwiki'] = $this->language->lc( $p );
338
339 # Redundant interwiki prefix to the local wiki
340 foreach ( $this->localInterwikis as $localIW ) {
341 if ( 0 == strcasecmp( $parts['interwiki'], $localIW ) ) {
342 if ( $dbkey == '' ) {
343 # Empty self-links should point to the Main Page, to ensure
344 # compatibility with cross-wiki transclusions and the like.
345 $mainPage = Title::newMainPage();
346 return [
347 'interwiki' => $mainPage->getInterwiki(),
348 'local_interwiki' => true,
349 'fragment' => $mainPage->getFragment(),
350 'namespace' => $mainPage->getNamespace(),
351 'dbkey' => $mainPage->getDBkey(),
352 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
353 ];
354 }
355 $parts['interwiki'] = '';
356 # local interwikis should behave like initial-colon links
357 $parts['local_interwiki'] = true;
358
359 # Do another namespace split...
360 continue 2;
361 }
362 }
363
364 # If there's an initial colon after the interwiki, that also
365 # resets the default namespace
366 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
367 $parts['namespace'] = NS_MAIN;
368 $dbkey = substr( $dbkey, 1 );
369 $dbkey = trim( $dbkey, '_' );
370 }
371 }
372 # If there's no recognized interwiki or namespace,
373 # then let the colon expression be part of the title.
374 }
375 break;
376 } while ( true );
377
378 $fragment = strstr( $dbkey, '#' );
379 if ( false !== $fragment ) {
380 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
381 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
382 # remove whitespace again: prevents "Foo_bar_#"
383 # becoming "Foo_bar_"
384 $dbkey = preg_replace( '/_*$/', '', $dbkey );
385 }
386
387 # Reject illegal characters.
388 $rxTc = self::getTitleInvalidRegex();
389 $matches = [];
390 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
391 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
392 }
393
394 # Pages with "/./" or "/../" appearing in the URLs will often be un-
395 # reachable due to the way web browsers deal with 'relative' URLs.
396 # Also, they conflict with subpage syntax. Forbid them explicitly.
397 if (
398 strpos( $dbkey, '.' ) !== false &&
399 (
400 $dbkey === '.' || $dbkey === '..' ||
401 strpos( $dbkey, './' ) === 0 ||
402 strpos( $dbkey, '../' ) === 0 ||
403 strpos( $dbkey, '/./' ) !== false ||
404 strpos( $dbkey, '/../' ) !== false ||
405 substr( $dbkey, -2 ) == '/.' ||
406 substr( $dbkey, -3 ) == '/..'
407 )
408 ) {
409 throw new MalformedTitleException( 'title-invalid-relative', $text );
410 }
411
412 # Magic tilde sequences? Nu-uh!
413 if ( strpos( $dbkey, '~~~' ) !== false ) {
414 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
415 }
416
417 # Limit the size of titles to 255 bytes. This is typically the size of the
418 # underlying database field. We make an exception for special pages, which
419 # don't need to be stored in the database, and may edge over 255 bytes due
420 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
421 $maxLength = ( $parts['namespace'] != NS_SPECIAL ) ? 255 : 512;
422 if ( strlen( $dbkey ) > $maxLength ) {
423 throw new MalformedTitleException( 'title-invalid-too-long', $text,
424 [ Message::numParam( $maxLength ) ] );
425 }
426
427 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
428 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
429 # other site might be case-sensitive.
430 $parts['user_case_dbkey'] = $dbkey;
431 if ( $parts['interwiki'] === '' ) {
432 $dbkey = Title::capitalize( $dbkey, $parts['namespace'] );
433 }
434
435 # Can't make a link to a namespace alone... "empty" local links can only be
436 # self-links with a fragment identifier.
437 if ( $dbkey == '' && $parts['interwiki'] === '' ) {
438 if ( $parts['namespace'] != NS_MAIN ) {
439 throw new MalformedTitleException( 'title-invalid-empty', $text );
440 }
441 }
442
443 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
444 // IP names are not allowed for accounts, and can only be referring to
445 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
446 // there are numerous ways to present the same IP. Having sp:contribs scan
447 // them all is silly and having some show the edits and others not is
448 // inconsistent. Same for talk/userpages. Keep them normalized instead.
449 if ( $parts['namespace'] == NS_USER || $parts['namespace'] == NS_USER_TALK ) {
450 $dbkey = IP::sanitizeIP( $dbkey );
451 }
452
453 // Any remaining initial :s are illegal.
454 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
455 throw new MalformedTitleException( 'title-invalid-leading-colon', $text );
456 }
457
458 # Fill fields
459 $parts['dbkey'] = $dbkey;
460
461 return $parts;
462 }
463
464 /**
465 * Returns a simple regex that will match on characters and sequences invalid in titles.
466 * Note that this doesn't pick up many things that could be wrong with titles, but that
467 * replacing this regex with something valid will make many titles valid.
468 * Previously Title::getTitleInvalidRegex()
469 *
470 * @return string Regex string
471 * @since 1.25
472 */
473 public static function getTitleInvalidRegex() {
474 static $rxTc = false;
475 if ( !$rxTc ) {
476 # Matching titles will be held as illegal.
477 $rxTc = '/' .
478 # Any character not allowed is forbidden...
479 '[^' . Title::legalChars() . ']' .
480 # URL percent encoding sequences interfere with the ability
481 # to round-trip titles -- you can't link to them consistently.
482 '|%[0-9A-Fa-f]{2}' .
483 # XML/HTML character references produce similar issues.
484 '|&[A-Za-z0-9\x80-\xff]+;' .
485 '|&#[0-9]+;' .
486 '|&#x[0-9A-Fa-f]+;' .
487 '/S';
488 }
489
490 return $rxTc;
491 }
492 }