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