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