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