MediaWiki REL1_39
MediaWikiTitleCodec.php
Go to the documentation of this file.
1<?php
26use Wikimedia\IPUtils;
27
41 protected $language;
42
44 protected $genderCache;
45
48
51
53 protected $nsInfo;
54
62 private $createMalformedTitleException;
63
72 public function __construct(
73 Language $language,
74 GenderCache $genderCache,
75 $localInterwikis,
76 InterwikiLookup $interwikiLookup,
77 NamespaceInfo $nsInfo
78 ) {
79 $this->language = $language;
80 $this->genderCache = $genderCache;
81 $this->localInterwikis = (array)$localInterwikis;
82 $this->interwikiLookup = $interwikiLookup;
83 $this->nsInfo = $nsInfo;
84
85 // Default callback is to return a real MalformedTitleException,
86 // callback signature matches constructor
87 $this->createMalformedTitleException = static function (
88 $errorMessage,
89 $titleText = null,
90 $errorMessageParameters = []
92 return new MalformedTitleException( $errorMessage, $titleText, $errorMessageParameters );
93 };
94 }
95
100 public function overrideCreateMalformedTitleExceptionCallback( callable $callback ) {
101 // @codeCoverageIgnoreStart
102 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
103 throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
104 }
105 // @codeCoverageIgnoreEnd
106 $this->createMalformedTitleException = $callback;
107 }
108
118 public function getNamespaceName( $namespace, $text ) {
119 if ( $this->language->needsGenderDistinction() &&
120 $this->nsInfo->hasGenderDistinction( $namespace )
121 ) {
122 // NOTE: we are assuming here that the title text is a user name!
123 $gender = $this->genderCache->getGenderOf( $text, __METHOD__ );
124 $name = $this->language->getGenderNsText( $namespace, $gender );
125 } else {
126 $name = $this->language->getNsText( $namespace );
127 }
128
129 if ( $name === false ) {
130 throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
131 }
132
133 return $name;
134 }
135
148 public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
149 $out = '';
150 if ( $interwiki !== '' ) {
151 $out = $interwiki . ':';
152 }
153
154 if ( $namespace != 0 ) {
155 try {
156 $nsName = $this->getNamespaceName( $namespace, $text );
157 } catch ( InvalidArgumentException $e ) {
158 // See T165149. Awkward, but better than erroneously linking to the main namespace.
159 $nsName = $this->language->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$namespace}";
160 }
161
162 $out .= $nsName . ':';
163 }
164 $out .= $text;
165
166 if ( $fragment !== '' ) {
167 $out .= '#' . $fragment;
168 }
169
170 $out = str_replace( '_', ' ', $out );
171
172 return $out;
173 }
174
184 public function parseTitle( $text, $defaultNamespace = NS_MAIN ) {
185 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
186 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
187
188 // NOTE: this is an ugly kludge that allows this class to share the
189 // code for parsing with the old Title class. The parser code should
190 // be refactored to avoid this.
191 $parts = $this->splitTitleString( $filteredText, $defaultNamespace );
192
193 return new TitleValue(
194 $parts['namespace'],
195 $parts['dbkey'],
196 $parts['fragment'],
197 $parts['interwiki']
198 );
199 }
200
211 public function makeTitleValueSafe( $namespace, $text, $fragment = '', $interwiki = '' ) {
212 if ( !$this->nsInfo->exists( $namespace ) ) {
213 return null;
214 }
215
216 $canonicalNs = $this->nsInfo->getCanonicalName( $namespace );
217 $fullText = $canonicalNs == '' ? $text : "$canonicalNs:$text";
218 if ( strval( $interwiki ) != '' ) {
219 $fullText = "$interwiki:$fullText";
220 }
221 if ( strval( $fragment ) != '' ) {
222 $fullText .= '#' . $fragment;
223 }
224
225 try {
226 $parts = $this->splitTitleString( $fullText );
227 } catch ( MalformedTitleException $e ) {
228 return null;
229 }
230
231 return new TitleValue(
232 $parts['namespace'], $parts['dbkey'], $parts['fragment'], $parts['interwiki'] );
233 }
234
242 public function getText( $title ) {
243 if ( $title instanceof LinkTarget ) {
244 return $title->getText();
245 } elseif ( $title instanceof PageReference ) {
246 return strtr( $title->getDBKey(), '_', ' ' );
247 } else {
248 throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
249 }
250 }
251
260 public function getPrefixedText( $title ) {
261 if ( $title instanceof LinkTarget ) {
262 if ( !isset( $title->prefixedText ) ) {
263 $title->prefixedText = $this->formatTitle(
264 $title->getNamespace(),
265 $title->getText(),
266 '',
267 $title->getInterwiki()
268 );
269 }
270 return $title->prefixedText;
271 } elseif ( $title instanceof PageReference ) {
272 $title->assertWiki( PageReference::LOCAL );
273 return $this->formatTitle(
274 $title->getNamespace(),
275 $this->getText( $title )
276 );
277 } else {
278 throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
279 }
280 }
281
288 public function getPrefixedDBkey( $target ) {
289 if ( $target instanceof LinkTarget ) {
290 return strtr( $this->formatTitle(
291 $target->getNamespace(),
292 $target->getDBkey(),
293 '',
294 $target->getInterwiki()
295 ), ' ', '_' );
296 } elseif ( $target instanceof PageReference ) {
297 $target->assertWiki( PageReference::LOCAL );
298 return strtr( $this->formatTitle(
299 $target->getNamespace(),
300 $target->getDBkey()
301 ), ' ', '_' );
302 } else {
303 throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $target ) );
304 }
305 }
306
314 public function getFullText( $title ) {
315 if ( $title instanceof LinkTarget ) {
316 return $this->formatTitle(
317 $title->getNamespace(),
318 $title->getText(),
319 $title->getFragment(),
320 $title->getInterwiki()
321 );
322 } elseif ( $title instanceof PageReference ) {
323 $title->assertWiki( PageReference::LOCAL );
324 return $this->formatTitle(
325 $title->getNamespace(),
326 $this->getText( $title )
327 );
328 } else {
329 throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
330 }
331 }
332
354 public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
355 $dbkey = str_replace( ' ', '_', $text );
356
357 # Initialisation
358 $parts = [
359 'interwiki' => '',
360 'local_interwiki' => false,
361 'fragment' => '',
362 'namespace' => (int)$defaultNamespace,
363 'dbkey' => $dbkey,
364 ];
365
366 # Strip Unicode bidi override characters.
367 # Sometimes they slip into cut-n-pasted page titles, where the
368 # override chars get included in list displays.
369 $dbkey = preg_replace( '/[\x{200E}\x{200F}\x{202A}-\x{202E}]+/u', '', $dbkey );
370
371 if ( $dbkey === null ) {
372 # Regex had an error. Most likely this is caused by invalid UTF-8
373 $exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
374 throw $exception;
375 }
376
377 # Clean up whitespace
378 # Note: use of the /u option on preg_replace here will cause
379 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
380 # conveniently disabling them.
381 $dbkey = preg_replace(
382 '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
383 '_',
384 $dbkey
385 );
386 $dbkey = trim( $dbkey, '_' );
387
388 if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
389 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
390 $exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
391 throw $exception;
392 }
393
394 $parts['dbkey'] = $dbkey;
395
396 # Initial colon indicates main namespace rather than specified default
397 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
398 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
399 $parts['namespace'] = NS_MAIN;
400 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
401 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
402 }
403
404 if ( $dbkey == '' ) {
405 $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
406 throw $exception;
407 }
408
409 # Namespace or interwiki prefix
410 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
411 do {
412 $m = [];
413 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
414 $p = $m[1];
415 $ns = $this->language->getNsIndex( $p );
416 if ( $ns !== false ) {
417 # Ordinary namespace
418 $dbkey = $m[2];
419 $parts['namespace'] = $ns;
420 # For Talk:X pages, check if X has a "namespace" prefix
421 if ( $ns === NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
422 if ( $this->language->getNsIndex( $x[1] ) ) {
423 # Disallow Talk:File:x type titles...
424 $exception = ( $this->createMalformedTitleException )(
425 'title-invalid-talk-namespace',
426 $text
427 );
428 throw $exception;
429 } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
430 # Disallow Talk:Interwiki:x type titles...
431 $exception = ( $this->createMalformedTitleException )(
432 'title-invalid-talk-namespace',
433 $text
434 );
435 throw $exception;
436 }
437 }
438 } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
439 # Interwiki link
440 $dbkey = $m[2];
441 $parts['interwiki'] = $this->language->lc( $p );
442
443 # Redundant interwiki prefix to the local wiki
444 foreach ( $this->localInterwikis as $localIW ) {
445 if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
446 if ( $dbkey == '' ) {
447 # Empty self-links should point to the Main Page, to ensure
448 # compatibility with cross-wiki transclusions and the like.
449 $mainPage = Title::newMainPage();
450 return [
451 'interwiki' => $mainPage->getInterwiki(),
452 'local_interwiki' => true,
453 'fragment' => $mainPage->getFragment(),
454 'namespace' => $mainPage->getNamespace(),
455 'dbkey' => $mainPage->getDBkey(),
456 ];
457 }
458 $parts['interwiki'] = '';
459 # local interwikis should behave like initial-colon links
460 $parts['local_interwiki'] = true;
461
462 # Do another namespace split...
463 continue 2;
464 }
465 }
466
467 # If there's an initial colon after the interwiki, that also
468 # resets the default namespace
469 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
470 $parts['namespace'] = NS_MAIN;
471 $dbkey = substr( $dbkey, 1 );
472 $dbkey = trim( $dbkey, '_' );
473 }
474 }
475 # If there's no recognized interwiki or namespace,
476 # then let the colon expression be part of the title.
477 }
478 break;
479 } while ( true );
480
481 $fragment = strstr( $dbkey, '#' );
482 if ( $fragment !== false ) {
483 $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
484 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
485 # remove whitespace again: prevents "Foo_bar_#"
486 # becoming "Foo_bar_"
487 $dbkey = preg_replace( '/_*$/', '', $dbkey );
488 }
489
490 # Reject illegal characters.
491 $rxTc = self::getTitleInvalidRegex();
492 $matches = [];
493 if ( preg_match( $rxTc, $dbkey, $matches ) ) {
494 $exception = ( $this->createMalformedTitleException )( 'title-invalid-characters', $text, [ $matches[0] ] );
495 throw $exception;
496 }
497
498 # Pages with "/./" or "/../" appearing in the URLs will often be un-
499 # reachable due to the way web browsers deal with 'relative' URLs.
500 # Also, they conflict with subpage syntax. Forbid them explicitly.
501 if (
502 strpos( $dbkey, '.' ) !== false &&
503 (
504 $dbkey === '.' || $dbkey === '..' ||
505 strpos( $dbkey, './' ) === 0 ||
506 strpos( $dbkey, '../' ) === 0 ||
507 strpos( $dbkey, '/./' ) !== false ||
508 strpos( $dbkey, '/../' ) !== false ||
509 substr( $dbkey, -2 ) == '/.' ||
510 substr( $dbkey, -3 ) == '/..'
511 )
512 ) {
513 $exception = ( $this->createMalformedTitleException )( 'title-invalid-relative', $text );
514 throw $exception;
515 }
516
517 # Magic tilde sequences? Nu-uh!
518 if ( strpos( $dbkey, '~~~' ) !== false ) {
519 $exception = ( $this->createMalformedTitleException )( 'title-invalid-magic-tilde', $text );
520 throw $exception;
521 }
522
523 # Limit the size of titles to 255 bytes. This is typically the size of the
524 # underlying database field. We make an exception for special pages, which
525 # don't need to be stored in the database, and may edge over 255 bytes due
526 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
527 $maxLength = ( $parts['namespace'] !== NS_SPECIAL ) ? 255 : 512;
528 if ( strlen( $dbkey ) > $maxLength ) {
529 $exception = ( $this->createMalformedTitleException )(
530 'title-invalid-too-long',
531 $text,
532 [ Message::numParam( $maxLength ) ]
533 );
534 throw $exception;
535 }
536
537 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
538 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
539 # other site might be case-sensitive.
540 if ( $parts['interwiki'] === '' && $this->nsInfo->isCapitalized( $parts['namespace'] ) ) {
541 $dbkey = $this->language->ucfirst( $dbkey );
542 }
543
544 # Can't make a link to a namespace alone... "empty" local links can only be
545 # self-links with a fragment identifier.
546 if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] !== NS_MAIN ) {
547 $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
548 throw $exception;
549 }
550
551 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
552 // IP names are not allowed for accounts, and can only be referring to
553 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
554 // there are numerous ways to present the same IP. Having sp:contribs scan
555 // them all is silly and having some show the edits and others not is
556 // inconsistent. Same for talk/userpages. Keep them normalized instead.
557 if ( $parts['namespace'] === NS_USER || $parts['namespace'] === NS_USER_TALK ) {
558 $dbkey = IPUtils::sanitizeIP( $dbkey );
559 // IPUtils::sanitizeIP return null only for bad input
560 '@phan-var string $dbkey';
561 }
562
563 // Any remaining initial :s are illegal.
564 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
565 $exception = ( $this->createMalformedTitleException )( 'title-invalid-leading-colon', $text );
566 throw $exception;
567 }
568
569 // Fill fields
570 $parts['dbkey'] = $dbkey;
571
572 // Check to ensure that the return value can be used to construct a TitleValue.
573 // All issues should in theory be caught above, this is here to enforce consistency.
574 try {
575 TitleValue::assertValidSpec(
576 $parts['namespace'],
577 $parts['dbkey'],
578 $parts['fragment'],
579 $parts['interwiki']
580 );
581 } catch ( InvalidArgumentException $ex ) {
582 $exception = ( $this->createMalformedTitleException )( 'title-invalid', $text, [ $ex->getMessage() ] );
583 throw $exception;
584 }
585
586 return $parts;
587 }
588
598 public static function getTitleInvalidRegex() {
599 static $rxTc = false;
600 if ( !$rxTc ) {
601 # Matching titles will be held as illegal.
602 $rxTc = '/' .
603 # Any character not allowed is forbidden...
604 '[^' . Title::legalChars() . ']' .
605 # URL percent encoding sequences interfere with the ability
606 # to round-trip titles -- you can't link to them consistently.
607 '|%[0-9A-Fa-f]{2}' .
608 # XML/HTML character references produce similar issues.
609 '|&[A-Za-z0-9\x80-\xff]+;' .
610 '/S';
611 }
612
613 return $rxTc;
614 }
615}
const NS_USER
Definition Defines.php:66
const NS_MAIN
Definition Defines.php:64
const NS_SPECIAL
Definition Defines.php:53
const NS_TALK
Definition Defines.php:65
const NS_USER_TALK
Definition Defines.php:67
Caches user genders when needed to use correct namespace aliases.
Base class for language-specific code.
Definition Language.php:53
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
A codec for MediaWiki page titles.
static getTitleInvalidRegex()
Returns a simple regex that will match on characters and sequences invalid in titles.
splitTitleString( $text, $defaultNamespace=NS_MAIN)
Validates, normalizes and splits a title string.
overrideCreateMalformedTitleExceptionCallback(callable $callback)
formatTitle( $namespace, $text, $fragment='', $interwiki='')
__construct(Language $language, GenderCache $genderCache, $localInterwikis, InterwikiLookup $interwikiLookup, NamespaceInfo $nsInfo)
InterwikiLookup $interwikiLookup
getNamespaceName( $namespace, $text)
parseTitle( $text, $defaultNamespace=NS_MAIN)
Parses the given text and constructs a TitleValue.
makeTitleValueSafe( $namespace, $text, $fragment='', $interwiki='')
Given a namespace and title, return a TitleValue if valid, or null if invalid.
static numParam( $num)
Definition Message.php:1145
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a page (or page fragment) title within MediaWiki.
Service interface for looking up Interwiki records.
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
A title formatter service for MediaWiki.
A title parser service for MediaWiki.