Update MediaWikiTitleCodec to use NamespaceInfo
[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 * @var NamespaceInfo
61 */
62 protected $nsInfo;
63
64 /**
65 * @param Language $language The language object to use for localizing namespace names.
66 * @param GenderCache $genderCache The gender cache for generating gendered namespace names
67 * @param string[]|string $localInterwikis
68 * @param InterwikiLookup|null $interwikiLookup
69 * @param NamespaceInfo|null $nsInfo
70 */
71 public function __construct( Language $language, GenderCache $genderCache,
72 $localInterwikis = [], InterwikiLookup $interwikiLookup = null,
73 NamespaceInfo $nsInfo = null
74 ) {
75 if ( !$interwikiLookup ) {
76 wfDeprecated( __METHOD__ . ' with no InterwikiLookup argument', '1.34' );
77 $interwikiLookup = MediaWikiServices::getInstance()->getInterwikiLookup();
78 }
79 if ( !$nsInfo ) {
80 wfDeprecated( __METHOD__ . ' with no NamespaceInfo argument', '1.34' );
81 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
82 }
83 $this->language = $language;
84 $this->genderCache = $genderCache;
85 $this->localInterwikis = (array)$localInterwikis;
86 $this->interwikiLookup = $interwikiLookup;
87 $this->nsInfo = $nsInfo;
88 }
89
90 /**
91 * @see TitleFormatter::getNamespaceName()
92 *
93 * @param int $namespace
94 * @param string $text
95 *
96 * @throws InvalidArgumentException If the namespace is invalid
97 * @return string Namespace name with underscores (not spaces)
98 */
99 public function getNamespaceName( $namespace, $text ) {
100 if ( $this->language->needsGenderDistinction() &&
101 $this->nsInfo->hasGenderDistinction( $namespace )
102 ) {
103 // NOTE: we are assuming here that the title text is a user name!
104 $gender = $this->genderCache->getGenderOf( $text, __METHOD__ );
105 $name = $this->language->getGenderNsText( $namespace, $gender );
106 } else {
107 $name = $this->language->getNsText( $namespace );
108 }
109
110 if ( $name === false ) {
111 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
112 }
113
114 return $name;
115 }
116
117 /**
118 * @see TitleFormatter::formatTitle()
119 *
120 * @param int|bool $namespace The namespace ID (or false, if the namespace should be ignored)
121 * @param string $text The page title. Should be valid. Only minimal normalization is applied.
122 * Underscores will be replaced.
123 * @param string $fragment The fragment name (may be empty).
124 * @param string $interwiki The interwiki name (may be empty).
125 *
126 * @throws InvalidArgumentException If the namespace is invalid
127 * @return string
128 */
129 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
130 $out = '';
131 if ( $interwiki !== '' ) {
132 $out = $interwiki . ':';
133 }
134
135 if ( $namespace != 0 ) {
136 try {
137 $nsName = $this->getNamespaceName( $namespace, $text );
138 } catch ( InvalidArgumentException $e ) {
139 // See T165149. Awkward, but better than erroneously linking to the main namespace.
140 $nsName = $this->language->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$namespace}";
141 }
142
143 $out .= $nsName . ':';
144 }
145 $out .= $text;
146
147 if ( $fragment !== '' ) {
148 $out .= '#' . $fragment;
149 }
150
151 $out = str_replace( '_', ' ', $out );
152
153 return $out;
154 }
155
156 /**
157 * Parses the given text and constructs a TitleValue. Normalization
158 * is applied according to the rules appropriate for the form specified by $form.
159 *
160 * @param string $text The text to parse
161 * @param int $defaultNamespace Namespace to assume per default (usually NS_MAIN)
162 *
163 * @throws MalformedTitleException
164 * @return TitleValue
165 */
166 public function parseTitle( $text, $defaultNamespace = NS_MAIN ) {
167 // NOTE: this is an ugly cludge that allows this class to share the
168 // code for parsing with the old Title class. The parser code should
169 // be refactored to avoid this.
170 $parts = $this->splitTitleString( $text, $defaultNamespace );
171
172 // Relative fragment links are not supported by TitleValue
173 if ( $parts['dbkey'] === '' ) {
174 throw new MalformedTitleException( 'title-invalid-empty', $text );
175 }
176
177 return new TitleValue(
178 $parts['namespace'],
179 $parts['dbkey'],
180 $parts['fragment'],
181 $parts['interwiki']
182 );
183 }
184
185 /**
186 * @see TitleFormatter::getText()
187 *
188 * @param LinkTarget $title
189 *
190 * @return string $title->getText()
191 */
192 public function getText( LinkTarget $title ) {
193 return $title->getText();
194 }
195
196 /**
197 * @see TitleFormatter::getText()
198 *
199 * @param LinkTarget $title
200 *
201 * @return string
202 */
203 public function getPrefixedText( LinkTarget $title ) {
204 if ( !isset( $title->prefixedText ) ) {
205 $title->prefixedText = $this->formatTitle(
206 $title->getNamespace(),
207 $title->getText(),
208 '',
209 $title->getInterwiki()
210 );
211 }
212
213 return $title->prefixedText;
214 }
215
216 /**
217 * @since 1.27
218 * @see TitleFormatter::getPrefixedDBkey()
219 * @param LinkTarget $target
220 * @return string
221 */
222 public function getPrefixedDBkey( LinkTarget $target ) {
223 return strtr( $this->formatTitle(
224 $target->getNamespace(),
225 $target->getDBkey(),
226 '',
227 $target->getInterwiki()
228 ), ' ', '_' );
229 }
230
231 /**
232 * @see TitleFormatter::getText()
233 *
234 * @param LinkTarget $title
235 *
236 * @return string
237 */
238 public function getFullText( LinkTarget $title ) {
239 return $this->formatTitle(
240 $title->getNamespace(),
241 $title->getText(),
242 $title->getFragment(),
243 $title->getInterwiki()
244 );
245 }
246
247 /**
248 * Normalizes and splits a title string.
249 *
250 * This function removes illegal characters, splits off the interwiki and
251 * namespace prefixes, sets the other forms, and canonicalizes
252 * everything.
253 *
254 * @todo this method is only exposed as a temporary measure to ease refactoring.
255 * It was copied with minimal changes from Title::secureAndSplit().
256 *
257 * @todo This method should be split up and an appropriate interface
258 * defined for use by the Title class.
259 *
260 * @param string $text
261 * @param int $defaultNamespace
262 *
263 * @throws MalformedTitleException If $text is not a valid title string.
264 * @return array A map with the fields 'interwiki', 'fragment', 'namespace',
265 * 'user_case_dbkey', and 'dbkey'.
266 */
267 public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
268 $dbkey = str_replace( ' ', '_', $text );
269
270 # Initialisation
271 $parts = [
272 'interwiki' => '',
273 'local_interwiki' => false,
274 'fragment' => '',
275 'namespace' => $defaultNamespace,
276 'dbkey' => $dbkey,
277 'user_case_dbkey' => $dbkey,
278 ];
279
280 # Strip Unicode bidi override characters.
281 # Sometimes they slip into cut-n-pasted page titles, where the
282 # override chars get included in list displays.
283 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
284
285 # Clean up whitespace
286 # Note: use of the /u option on preg_replace here will cause
287 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
288 # conveniently disabling them.
289 $dbkey = preg_replace(
290 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
291 '_',
292 $dbkey
293 );
294 $dbkey = trim( $dbkey, '_' );
295
296 if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
297 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
298 throw new MalformedTitleException( 'title-invalid-utf8', $text );
299 }
300
301 $parts['dbkey'] = $dbkey;
302
303 # Initial colon indicates main namespace rather than specified default
304 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
305 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
306 $parts['namespace'] = NS_MAIN;
307 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
308 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
309 }
310
311 if ( $dbkey == '' ) {
312 throw new MalformedTitleException( 'title-invalid-empty', $text );
313 }
314
315 # Namespace or interwiki prefix
316 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
317 do {
318 $m = [];
319 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
320 $p = $m[1];
321 $ns = $this->language->getNsIndex( $p );
322 if ( $ns !== false ) {
323 # Ordinary namespace
324 $dbkey = $m[2];
325 $parts['namespace'] = $ns;
326 # For Talk:X pages, check if X has a "namespace" prefix
327 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
328 if ( $this->language->getNsIndex( $x[1] ) ) {
329 # Disallow Talk:File:x type titles...
330 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
331 } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
332 # Disallow Talk:Interwiki:x type titles...
333 throw new MalformedTitleException( 'title-invalid-talk-namespace', $text );
334 }
335 }
336 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
337 # Interwiki link
338 $dbkey = $m[2];
339 $parts['interwiki'] = $this->language->lc( $p );
340
341 # Redundant interwiki prefix to the local wiki
342 foreach ( $this->localInterwikis as $localIW ) {
343 if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
344 if ( $dbkey == '' ) {
345 # Empty self-links should point to the Main Page, to ensure
346 # compatibility with cross-wiki transclusions and the like.
347 $mainPage = Title::newMainPage();
348 return [
349 'interwiki' => $mainPage->getInterwiki(),
350 'local_interwiki' => true,
351 'fragment' => $mainPage->getFragment(),
352 'namespace' => $mainPage->getNamespace(),
353 'dbkey' => $mainPage->getDBkey(),
354 'user_case_dbkey' => $mainPage->getUserCaseDBKey()
355 ];
356 }
357 $parts['interwiki'] = '';
358 # local interwikis should behave like initial-colon links
359 $parts['local_interwiki'] = true;
360
361 # Do another namespace split...
362 continue 2;
363 }
364 }
365
366 # If there's an initial colon after the interwiki, that also
367 # resets the default namespace
368 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
369 $parts['namespace'] = NS_MAIN;
370 $dbkey = substr( $dbkey, 1 );
371 $dbkey = trim( $dbkey, '_' );
372 }
373 }
374 # If there's no recognized interwiki or namespace,
375 # then let the colon expression be part of the title.
376 }
377 break;
378 } while ( true );
379
380 $fragment = strstr( $dbkey, '#' );
381 if ( $fragment !== false ) {
382 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
383 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
384 # remove whitespace again: prevents "Foo_bar_#"
385 # becoming "Foo_bar_"
386 $dbkey = preg_replace( '/_*$/', '', $dbkey );
387 }
388
389 # Reject illegal characters.
390 $rxTc = self::getTitleInvalidRegex();
391 $matches = [];
392 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
393 throw new MalformedTitleException( 'title-invalid-characters', $text, [ $matches[0] ] );
394 }
395
396 # Pages with "/./" or "/../" appearing in the URLs will often be un-
397 # reachable due to the way web browsers deal with 'relative' URLs.
398 # Also, they conflict with subpage syntax. Forbid them explicitly.
399 if (
400 strpos( $dbkey, '.' ) !== false &&
401 (
402 $dbkey === '.' || $dbkey === '..' ||
403 strpos( $dbkey, './' ) === 0 ||
404 strpos( $dbkey, '../' ) === 0 ||
405 strpos( $dbkey, '/./' ) !== false ||
406 strpos( $dbkey, '/../' ) !== false ||
407 substr( $dbkey, -2 ) == '/.' ||
408 substr( $dbkey, -3 ) == '/..'
409 )
410 ) {
411 throw new MalformedTitleException( 'title-invalid-relative', $text );
412 }
413
414 # Magic tilde sequences? Nu-uh!
415 if ( strpos( $dbkey, '~~~' ) !== false ) {
416 throw new MalformedTitleException( 'title-invalid-magic-tilde', $text );
417 }
418
419 # Limit the size of titles to 255 bytes. This is typically the size of the
420 # underlying database field. We make an exception for special pages, which
421 # don't need to be stored in the database, and may edge over 255 bytes due
422 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
423 $maxLength = ( $parts['namespace'] != NS_SPECIAL ) ? 255 : 512;
424 if ( strlen( $dbkey ) > $maxLength ) {
425 throw new MalformedTitleException( 'title-invalid-too-long', $text,
426 [ Message::numParam( $maxLength ) ] );
427 }
428
429 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
430 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
431 # other site might be case-sensitive.
432 $parts['user_case_dbkey'] = $dbkey;
433 if ( $parts['interwiki'] === '' ) {
434 $dbkey = Title::capitalize( $dbkey, $parts['namespace'] );
435 }
436
437 # Can't make a link to a namespace alone... "empty" local links can only be
438 # self-links with a fragment identifier.
439 if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] != NS_MAIN ) {
440 throw new MalformedTitleException( 'title-invalid-empty', $text );
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 }