1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
|
<?php
/**
* A codec for MediaWiki page titles.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @author Daniel Kinzler
*/
namespace MediaWiki\Title;
use InvalidArgumentException;
use LogicException;
use MediaWiki\Cache\GenderCache;
use MediaWiki\Interwiki\InterwikiLookup;
use MediaWiki\Language\Language;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\Message\Message;
use MediaWiki\Page\PageReference;
use MediaWiki\Parser\Sanitizer;
use Wikimedia\IPUtils;
/**
* A codec for MediaWiki page titles.
*
* @note Normalization and validation is applied while parsing, not when formatting.
* It's possible to construct a TitleValue with an invalid title, and use MediaWikiTitleCodec
* to generate an (invalid) title string from it. TitleValues should be constructed only
* via parseTitle() or from a (semi)trusted source, such as the database.
*
* @see https://www.mediawiki.org/wiki/Requests_for_comment/TitleValue
* @since 1.23
*/
class MediaWikiTitleCodec implements TitleFormatter, TitleParser {
protected Language $language;
protected GenderCache $genderCache;
/** @var string[] */
protected array $localInterwikis;
protected InterwikiLookup $interwikiLookup;
protected NamespaceInfo $nsInfo;
/**
* The code here can throw MalformedTitleException, which cannot be created in
* unit tests (see T281935). Until that changes, we use this helper callback
* that can be overridden in unit tests to return a mock instead.
*
* @var callable
*/
private $createMalformedTitleException;
/**
* @param Language $language The language object to use for localizing namespace names,
* capitalization, etc.
* @param GenderCache $genderCache The gender cache for generating gendered namespace names
* @param string[]|string $localInterwikis
* @param InterwikiLookup $interwikiLookup
* @param NamespaceInfo $nsInfo
*/
public function __construct(
Language $language,
GenderCache $genderCache,
$localInterwikis,
InterwikiLookup $interwikiLookup,
NamespaceInfo $nsInfo
) {
$this->language = $language;
$this->genderCache = $genderCache;
$this->localInterwikis = (array)$localInterwikis;
$this->interwikiLookup = $interwikiLookup;
$this->nsInfo = $nsInfo;
// Default callback is to return a real MalformedTitleException,
// callback signature matches constructor
$this->createMalformedTitleException = static function (
$errorMessage,
$titleText = null,
$errorMessageParameters = []
): MalformedTitleException {
return new MalformedTitleException( $errorMessage, $titleText, $errorMessageParameters );
};
}
/**
* @internal
* @param callable $callback
*/
public function overrideCreateMalformedTitleExceptionCallback( callable $callback ) {
// @codeCoverageIgnoreStart
if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
throw new LogicException( __METHOD__ . ' can only be used in tests' );
}
// @codeCoverageIgnoreEnd
$this->createMalformedTitleException = $callback;
}
/**
* @see TitleFormatter::getNamespaceName()
*
* @param int $namespace
* @param string $text
*
* @throws InvalidArgumentException If the namespace is invalid
* @return string Namespace name with underscores (not spaces), e.g. 'User_talk'
*/
public function getNamespaceName( $namespace, $text ) {
if ( $this->language->needsGenderDistinction() &&
$this->nsInfo->hasGenderDistinction( $namespace )
) {
// NOTE: we are assuming here that the title text is a user name!
$gender = $this->genderCache->getGenderOf( $text, __METHOD__ );
$name = $this->language->getGenderNsText( $namespace, $gender );
} else {
$name = $this->language->getNsText( $namespace );
}
if ( $name === false ) {
throw new InvalidArgumentException( 'Unknown namespace ID: ' . $namespace );
}
return $name;
}
/**
* @see TitleFormatter::formatTitle()
*
* @param int|false $namespace The namespace ID (or false, if the namespace should be ignored)
* @param string $text The page title. Should be valid. Only minimal normalization is applied.
* Underscores will be replaced.
* @param string $fragment The fragment name (may be empty).
* @param string $interwiki The interwiki name (may be empty).
*
* @throws InvalidArgumentException If the namespace is invalid
* @return string
*/
public function formatTitle( $namespace, $text, $fragment = '', $interwiki = '' ) {
$out = '';
if ( $interwiki !== '' ) {
$out = $interwiki . ':';
}
if ( $namespace != 0 ) {
try {
$nsName = $this->getNamespaceName( $namespace, $text );
} catch ( InvalidArgumentException $e ) {
// See T165149. Awkward, but better than erroneously linking to the main namespace.
$nsName = $this->language->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$namespace}";
}
$out .= $nsName . ':';
}
$out .= $text;
if ( $fragment !== '' ) {
$out .= '#' . $fragment;
}
$out = str_replace( '_', ' ', $out );
return $out;
}
/**
* Parses the given text and constructs a TitleValue.
*
* @param string $text The text to parse
* @param int $defaultNamespace Namespace to assume by default (usually NS_MAIN)
*
* @throws MalformedTitleException
* @return TitleValue
*/
public function parseTitle( $text, $defaultNamespace = NS_MAIN ) {
// Convert things like é ā or 〗 into normalized (T16952) text
$filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
// NOTE: this is an ugly kludge that allows this class to share the
// code for parsing with the old Title class. The parser code should
// be refactored to avoid this.
$parts = $this->splitTitleString( $filteredText, $defaultNamespace );
return new TitleValue(
$parts['namespace'],
$parts['dbkey'],
$parts['fragment'],
$parts['interwiki']
);
}
/**
* Given a namespace and title, return a TitleValue if valid, or null if invalid.
*
* @param int $namespace
* @param string $text
* @param string $fragment
* @param string $interwiki
*
* @return TitleValue|null
*/
public function makeTitleValueSafe( $namespace, $text, $fragment = '', $interwiki = '' ) {
if ( !$this->nsInfo->exists( $namespace ) ) {
return null;
}
$canonicalNs = $this->nsInfo->getCanonicalName( $namespace );
$fullText = $canonicalNs == '' ? $text : "$canonicalNs:$text";
if ( strval( $interwiki ) != '' ) {
$fullText = "$interwiki:$fullText";
}
if ( strval( $fragment ) != '' ) {
$fullText .= '#' . $fragment;
}
try {
$parts = $this->splitTitleString( $fullText );
} catch ( MalformedTitleException $e ) {
return null;
}
return new TitleValue(
$parts['namespace'], $parts['dbkey'], $parts['fragment'], $parts['interwiki'] );
}
/**
* @see TitleFormatter::getText()
*
* @param LinkTarget|PageReference $title
*
* @return string
*/
public function getText( $title ) {
if ( $title instanceof LinkTarget ) {
return $title->getText();
} elseif ( $title instanceof PageReference ) {
return strtr( $title->getDBKey(), '_', ' ' );
} else {
throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
}
}
/**
* @see TitleFormatter::getText()
*
* @param LinkTarget|PageReference $title
*
* @return string
* @suppress PhanUndeclaredProperty
*/
public function getPrefixedText( $title ) {
if ( $title instanceof LinkTarget ) {
if ( !isset( $title->prefixedText ) ) {
$title->prefixedText = $this->formatTitle(
$title->getNamespace(),
$title->getText(),
'',
$title->getInterwiki()
);
}
return $title->prefixedText;
} elseif ( $title instanceof PageReference ) {
$title->assertWiki( PageReference::LOCAL );
return $this->formatTitle(
$title->getNamespace(),
$this->getText( $title )
);
} else {
throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
}
}
/**
* @since 1.27
* @see TitleFormatter::getPrefixedDBkey()
* @param LinkTarget|PageReference $target
* @return string
*/
public function getPrefixedDBkey( $target ) {
if ( $target instanceof LinkTarget ) {
return strtr( $this->formatTitle(
$target->getNamespace(),
$target->getDBkey(),
'',
$target->getInterwiki()
), ' ', '_' );
} elseif ( $target instanceof PageReference ) {
$target->assertWiki( PageReference::LOCAL );
return strtr( $this->formatTitle(
$target->getNamespace(),
$target->getDBkey()
), ' ', '_' );
} else {
throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $target ) );
}
}
/**
* @see TitleFormatter::getText()
*
* @param LinkTarget|PageReference $title
*
* @return string
*/
public function getFullText( $title ) {
if ( $title instanceof LinkTarget ) {
return $this->formatTitle(
$title->getNamespace(),
$title->getText(),
$title->getFragment(),
$title->getInterwiki()
);
} elseif ( $title instanceof PageReference ) {
$title->assertWiki( PageReference::LOCAL );
return $this->formatTitle(
$title->getNamespace(),
$this->getText( $title )
);
} else {
throw new InvalidArgumentException( '$title has invalid type: ' . get_class( $title ) );
}
}
/**
* Validates, normalizes and splits a title string.
* This is the "source of truth" for title validity.
*
* This function removes illegal characters, splits off the interwiki and
* namespace prefixes, sets the other forms, and canonicalizes
* everything.
*
* @todo this method is only exposed as a temporary measure to ease refactoring.
* It was copied with minimal changes from Title::secureAndSplit().
*
* @todo This method should be split up and an appropriate interface
* defined for use by the Title class.
*
* @param string $text
* @param int $defaultNamespace
*
* @internal
* @throws MalformedTitleException If $text is not a valid title string.
* @return array A map with the fields 'interwiki', 'fragment', 'namespace', and 'dbkey'.
*/
public function splitTitleString( $text, $defaultNamespace = NS_MAIN ) {
$dbkey = str_replace( ' ', '_', $text );
# Initialisation
$parts = [
'interwiki' => '',
'local_interwiki' => false,
'fragment' => '',
'namespace' => (int)$defaultNamespace,
'dbkey' => $dbkey,
];
# Strip Unicode bidi override characters.
# Sometimes they slip into cut-n-pasted page titles, where the
# override chars get included in list displays.
$dbkey = preg_replace( '/[\x{200E}\x{200F}\x{202A}-\x{202E}]+/u', '', $dbkey );
if ( $dbkey === null ) {
# Regex had an error. Most likely this is caused by invalid UTF-8
$exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
throw $exception;
}
# Clean up whitespace
$dbkey = preg_replace(
'/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u',
'_',
$dbkey
);
$dbkey = trim( $dbkey, '_' );
if ( strpos( $dbkey, \UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
# Contained illegal UTF-8 sequences or forbidden Unicode chars.
$exception = ( $this->createMalformedTitleException )( 'title-invalid-utf8', $text );
throw $exception;
}
$parts['dbkey'] = $dbkey;
# Initial colon indicates main namespace rather than specified default
# but should not create invalid {ns,title} pairs such as {0,Project:Foo}
if ( $dbkey !== '' && $dbkey[0] == ':' ) {
$parts['namespace'] = NS_MAIN;
$dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
$dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
}
if ( $dbkey == '' ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
throw $exception;
}
# Namespace or interwiki prefix
$prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
do {
$m = [];
if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
$p = $m[1];
$ns = $this->language->getNsIndex( $p );
if ( $ns !== false ) {
# Ordinary namespace
$dbkey = $m[2];
$parts['namespace'] = $ns;
# For Talk:X pages, check if X has a "namespace" prefix
if ( $ns === NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
if ( $this->language->getNsIndex( $x[1] ) ) {
# Disallow Talk:File:x type titles...
$exception = ( $this->createMalformedTitleException )(
'title-invalid-talk-namespace',
$text
);
throw $exception;
} elseif ( $this->interwikiLookup->isValidInterwiki( $x[1] ) ) {
# Disallow Talk:Interwiki:x type titles...
$exception = ( $this->createMalformedTitleException )(
'title-invalid-talk-namespace',
$text
);
throw $exception;
}
}
} elseif ( $this->interwikiLookup->isValidInterwiki( $p ) ) {
# Interwiki link
$dbkey = $m[2];
$parts['interwiki'] = $this->language->lc( $p );
# Redundant interwiki prefix to the local wiki
foreach ( $this->localInterwikis as $localIW ) {
if ( strcasecmp( $parts['interwiki'], $localIW ) == 0 ) {
if ( $dbkey == '' ) {
# Empty self-links should point to the Main Page, to ensure
# compatibility with cross-wiki transclusions and the like.
$mainPage = Title::newMainPage();
return [
'interwiki' => $mainPage->getInterwiki(),
'local_interwiki' => true,
'fragment' => $mainPage->getFragment(),
'namespace' => $mainPage->getNamespace(),
'dbkey' => $mainPage->getDBkey(),
];
}
$parts['interwiki'] = '';
# local interwikis should behave like initial-colon links
$parts['local_interwiki'] = true;
# Do another namespace split...
continue 2;
}
}
# If there's an initial colon after the interwiki, that also
# resets the default namespace
if ( $dbkey !== '' && $dbkey[0] == ':' ) {
$parts['namespace'] = NS_MAIN;
$dbkey = substr( $dbkey, 1 );
$dbkey = trim( $dbkey, '_' );
}
}
# If there's no recognized interwiki or namespace,
# then let the colon expression be part of the title.
}
break;
} while ( true );
$fragment = strstr( $dbkey, '#' );
if ( $fragment !== false ) {
$parts['fragment'] = str_replace( '_', ' ', substr( $fragment, 1 ) );
$dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
# remove whitespace again: prevents "Foo_bar_#"
# becoming "Foo_bar_"
$dbkey = rtrim( $dbkey, "_" );
}
# Reject illegal characters.
$rxTc = self::getTitleInvalidRegex();
$matches = [];
if ( preg_match( $rxTc, $dbkey, $matches ) ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-characters', $text, [ $matches[0] ] );
throw $exception;
}
# Pages with "/./" or "/../" appearing in the URLs will often be un-
# reachable due to the way web browsers deal with 'relative' URLs.
# Also, they conflict with subpage syntax. Forbid them explicitly.
if (
str_contains( $dbkey, '.' ) &&
(
$dbkey === '.' || $dbkey === '..' ||
str_starts_with( $dbkey, './' ) ||
str_starts_with( $dbkey, '../' ) ||
str_contains( $dbkey, '/./' ) ||
str_contains( $dbkey, '/../' ) ||
str_ends_with( $dbkey, '/.' ) ||
str_ends_with( $dbkey, '/..' )
)
) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-relative', $text );
throw $exception;
}
# Magic tilde sequences? Nu-uh!
if ( strpos( $dbkey, '~~~' ) !== false ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-magic-tilde', $text );
throw $exception;
}
# Limit the size of titles to 255 bytes. This is typically the size of the
# underlying database field. We make an exception for special pages, which
# don't need to be stored in the database, and may edge over 255 bytes due
# to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
$maxLength = ( $parts['namespace'] !== NS_SPECIAL ) ? 255 : 512;
if ( strlen( $dbkey ) > $maxLength ) {
$exception = ( $this->createMalformedTitleException )(
'title-invalid-too-long',
$text,
[ Message::numParam( $maxLength ) ]
);
throw $exception;
}
# Normally, all wiki links are forced to have an initial capital letter so [[foo]]
# and [[Foo]] point to the same place. Don't force it for interwikis, since the
# other site might be case-sensitive.
if ( $parts['interwiki'] === '' && $this->nsInfo->isCapitalized( $parts['namespace'] ) ) {
$dbkey = $this->language->ucfirst( $dbkey );
}
# Can't make a link to a namespace alone... "empty" local links can only be
# self-links with a fragment identifier.
if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] !== NS_MAIN ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-empty', $text );
throw $exception;
}
// Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
// IP names are not allowed for accounts, and can only be referring to
// edits from the IP. Given '::' abbreviations and caps/lowercaps,
// there are numerous ways to present the same IP. Having sp:contribs scan
// them all is silly and having some show the edits and others not is
// inconsistent. Same for talk/userpages. Keep them normalized instead.
if ( $dbkey !== '' && ( $parts['namespace'] === NS_USER || $parts['namespace'] === NS_USER_TALK ) ) {
$dbkey = IPUtils::sanitizeIP( $dbkey );
// IPUtils::sanitizeIP return null only for bad input
'@phan-var string $dbkey';
}
// Any remaining initial :s are illegal.
if ( $dbkey !== '' && $dbkey[0] == ':' ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid-leading-colon', $text );
throw $exception;
}
// Fill fields
$parts['dbkey'] = $dbkey;
// Check to ensure that the return value can be used to construct a TitleValue.
// All issues should in theory be caught above, this is here to enforce consistency.
try {
TitleValue::assertValidSpec(
$parts['namespace'],
$parts['dbkey'],
$parts['fragment'],
$parts['interwiki']
);
} catch ( InvalidArgumentException $ex ) {
$exception = ( $this->createMalformedTitleException )( 'title-invalid', $text, [ $ex->getMessage() ] );
throw $exception;
}
return $parts;
}
/**
* Returns a simple regex that will match on characters and sequences invalid in titles.
* Note that this doesn't pick up many things that could be wrong with titles, but that
* replacing this regex with something valid will make many titles valid.
* Previously Title::getTitleInvalidRegex()
*
* @return string Regex string
* @since 1.25
*/
public static function getTitleInvalidRegex() {
static $rxTc = false;
if ( !$rxTc ) {
# Matching titles will be held as illegal.
$rxTc = '/' .
# Any character not allowed is forbidden...
'[^' . Title::legalChars() . ']' .
# URL percent encoding sequences interfere with the ability
# to round-trip titles -- you can't link to them consistently.
'|%[0-9A-Fa-f]{2}' .
# XML/HTML character references produce similar issues.
'|&[A-Za-z0-9\x80-\xff]+;' .
'/S';
}
return $rxTc;
}
}
/** @deprecated class alias since 1.41 */
class_alias( MediaWikiTitleCodec::class, 'MediaWikiTitleCodec' );
|