MediaWiki  master
MediaWikiTitleCodec.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\IPUtils;
27 
41  protected $language;
42 
44  protected $genderCache;
45 
47  protected $localInterwikis;
48 
50  protected $interwikiLookup;
51 
53  protected $nsInfo;
54 
63 
72  public function __construct(
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  # Clean up whitespace
372  # Note: use of the /u option on preg_replace here will cause
373  # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
374  # conveniently disabling them.
375  $dbkey = preg_replace(
376  '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
377  '_',
378  $dbkey
379  );
380  $dbkey = trim( $dbkey, '_' );
381 
382  if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
383  # Contained illegal UTF-8 sequences or forbidden Unicode chars.
384  $exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
385  throw $exception;
386  }
387 
388  $parts['dbkey'] = $dbkey;
389 
390  # Initial colon indicates main namespace rather than specified default
391  # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
392  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
393  $parts['namespace'] = NS_MAIN;
394  $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
395  $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
396  }
397 
398  if ( $dbkey == '' ) {
399  $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
400  throw $exception;
401  }
402 
403  # Namespace or interwiki prefix
404  $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
405  do {
406  $m = [];
407  if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
408  $p = $m[1];
409  $ns = $this->language->getNsIndex( $p );
410  if ( $ns !== false ) {
411  # Ordinary namespace
412  $dbkey = $m[2];
413  $parts['namespace'] = $ns;
414  # For Talk:X pages, check if X has a "namespace" prefix
415  if ( $ns === NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
416  if ( $this->language->getNsIndex( $x[1] ) ) {
417  # Disallow Talk:File:x type titles...
418  $exception = ( $this->createMalformedTitleException )(
419  'title-invalid-talk-namespace',
420  $text
421  );
422  throw $exception;
423  } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
424  # Disallow Talk:Interwiki:x type titles...
425  $exception = ( $this->createMalformedTitleException )(
426  'title-invalid-talk-namespace',
427  $text
428  );
429  throw $exception;
430  }
431  }
432  } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
433  # Interwiki link
434  $dbkey = $m[2];
435  $parts['interwiki'] = $this->language->lc( $p );
436 
437  # Redundant interwiki prefix to the local wiki
438  foreach ( $this->localInterwikis as $localIW ) {
439  if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
440  if ( $dbkey == '' ) {
441  # Empty self-links should point to the Main Page, to ensure
442  # compatibility with cross-wiki transclusions and the like.
443  $mainPage = Title::newMainPage();
444  return [
445  'interwiki' => $mainPage->getInterwiki(),
446  'local_interwiki' => true,
447  'fragment' => $mainPage->getFragment(),
448  'namespace' => $mainPage->getNamespace(),
449  'dbkey' => $mainPage->getDBkey(),
450  ];
451  }
452  $parts['interwiki'] = '';
453  # local interwikis should behave like initial-colon links
454  $parts['local_interwiki'] = true;
455 
456  # Do another namespace split...
457  continue 2;
458  }
459  }
460 
461  # If there's an initial colon after the interwiki, that also
462  # resets the default namespace
463  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
464  $parts['namespace'] = NS_MAIN;
465  $dbkey = substr( $dbkey, 1 );
466  $dbkey = trim( $dbkey, '_' );
467  }
468  }
469  # If there's no recognized interwiki or namespace,
470  # then let the colon expression be part of the title.
471  }
472  break;
473  } while ( true );
474 
475  $fragment = strstr( $dbkey, '#' );
476  if ( $fragment !== false ) {
477  $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
478  $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
479  # remove whitespace again: prevents "Foo_bar_#"
480  # becoming "Foo_bar_"
481  $dbkey = preg_replace( '/_*$/', '', $dbkey );
482  }
483 
484  # Reject illegal characters.
485  $rxTc = self::getTitleInvalidRegex();
486  $matches = [];
487  if ( preg_match( $rxTc, $dbkey, $matches ) ) {
488  $exception = ( $this->createMalformedTitleException )( 'title-invalid-characters', $text, [ $matches[0] ] );
489  throw $exception;
490  }
491 
492  # Pages with "/./" or "/../" appearing in the URLs will often be un-
493  # reachable due to the way web browsers deal with 'relative' URLs.
494  # Also, they conflict with subpage syntax. Forbid them explicitly.
495  if (
496  strpos( $dbkey, '.' ) !== false &&
497  (
498  $dbkey === '.' || $dbkey === '..' ||
499  strpos( $dbkey, './' ) === 0 ||
500  strpos( $dbkey, '../' ) === 0 ||
501  strpos( $dbkey, '/./' ) !== false ||
502  strpos( $dbkey, '/../' ) !== false ||
503  substr( $dbkey, -2 ) == '/.' ||
504  substr( $dbkey, -3 ) == '/..'
505  )
506  ) {
507  $exception = ( $this->createMalformedTitleException )( 'title-invalid-relative', $text );
508  throw $exception;
509  }
510 
511  # Magic tilde sequences? Nu-uh!
512  if ( strpos( $dbkey, '~~~' ) !== false ) {
513  $exception = ( $this->createMalformedTitleException )( 'title-invalid-magic-tilde', $text );
514  throw $exception;
515  }
516 
517  # Limit the size of titles to 255 bytes. This is typically the size of the
518  # underlying database field. We make an exception for special pages, which
519  # don't need to be stored in the database, and may edge over 255 bytes due
520  # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
521  $maxLength = ( $parts['namespace'] !== NS_SPECIAL ) ? 255 : 512;
522  if ( strlen( $dbkey ) > $maxLength ) {
523  $exception = ( $this->createMalformedTitleException )(
524  'title-invalid-too-long',
525  $text,
526  [ Message::numParam( $maxLength ) ]
527  );
528  throw $exception;
529  }
530 
531  # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
532  # and [[Foo]] point to the same place. Don't force it for interwikis, since the
533  # other site might be case-sensitive.
534  if ( $parts['interwiki'] === '' && $this->nsInfo->isCapitalized( $parts['namespace'] ) ) {
535  $dbkey = $this->language->ucfirst( $dbkey );
536  }
537 
538  # Can't make a link to a namespace alone... "empty" local links can only be
539  # self-links with a fragment identifier.
540  if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] !== NS_MAIN ) {
541  $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
542  throw $exception;
543  }
544 
545  // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
546  // IP names are not allowed for accounts, and can only be referring to
547  // edits from the IP. Given '::' abbreviations and caps/lowercaps,
548  // there are numerous ways to present the same IP. Having sp:contribs scan
549  // them all is silly and having some show the edits and others not is
550  // inconsistent. Same for talk/userpages. Keep them normalized instead.
551  if ( $parts['namespace'] === NS_USER || $parts['namespace'] === NS_USER_TALK ) {
552  $dbkey = IPUtils::sanitizeIP( $dbkey );
553  }
554 
555  // Any remaining initial :s are illegal.
556  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
557  $exception = ( $this->createMalformedTitleException )( 'title-invalid-leading-colon', $text );
558  throw $exception;
559  }
560 
561  // Fill fields
562  $parts['dbkey'] = $dbkey;
563 
564  // Check to ensure that the return value can be used to construct a TitleValue.
565  // All issues should in theory be caught above, this is here to enforce consistency.
566  try {
568  $parts['namespace'],
569  $parts['dbkey'],
570  $parts['fragment'],
571  $parts['interwiki']
572  );
573  } catch ( InvalidArgumentException $ex ) {
574  $exception = ( $this->createMalformedTitleException )( 'title-invalid', $text, [ $ex->getMessage() ] );
575  throw $exception;
576  }
577 
578  return $parts;
579  }
580 
590  public static function getTitleInvalidRegex() {
591  static $rxTc = false;
592  if ( !$rxTc ) {
593  # Matching titles will be held as illegal.
594  $rxTc = '/' .
595  # Any character not allowed is forbidden...
596  '[^' . Title::legalChars() . ']' .
597  # URL percent encoding sequences interfere with the ability
598  # to round-trip titles -- you can't link to them consistently.
599  '|%[0-9A-Fa-f]{2}' .
600  # XML/HTML character references produce similar issues.
601  '|&[A-Za-z0-9\x80-\xff]+;' .
602  '|&#[0-9]+;' .
603  '|&#x[0-9A-Fa-f]+;' .
604  '/S';
605  }
606 
607  return $rxTc;
608  }
609 }
MediaWikiTitleCodec\getText
getText( $title)
Definition: MediaWikiTitleCodec.php:242
Message\numParam
static numParam( $num)
Definition: Message.php:1127
MediaWikiTitleCodec
A codec for MediaWiki page titles.
Definition: MediaWikiTitleCodec.php:39
MediaWikiTitleCodec\getTitleInvalidRegex
static getTitleInvalidRegex()
Returns a simple regex that will match on characters and sequences invalid in titles.
Definition: MediaWikiTitleCodec.php:590
GenderCache
Caches user genders when needed to use correct namespace aliases.
Definition: GenderCache.php:36
MediaWikiTitleCodec\splitTitleString
splitTitleString( $text, $defaultNamespace=NS_MAIN)
Validates, normalizes and splits a title string.
Definition: MediaWikiTitleCodec.php:354
Sanitizer\decodeCharReferencesAndNormalize
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
Definition: Sanitizer.php:1245
MediaWikiTitleCodec\makeTitleValueSafe
makeTitleValueSafe( $namespace, $text, $fragment='', $interwiki='')
Given a namespace and title, return a TitleValue if valid, or null if invalid.
Definition: MediaWikiTitleCodec.php:211
Title\newMainPage
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:728
MediaWikiTitleCodec\getNamespaceName
getNamespaceName( $namespace, $text)
Definition: MediaWikiTitleCodec.php:118
Page\PageReference
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Definition: PageReference.php:49
MediaWikiTitleCodec\parseTitle
parseTitle( $text, $defaultNamespace=NS_MAIN)
Parses the given text and constructs a TitleValue.
Definition: MediaWikiTitleCodec.php:184
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
$matches
$matches
Definition: NoLocalSettings.php:24
MediaWikiTitleCodec\getPrefixedDBkey
getPrefixedDBkey( $target)
Definition: MediaWikiTitleCodec.php:288
MediaWiki\Interwiki\InterwikiLookup
Service interface for looking up Interwiki records.
Definition: InterwikiLookup.php:32
MediaWikiTitleCodec\formatTitle
formatTitle( $namespace, $text, $fragment='', $interwiki='')
Definition: MediaWikiTitleCodec.php:148
MediaWikiTitleCodec\$createMalformedTitleException
callable $createMalformedTitleException
The code here can throw MalformedTitleException, which cannot be created in unit tests (see T281935).
Definition: MediaWikiTitleCodec.php:62
MediaWikiTitleCodec\$localInterwikis
string[] $localInterwikis
Definition: MediaWikiTitleCodec.php:47
$title
$title
Definition: testCompression.php:38
TitleParser
A title parser service for MediaWiki.
Definition: TitleParser.php:33
NS_TALK
const NS_TALK
Definition: Defines.php:65
TitleValue\assertValidSpec
static assertValidSpec( $namespace, $title, $fragment='', $interwiki='')
Asserts that the given parameters could be used to construct a TitleValue object.
Definition: TitleValue.php:173
MediaWikiTitleCodec\overrideCreateMalformedTitleExceptionCallback
overrideCreateMalformedTitleExceptionCallback(callable $callback)
Definition: MediaWikiTitleCodec.php:100
MediaWikiTitleCodec\$interwikiLookup
InterwikiLookup $interwikiLookup
Definition: MediaWikiTitleCodec.php:50
NS_USER
const NS_USER
Definition: Defines.php:66
MediaWikiTitleCodec\$genderCache
GenderCache $genderCache
Definition: MediaWikiTitleCodec.php:44
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:26
MediaWikiTitleCodec\getFullText
getFullText( $title)
Definition: MediaWikiTitleCodec.php:314
TitleFormatter
A title formatter service for MediaWiki.
Definition: TitleFormatter.php:35
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:67
MediaWikiTitleCodec\$nsInfo
NamespaceInfo $nsInfo
Definition: MediaWikiTitleCodec.php:53
NamespaceInfo
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Definition: NamespaceInfo.php:35
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:752
MediaWikiTitleCodec\getPrefixedText
getPrefixedText( $title)
Definition: MediaWikiTitleCodec.php:260
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
MediaWikiTitleCodec\$language
Language $language
Definition: MediaWikiTitleCodec.php:41
MediaWikiTitleCodec\__construct
__construct(Language $language, GenderCache $genderCache, $localInterwikis, InterwikiLookup $interwikiLookup, NamespaceInfo $nsInfo)
Definition: MediaWikiTitleCodec.php:72
TitleValue
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40