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 
62  private $createMalformedTitleException;
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  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  $dbkey = preg_replace(
379  '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
380  '_',
381  $dbkey
382  );
383  $dbkey = trim( $dbkey, '_' );
384 
385  if ( strpos( $dbkey, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
386  # Contained illegal UTF-8 sequences or forbidden Unicode chars.
387  $exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
388  throw $exception;
389  }
390 
391  $parts['dbkey'] = $dbkey;
392 
393  # Initial colon indicates main namespace rather than specified default
394  # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
395  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
396  $parts['namespace'] = NS_MAIN;
397  $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
398  $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
399  }
400 
401  if ( $dbkey == '' ) {
402  $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
403  throw $exception;
404  }
405 
406  # Namespace or interwiki prefix
407  $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
408  do {
409  $m = [];
410  if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
411  $p = $m[1];
412  $ns = $this->language->getNsIndex( $p );
413  if ( $ns !== false ) {
414  # Ordinary namespace
415  $dbkey = $m[2];
416  $parts['namespace'] = $ns;
417  # For Talk:X pages, check if X has a "namespace" prefix
418  if ( $ns === NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
419  if ( $this->language->getNsIndex( $x[1] ) ) {
420  # Disallow Talk:File:x type titles...
421  $exception = ( $this->createMalformedTitleException )(
422  'title-invalid-talk-namespace',
423  $text
424  );
425  throw $exception;
426  } elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
427  # Disallow Talk:Interwiki:x type titles...
428  $exception = ( $this->createMalformedTitleException )(
429  'title-invalid-talk-namespace',
430  $text
431  );
432  throw $exception;
433  }
434  }
435  } elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
436  # Interwiki link
437  $dbkey = $m[2];
438  $parts['interwiki'] = $this->language->lc( $p );
439 
440  # Redundant interwiki prefix to the local wiki
441  foreach ( $this->localInterwikis as $localIW ) {
442  if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
443  if ( $dbkey == '' ) {
444  # Empty self-links should point to the Main Page, to ensure
445  # compatibility with cross-wiki transclusions and the like.
446  $mainPage = Title::newMainPage();
447  return [
448  'interwiki' => $mainPage->getInterwiki(),
449  'local_interwiki' => true,
450  'fragment' => $mainPage->getFragment(),
451  'namespace' => $mainPage->getNamespace(),
452  'dbkey' => $mainPage->getDBkey(),
453  ];
454  }
455  $parts['interwiki'] = '';
456  # local interwikis should behave like initial-colon links
457  $parts['local_interwiki'] = true;
458 
459  # Do another namespace split...
460  continue 2;
461  }
462  }
463 
464  # If there's an initial colon after the interwiki, that also
465  # resets the default namespace
466  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
467  $parts['namespace'] = NS_MAIN;
468  $dbkey = substr( $dbkey, 1 );
469  $dbkey = trim( $dbkey, '_' );
470  }
471  }
472  # If there's no recognized interwiki or namespace,
473  # then let the colon expression be part of the title.
474  }
475  break;
476  } while ( true );
477 
478  $fragment = strstr( $dbkey, '#' );
479  if ( $fragment !== false ) {
480  $parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
481  $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
482  # remove whitespace again: prevents "Foo_bar_#"
483  # becoming "Foo_bar_"
484  $dbkey = preg_replace( '/_*$/', '', $dbkey );
485  }
486 
487  # Reject illegal characters.
488  $rxTc = self::getTitleInvalidRegex();
489  $matches = [];
490  if ( preg_match( $rxTc, $dbkey, $matches ) ) {
491  $exception = ( $this->createMalformedTitleException )( 'title-invalid-characters', $text, [ $matches[0] ] );
492  throw $exception;
493  }
494 
495  # Pages with "/./" or "/../" appearing in the URLs will often be un-
496  # reachable due to the way web browsers deal with 'relative' URLs.
497  # Also, they conflict with subpage syntax. Forbid them explicitly.
498  if (
499  strpos( $dbkey, '.' ) !== false &&
500  (
501  $dbkey === '.' || $dbkey === '..' ||
502  strpos( $dbkey, './' ) === 0 ||
503  strpos( $dbkey, '../' ) === 0 ||
504  strpos( $dbkey, '/./' ) !== false ||
505  strpos( $dbkey, '/../' ) !== false ||
506  substr( $dbkey, -2 ) == '/.' ||
507  substr( $dbkey, -3 ) == '/..'
508  )
509  ) {
510  $exception = ( $this->createMalformedTitleException )( 'title-invalid-relative', $text );
511  throw $exception;
512  }
513 
514  # Magic tilde sequences? Nu-uh!
515  if ( strpos( $dbkey, '~~~' ) !== false ) {
516  $exception = ( $this->createMalformedTitleException )( 'title-invalid-magic-tilde', $text );
517  throw $exception;
518  }
519 
520  # Limit the size of titles to 255 bytes. This is typically the size of the
521  # underlying database field. We make an exception for special pages, which
522  # don't need to be stored in the database, and may edge over 255 bytes due
523  # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
524  $maxLength = ( $parts['namespace'] !== NS_SPECIAL ) ? 255 : 512;
525  if ( strlen( $dbkey ) > $maxLength ) {
526  $exception = ( $this->createMalformedTitleException )(
527  'title-invalid-too-long',
528  $text,
529  [ Message::numParam( $maxLength ) ]
530  );
531  throw $exception;
532  }
533 
534  # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
535  # and [[Foo]] point to the same place. Don't force it for interwikis, since the
536  # other site might be case-sensitive.
537  if ( $parts['interwiki'] === '' && $this->nsInfo->isCapitalized( $parts['namespace'] ) ) {
538  $dbkey = $this->language->ucfirst( $dbkey );
539  }
540 
541  # Can't make a link to a namespace alone... "empty" local links can only be
542  # self-links with a fragment identifier.
543  if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] !== NS_MAIN ) {
544  $exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
545  throw $exception;
546  }
547 
548  // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
549  // IP names are not allowed for accounts, and can only be referring to
550  // edits from the IP. Given '::' abbreviations and caps/lowercaps,
551  // there are numerous ways to present the same IP. Having sp:contribs scan
552  // them all is silly and having some show the edits and others not is
553  // inconsistent. Same for talk/userpages. Keep them normalized instead.
554  if ( $parts['namespace'] === NS_USER || $parts['namespace'] === NS_USER_TALK ) {
555  $dbkey = IPUtils::sanitizeIP( $dbkey );
556  // IPUtils::sanitizeIP return null only for bad input
557  '@phan-var string $dbkey';
558  }
559 
560  // Any remaining initial :s are illegal.
561  if ( $dbkey !== '' && $dbkey[0] == ':' ) {
562  $exception = ( $this->createMalformedTitleException )( 'title-invalid-leading-colon', $text );
563  throw $exception;
564  }
565 
566  // Fill fields
567  $parts['dbkey'] = $dbkey;
568 
569  // Check to ensure that the return value can be used to construct a TitleValue.
570  // All issues should in theory be caught above, this is here to enforce consistency.
571  try {
573  $parts['namespace'],
574  $parts['dbkey'],
575  $parts['fragment'],
576  $parts['interwiki']
577  );
578  } catch ( InvalidArgumentException $ex ) {
579  $exception = ( $this->createMalformedTitleException )( 'title-invalid', $text, [ $ex->getMessage() ] );
580  throw $exception;
581  }
582 
583  return $parts;
584  }
585 
595  public static function getTitleInvalidRegex() {
596  static $rxTc = false;
597  if ( !$rxTc ) {
598  # Matching titles will be held as illegal.
599  $rxTc = '/' .
600  # Any character not allowed is forbidden...
601  '[^' . Title::legalChars() . ']' .
602  # URL percent encoding sequences interfere with the ability
603  # to round-trip titles -- you can't link to them consistently.
604  '|%[0-9A-Fa-f]{2}' .
605  # XML/HTML character references produce similar issues.
606  '|&[A-Za-z0-9\x80-\xff]+;' .
607  '/S';
608  }
609 
610  return $rxTc;
611  }
612 }
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
$matches
Caches user genders when needed to use correct namespace aliases.
Definition: GenderCache.php:34
Base class for language-specific code.
Definition: Language.php:54
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:1146
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
Definition: Sanitizer.php:1388
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40
static assertValidSpec( $namespace, $title, $fragment='', $interwiki='')
Assert that the given parameters could be used to construct a TitleValue object.
Definition: TitleValue.php:165
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:737
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:703
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.
Definition: TitleParser.php:33