| 1 |
<?php |
| 2 |
declare( strict_types = 1 ); |
| 3 |
|
| 4 |
namespace Wikimedia\Parsoid\Utils; |
| 5 |
|
| 6 |
use Psr\Log\LoggerInterface; |
| 7 |
use Wikimedia\Bcp47Code\Bcp47Code; |
| 8 |
use Wikimedia\Bcp47Code\Bcp47CodeValue; |
| 9 |
use Wikimedia\Parsoid\Config\Env; |
| 10 |
use Wikimedia\Parsoid\Config\SiteConfig; |
| 11 |
use Wikimedia\Parsoid\Core\DomSourceRange; |
| 12 |
use Wikimedia\Parsoid\Core\Sanitizer; |
| 13 |
use Wikimedia\Parsoid\NodeData\DataMw; |
| 14 |
use Wikimedia\Parsoid\Tokens\Token; |
| 15 |
use Wikimedia\Parsoid\Wikitext\Consts; |
| 16 |
|
| 17 |
/** |
| 18 |
* This file contains general utilities for token transforms. |
| 19 |
*/ |
| 20 |
class Utils { |
| 21 |
/** |
| 22 |
* Regular expression fragment for matching wikitext comments. |
| 23 |
* Meant for inclusion in other regular expressions. |
| 24 |
*/ |
| 25 |
// Maintenance note: this is used in /x regexes so all whitespace and # should be escaped |
| 26 |
public const COMMENT_REGEXP_FRAGMENT = '<!--(?>[\s\S]*?-->)'; |
| 27 |
/** Regular fragment for matching a wikitext comment */ |
| 28 |
public const COMMENT_REGEXP = '/' . self::COMMENT_REGEXP_FRAGMENT . '/'; |
| 29 |
|
| 30 |
/** |
| 31 |
* Strip Parsoid id prefix from aboutID |
| 32 |
* |
| 33 |
* @param string $aboutId aboud ID string |
| 34 |
* @return string |
| 35 |
*/ |
| 36 |
public static function stripParsoidIdPrefix( string $aboutId ): string { |
| 37 |
// 'mwt' is the prefix used for new ids |
| 38 |
return preg_replace( '/^#?mwt/', '', $aboutId ); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Strip PHP namespace from the fully qualified class name |
| 43 |
* @param string $className |
| 44 |
* @return string |
| 45 |
*/ |
| 46 |
public static function stripNamespace( string $className ): string { |
| 47 |
return preg_replace( '/.*\\\\/', '', $className ); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Check for Parsoid id prefix in an aboutID string |
| 52 |
* |
| 53 |
* @param string $aboutId aboud ID string |
| 54 |
* @return bool |
| 55 |
*/ |
| 56 |
public static function isParsoidObjectId( string $aboutId ): bool { |
| 57 |
// 'mwt' is the prefix used for new ids |
| 58 |
return str_starts_with( $aboutId, '#mwt' ); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Determine if the named tag is void (can not have content). |
| 63 |
* |
| 64 |
* @param string $name tag name |
| 65 |
* @return bool |
| 66 |
*/ |
| 67 |
public static function isVoidElement( string $name ): bool { |
| 68 |
return isset( Consts::$HTML['VoidTags'][$name] ); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* recursive deep clones helper function |
| 73 |
* |
| 74 |
* @param object $el object |
| 75 |
* @return object |
| 76 |
*/ |
| 77 |
private static function recursiveClone( $el ) { |
| 78 |
return self::clone( $el, true ); |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Deep clones by default. |
| 83 |
* @param object|array $obj arrays or plain objects |
| 84 |
* Tokens or DOM nodes shouldn't be passed in. |
| 85 |
* |
| 86 |
* CAVEAT: It looks like debugging methods pass in arrays |
| 87 |
* that can have DOM nodes. So, for debugging purposes, |
| 88 |
* we handle top-level DOM nodes or DOM nodes embedded in arrays |
| 89 |
* But, this will miserably fail if an object embeds a DOM node. |
| 90 |
* |
| 91 |
* @param bool $deepClone |
| 92 |
* @param bool $debug |
| 93 |
* @return object|array |
| 94 |
*/ |
| 95 |
public static function clone( $obj, $deepClone = true, $debug = false ) { |
| 96 |
if ( $debug ) { |
| 97 |
if ( $obj instanceof \DOMNode ) { |
| 98 |
return $obj->cloneNode( $deepClone ); |
| 99 |
} |
| 100 |
if ( is_array( $obj ) ) { |
| 101 |
if ( $deepClone ) { |
| 102 |
return array_map( |
| 103 |
static function ( $o ) { |
| 104 |
return Utils::clone( $o, true, true ); |
| 105 |
}, |
| 106 |
$obj |
| 107 |
); |
| 108 |
} else { |
| 109 |
return $obj; // Copy-on-write cloning |
| 110 |
} |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
if ( !$deepClone && is_object( $obj ) ) { |
| 115 |
return clone $obj; |
| 116 |
} |
| 117 |
|
| 118 |
// FIXME, see T161647 |
| 119 |
// This will fail if $obj is (or embeds) a DOMNode |
| 120 |
return unserialize( serialize( $obj ) ); |
| 121 |
} |
| 122 |
|
| 123 |
/** |
| 124 |
* Extract the last *unicode* character of the string. |
| 125 |
* This might be more than one byte, if the last character |
| 126 |
* is non-ASCII. |
| 127 |
* @param string $str |
| 128 |
* @param ?int $idx The index *after* the character to extract; defaults |
| 129 |
* to the length of $str, which will extract the last character in |
| 130 |
* $str. |
| 131 |
* @return string |
| 132 |
*/ |
| 133 |
public static function lastUniChar( string $str, ?int $idx = null ): string { |
| 134 |
if ( $idx === null ) { |
| 135 |
$idx = strlen( $str ); |
| 136 |
} elseif ( $idx <= 0 || $idx > strlen( $str ) ) { |
| 137 |
return ''; |
| 138 |
} |
| 139 |
$c = $str[--$idx]; |
| 140 |
while ( ( ord( $c[0] ) & 0xC0 ) === 0x80 ) { |
| 141 |
$c = $str[--$idx] . $c; |
| 142 |
} |
| 143 |
return $c; |
| 144 |
} |
| 145 |
|
| 146 |
/** |
| 147 |
* Return true if the first character in $s is a unicode word character. |
| 148 |
* @param string $s |
| 149 |
* @return bool |
| 150 |
*/ |
| 151 |
public static function isUniWord( string $s ): bool { |
| 152 |
return preg_match( '#^\w#u', $s ) === 1; |
| 153 |
} |
| 154 |
|
| 155 |
/** |
| 156 |
* This should not be used. |
| 157 |
* @param string $txt URL to encode using PHP encoding |
| 158 |
* @return string |
| 159 |
*/ |
| 160 |
public static function phpURLEncode( $txt ) { |
| 161 |
// @phan-suppress-previous-line PhanPluginNeverReturnMethod |
| 162 |
throw new \BadMethodCallException( 'Use urlencode( $txt ) instead' ); |
| 163 |
} |
| 164 |
|
| 165 |
/** |
| 166 |
* Percent-decode only valid UTF-8 characters, leaving other encoded bytes alone. |
| 167 |
* |
| 168 |
* Distinct from `decodeURIComponent` in that certain escapes are not decoded, |
| 169 |
* matching the behavior of JavaScript's decodeURI(). |
| 170 |
* |
| 171 |
* @see https://www.ecma-international.org/ecma-262/6.0/#sec-decodeuri-encodeduri |
| 172 |
* @param string $s URI to be decoded |
| 173 |
* @return string |
| 174 |
*/ |
| 175 |
public static function decodeURI( string $s ): string { |
| 176 |
// Escape the '%' in sequences for the reserved characters, then use decodeURIComponent. |
| 177 |
$s = preg_replace( '/%(?=2[346bcfBCF]|3[abdfABDF]|40)/', '%25', $s ); |
| 178 |
return self::decodeURIComponent( $s ); |
| 179 |
} |
| 180 |
|
| 181 |
/** |
| 182 |
* Percent-decode only valid UTF-8 characters, leaving other encoded bytes alone. |
| 183 |
* |
| 184 |
* @param string $s URI to be decoded |
| 185 |
* @return string |
| 186 |
*/ |
| 187 |
public static function decodeURIComponent( string $s ): string { |
| 188 |
// Most of the time we should have valid input |
| 189 |
$ret = rawurldecode( $s ); |
| 190 |
if ( mb_check_encoding( $ret, 'UTF-8' ) ) { |
| 191 |
return $ret; |
| 192 |
} |
| 193 |
|
| 194 |
// Extract each encoded character and decode it individually |
| 195 |
return preg_replace_callback( |
| 196 |
// phpcs:ignore Generic.Files.LineLength.TooLong |
| 197 |
'/%[0-7][0-9A-F]|%[CD][0-9A-F]%[89AB][0-9A-F]|%E[0-9A-F](?:%[89AB][0-9A-F]){2}|%F[0-4](?:%[89AB][0-9A-F]){3}/i', |
| 198 |
static function ( $match ) { |
| 199 |
$ret = rawurldecode( $match[0] ); |
| 200 |
return mb_check_encoding( $ret, 'UTF-8' ) ? $ret : $match[0]; |
| 201 |
}, $s |
| 202 |
); |
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* Extract extension source from the token |
| 207 |
* |
| 208 |
* @param Token $token token |
| 209 |
* @return string |
| 210 |
*/ |
| 211 |
public static function extractExtBody( Token $token ): string { |
| 212 |
$src = $token->getAttributeV( 'source' ); |
| 213 |
$extTagOffsets = $token->dataParsoid->extTagOffsets; |
| 214 |
'@phan-var \Wikimedia\Parsoid\Core\DomSourceRange $extTagOffsets'; |
| 215 |
return $extTagOffsets->stripTags( $src ); |
| 216 |
} |
| 217 |
|
| 218 |
/** |
| 219 |
* Helper function checks numeric values |
| 220 |
* |
| 221 |
* @param ?int $n checks parameters for numeric type and value zero or positive |
| 222 |
* @return bool |
| 223 |
*/ |
| 224 |
private static function isValidOffset( ?int $n ): bool { |
| 225 |
return $n !== null && $n >= 0; |
| 226 |
} |
| 227 |
|
| 228 |
/** |
| 229 |
* Basic check if a DOM Source Range (DSR) is valid. |
| 230 |
* |
| 231 |
* Clarifications about the "basic validity checks": |
| 232 |
* - Only checks for underflow, not for overflow. |
| 233 |
* - Does not verify that start <= end |
| 234 |
* - Does not verify that openWidth + endWidth <= end - start |
| 235 |
* (even so, the values might be invalid because of content) |
| 236 |
* These would be overkill for our purposes. Given how DSR computation |
| 237 |
* works in thie codebase, the real scenarios we care about are |
| 238 |
* non-null / non-negative values since that can happen. |
| 239 |
* |
| 240 |
* @param ?DomSourceRange $dsr DSR source range values |
| 241 |
* @param bool $all Also check the widths of the container tag |
| 242 |
* @return bool |
| 243 |
*/ |
| 244 |
public static function isValidDSR( |
| 245 |
?DomSourceRange $dsr, bool $all = false |
| 246 |
): bool { |
| 247 |
return $dsr !== null && |
| 248 |
self::isValidOffset( $dsr->start ) && |
| 249 |
self::isValidOffset( $dsr->end ) && |
| 250 |
( !$all || ( |
| 251 |
self::isValidOffset( $dsr->openWidth ) && |
| 252 |
self::isValidOffset( $dsr->closeWidth ) |
| 253 |
) |
| 254 |
); |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* Cannonicalizes a namespace name. |
| 259 |
* |
| 260 |
* @param string $name Non-normalized namespace name. |
| 261 |
* @return string |
| 262 |
*/ |
| 263 |
public static function normalizeNamespaceName( string $name ): string { |
| 264 |
return strtr( mb_strtolower( $name ), ' ', '_' ); |
| 265 |
} |
| 266 |
|
| 267 |
/** |
| 268 |
* Decode HTML5 entities in wikitext. |
| 269 |
* |
| 270 |
* NOTE that wikitext only allows semicolon-terminated entities, while |
| 271 |
* HTML allows a number of "legacy" entities to be decoded without |
| 272 |
* a terminating semicolon. This function deliberately does not |
| 273 |
* decode these HTML-only entity forms. |
| 274 |
* |
| 275 |
* @param string $text |
| 276 |
* @return string |
| 277 |
*/ |
| 278 |
public static function decodeWtEntities( string $text ): string { |
| 279 |
// Note that HTML5 allows semicolon-less entities which |
| 280 |
// wikitext does not: in wikitext all entities must end in a |
| 281 |
// semicolon. |
| 282 |
// By normalizing before decoding, this routine deliberately |
| 283 |
// does not decode entity references which are invalid in wikitext |
| 284 |
// (mostly because they decode to invalid codepoints). |
| 285 |
return Sanitizer::decodeCharReferences( |
| 286 |
Sanitizer::normalizeCharReferences( $text ) |
| 287 |
); |
| 288 |
} |
| 289 |
|
| 290 |
/** |
| 291 |
* Entity-escape anything that would decode to a valid wikitext entity. |
| 292 |
* |
| 293 |
* Note that HTML5 allows certain "semicolon-less" entities, like |
| 294 |
* `¶`; these aren't allowed in wikitext and won't be escaped |
| 295 |
* by this function. |
| 296 |
* |
| 297 |
* @param string $text |
| 298 |
* @return string |
| 299 |
*/ |
| 300 |
public static function escapeWtEntities( string $text ): string { |
| 301 |
// We just want to encode ampersands that precede valid entities. |
| 302 |
// (And note that semicolon-less entities aren't valid wikitext.) |
| 303 |
return preg_replace_callback( '/&[#0-9a-zA-Z\x80-\xff]+;/', function ( $match ) { |
| 304 |
$m = $match[0]; |
| 305 |
$decodedChar = self::decodeWtEntities( $m ); |
| 306 |
if ( $decodedChar !== $m ) { |
| 307 |
// Escape the ampersand |
| 308 |
return '&' . substr( $m, 1 ); |
| 309 |
} else { |
| 310 |
// Not an entity, just return the string |
| 311 |
return $m; |
| 312 |
} |
| 313 |
}, $text ); |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Convert special characters to HTML entities |
| 318 |
* |
| 319 |
* @param string $s |
| 320 |
* @return string |
| 321 |
*/ |
| 322 |
public static function escapeHtml( string $s ): string { |
| 323 |
// Only encodes five characters: " ' & < > |
| 324 |
$s = htmlspecialchars( $s, ENT_QUOTES | ENT_HTML5 ); |
| 325 |
$s = str_replace( "\u{0338}", '̸', $s ); |
| 326 |
return $s; |
| 327 |
} |
| 328 |
|
| 329 |
/** |
| 330 |
* Encode all characters as entity references. This is done to make |
| 331 |
* characters safe for wikitext (regardless of whether they are |
| 332 |
* HTML-safe). Typically only called with single-codepoint strings. |
| 333 |
* @param string $s |
| 334 |
* @return string |
| 335 |
*/ |
| 336 |
public static function entityEncodeAll( string $s ): string { |
| 337 |
// This is Unicode aware. |
| 338 |
static $conventions = [ |
| 339 |
// We always use at least two characters for the hex code |
| 340 |
'�' => '�', '' => '', '' => '', '' => '', |
| 341 |
'' => '', '' => '', '' => '', '' => '', |
| 342 |
'' => '', '	' => '	', '
' => '
', '' => '', |
| 343 |
'' => '', '
' => '
', '' => '', '' => '', |
| 344 |
// By convention we use where possible |
| 345 |
' ' => ' ', |
| 346 |
]; |
| 347 |
|
| 348 |
return strtr( mb_encode_numericentity( |
| 349 |
$s, [ 0, 0x10ffff, 0, ~0 ], 'utf-8', true |
| 350 |
), $conventions ); |
| 351 |
} |
| 352 |
|
| 353 |
/** |
| 354 |
* Determine whether the protocol of a link is potentially valid. Use the |
| 355 |
* environment's per-wiki config to do so. |
| 356 |
* |
| 357 |
* @param mixed $linkTarget |
| 358 |
* @param Env $env |
| 359 |
* @return bool |
| 360 |
*/ |
| 361 |
public static function isProtocolValid( $linkTarget, Env $env ): bool { |
| 362 |
$siteConf = $env->getSiteConfig(); |
| 363 |
if ( is_string( $linkTarget ) ) { |
| 364 |
return $siteConf->hasValidProtocol( $linkTarget ); |
| 365 |
} else { |
| 366 |
return true; |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
/** |
| 371 |
* Get argument information for an extension tag token. |
| 372 |
* |
| 373 |
* @param Token $extToken |
| 374 |
* @return DataMw |
| 375 |
*/ |
| 376 |
public static function getExtArgInfo( Token $extToken ): DataMw { |
| 377 |
$name = $extToken->getAttributeV( 'name' ); |
| 378 |
$options = $extToken->getAttributeV( 'options' ); |
| 379 |
$defaultDataMw = new DataMw( [ |
| 380 |
'name' => $name, |
| 381 |
// T367616: 'attrs' should be renamed to 'extAttrs' |
| 382 |
'attrs' => (object)TokenUtils::kvToHash( $options ), |
| 383 |
] ); |
| 384 |
$extTagOffsets = $extToken->dataParsoid->extTagOffsets; |
| 385 |
if ( $extTagOffsets->closeWidth !== 0 ) { |
| 386 |
// If not self-closing... |
| 387 |
$defaultDataMw->body = (object)[ |
| 388 |
'extsrc' => self::extractExtBody( $extToken ), |
| 389 |
]; |
| 390 |
} |
| 391 |
return $defaultDataMw; |
| 392 |
} |
| 393 |
|
| 394 |
/** |
| 395 |
* Parse media dimensions |
| 396 |
* |
| 397 |
* @param SiteConfig $siteConfig |
| 398 |
* @param string $str media dimension string to parse |
| 399 |
* @param bool $onlyOne If set, returns null if multiple dimenstions are present |
| 400 |
* @param bool $localized Defaults to false; set to true if the $str |
| 401 |
* has already been matched against `img_width` to localize the `px` |
| 402 |
* suffix. |
| 403 |
* @return ?array{x:int,y?:int,bogusPx:bool} |
| 404 |
*/ |
| 405 |
public static function parseMediaDimensions( |
| 406 |
SiteConfig $siteConfig, string $str, bool $onlyOne = false, |
| 407 |
bool $localized = false |
| 408 |
): ?array { |
| 409 |
if ( !$localized ) { |
| 410 |
$getOption = $siteConfig->getMediaPrefixParameterizedAliasMatcher(); |
| 411 |
$bits = $getOption( $str ); |
| 412 |
$normalizedBit0 = $bits ? mb_strtolower( trim( $bits['k'] ) ) : null; |
| 413 |
if ( $normalizedBit0 === 'img_width' ) { |
| 414 |
$str = $bits['v']; |
| 415 |
} |
| 416 |
} |
| 417 |
$dimensions = null; |
| 418 |
// We support a trailing 'px' here for historical reasons |
| 419 |
// (T15500, T53628, T207032) |
| 420 |
if ( preg_match( '/^(\d*)(?:x(\d+))?\s*(px\s*)?$/D', $str, $match ) ) { |
| 421 |
$dimensions = [ 'x' => null, 'y' => null, 'bogusPx' => false ]; |
| 422 |
if ( !empty( $match[1] ) ) { |
| 423 |
$dimensions['x'] = intval( $match[1], 10 ); |
| 424 |
} |
| 425 |
if ( !empty( $match[2] ) ) { |
| 426 |
if ( $onlyOne ) { |
| 427 |
return null; |
| 428 |
} |
| 429 |
$dimensions['y'] = intval( $match[2], 10 ); |
| 430 |
} |
| 431 |
if ( !empty( $match[3] ) ) { |
| 432 |
$dimensions['bogusPx'] = true; |
| 433 |
} |
| 434 |
} |
| 435 |
return $dimensions; |
| 436 |
} |
| 437 |
|
| 438 |
/** |
| 439 |
* Validate media parameters |
| 440 |
* More generally, this is defined by the media handler in core |
| 441 |
* |
| 442 |
* @param ?int $num |
| 443 |
* @return bool |
| 444 |
*/ |
| 445 |
public static function validateMediaParam( ?int $num ): bool { |
| 446 |
return $num !== null && $num > 0; |
| 447 |
} |
| 448 |
|
| 449 |
/** |
| 450 |
* FIXME: Is this needed?? |
| 451 |
* |
| 452 |
* Extract content in a backwards compatible way |
| 453 |
* |
| 454 |
* @param object $revision |
| 455 |
* @return object |
| 456 |
*/ |
| 457 |
public static function getStar( $revision ) { |
| 458 |
// @phan-suppress-previous-line PhanPluginNeverReturnMethod |
| 459 |
/* |
| 460 |
$content = $revision; |
| 461 |
if ( $revision && isset( $revision->slots ) ) { |
| 462 |
$content = $revision->slots->main; |
| 463 |
} |
| 464 |
return $content; |
| 465 |
*/ |
| 466 |
throw new \BadMethodCallException( "This method shouldn't be needed. " . |
| 467 |
"But, port this if you really need it." ); |
| 468 |
} |
| 469 |
|
| 470 |
/** |
| 471 |
* This regex was generated by running through *all unicode characters* and |
| 472 |
* testing them against *all regexes* for linktrails in a default MW install. |
| 473 |
* We had to treat it a little bit, here's what we changed: |
| 474 |
* |
| 475 |
* 1. A-Z, though allowed in Walloon, is disallowed. |
| 476 |
* 2. '"', though allowed in Chuvash, is disallowed. |
| 477 |
* 3. '-', though allowed in Icelandic (possibly due to a bug), is disallowed. |
| 478 |
* 4. '1', though allowed in Lak (possibly due to a bug), is disallowed. |
| 479 |
*/ |
| 480 |
// phpcs:disable Generic.Files.LineLength.TooLong |
| 481 |
public static $linkTrailRegex = |
| 482 |
'/^[^\0-`{÷ĀĈ-ČĎĐĒĔĖĚĜĝĠ-ĪĬ-įIJĴ-ĹĻ-ĽĿŀŅņʼnŊŌŎŏŒŔŖ-ŘŜŝŠŤŦŨŪ-ŬŮŲ-ŴŶŸ' . |
| 483 |
'ſ-ǤǦǨǪ-Ǯǰ-ȗȜ-ȞȠ-ɘɚ-ʑʓ-ʸʽ-̂̄-΅·Ϗ-ЯѐѝѠѢѤѦѨѪѬѮѰѲѴѶѸѺ-ѾҀ-҃҅-ҐҒҔҕҘҚҜ-ҠҤ-ҪҬҭҰҲ' . |
| 484 |
'Ҵ-ҶҸҹҼ-ҿӁ-ӗӚ-ӜӞӠ-ӢӤӦӪ-ӲӴӶ-ՠֈ--ؠً-ٳٵ-ٽٿ-څڇ-ڗڙ-ڨڪ-ڬڮڰ-ڽڿ-ۅۈ-ۊۍ-۔ۖ--' . |
| 485 |
'---੯ੴ-ჱ-ẼẾ-\x{200b}\x{200d}-‒—-‗‚‛”--\x{fffd}]+$/D'; |
| 486 |
// phpcs:enable Generic.Files.LineLength.TooLong |
| 487 |
|
| 488 |
/** |
| 489 |
* Check whether some text is a valid link trail. |
| 490 |
* |
| 491 |
* @param string $text |
| 492 |
* @return bool |
| 493 |
*/ |
| 494 |
public static function isLinkTrail( string $text ): bool { |
| 495 |
return $text !== '' && preg_match( self::$linkTrailRegex, $text ); |
| 496 |
} |
| 497 |
|
| 498 |
/** |
| 499 |
* Convert BCP-47-compliant language code to MediaWiki-internal code. |
| 500 |
* |
| 501 |
* This is a temporary back-compatibility hack; Parsoid should be |
| 502 |
* using BCP 47 strings or Bcp47Code objects in all its external APIs. |
| 503 |
* Try to avoid using it, though: there's no guarantee |
| 504 |
* that this mapping will remain in sync with upstream. |
| 505 |
* |
| 506 |
* @param string|Bcp47Code $code BCP-47 language code |
| 507 |
* @return string MediaWiki-internal language code |
| 508 |
*/ |
| 509 |
public static function bcp47ToMwCode( $code ): string { |
| 510 |
// This map is dumped from |
| 511 |
// LanguageCode::NON_STANDARD_LANGUAGE_CODE_MAPPING in core, but |
| 512 |
// with keys and values swapped and BCP-47 codes lowercased: |
| 513 |
// |
| 514 |
// array_flip(array_map(strtolower, |
| 515 |
// LanguageCode::NON_STANDARD_LANGUAGE_CODE_MAPPING)) |
| 516 |
// |
| 517 |
// Hopefully we will be able to deprecate and remove this from |
| 518 |
// Parsoid quickly enough that keeping it in sync with upstream |
| 519 |
// is not an issue. |
| 520 |
static $MAP = [ |
| 521 |
"cbk" => "cbk-zam", |
| 522 |
"de-x-formal" => "de-formal", |
| 523 |
"egl" => "eml", |
| 524 |
"en-x-rtl" => "en-rtl", |
| 525 |
"es-x-formal" => "es-formal", |
| 526 |
"hu-x-formal" => "hu-formal", |
| 527 |
"jv-x-bms" => "map-bms", |
| 528 |
"ro-cyrl-md" => "mo", |
| 529 |
"nrf" => "nrm", |
| 530 |
"nl-x-informal" => "nl-informal", |
| 531 |
"nap-x-tara" => "roa-tara", |
| 532 |
"en-simple" => "simple", |
| 533 |
"sr-cyrl" => "sr-ec", |
| 534 |
"sr-latn" => "sr-el", |
| 535 |
"zh-hans-cn" => "zh-cn", |
| 536 |
"zh-hans-sg" => "zh-sg", |
| 537 |
"zh-hans-my" => "zh-my", |
| 538 |
"zh-hant-tw" => "zh-tw", |
| 539 |
"zh-hant-hk" => "zh-hk", |
| 540 |
"zh-hant-mo" => "zh-mo", |
| 541 |
]; |
| 542 |
if ( $code instanceof Bcp47Code ) { |
| 543 |
$code = $code->toBcp47Code(); |
| 544 |
} |
| 545 |
$code = strtolower( $code ); // All MW-internal codes are lowercase |
| 546 |
return $MAP[$code] ?? $code; |
| 547 |
} |
| 548 |
|
| 549 |
/** |
| 550 |
* Convert MediaWiki-internal language code to a BCP-47-compliant |
| 551 |
* language code suitable for including in HTML. |
| 552 |
* |
| 553 |
* This is a temporary back-compatibility hack, needed for compatibility |
| 554 |
* when running in standalone mode with MediaWiki Action APIs which expose |
| 555 |
* internal language codes. These APIs should eventually be improved |
| 556 |
* so that they also expose BCP-47 compliant codes, which can then be |
| 557 |
* used directly by Parsoid without conversion. But until that day |
| 558 |
* comes, this function will paper over the differences. |
| 559 |
* |
| 560 |
* Note that MediaWiki-internal Language objects implement Bcp47Code, |
| 561 |
* so we can transition interfaces which currently take a string code |
| 562 |
* to pass a Language object instead; that will make this method |
| 563 |
* effectively a no-op and avoid the issue of upstream sync of the |
| 564 |
* mapping table. |
| 565 |
* |
| 566 |
* @param string|Bcp47Code $code MediaWiki-internal language code or object |
| 567 |
* @param bool $strict If true, this code will log a deprecation message |
| 568 |
* or fail if a MediaWiki-internal language code is passed. |
| 569 |
* @param ?LoggerInterface $warnLogger A deprecation warning will be |
| 570 |
* emitted on $warnLogger if $strict is true and a string-valued |
| 571 |
* MediaWiki-internal language code is passed; otherwise an exception |
| 572 |
* will be thrown. |
| 573 |
* @return Bcp47Code BCP-47 language code. |
| 574 |
* @see LanguageCode::bcp47() |
| 575 |
*/ |
| 576 |
public static function mwCodeToBcp47( |
| 577 |
$code, bool $strict = false, ?LoggerInterface $warnLogger = null |
| 578 |
): Bcp47Code { |
| 579 |
if ( $code instanceof Bcp47Code ) { |
| 580 |
return $code; |
| 581 |
} |
| 582 |
if ( $strict ) { |
| 583 |
$msg = "Use of string-valued BCP-47 codes is deprecated."; |
| 584 |
if ( defined( 'MW_PHPUNIT_TEST' ) || defined( 'MW_PARSER_TEST' ) ) { |
| 585 |
// Always throw an error if running tests |
| 586 |
throw new \Error( $msg ); |
| 587 |
} |
| 588 |
if ( $warnLogger ) { |
| 589 |
$warnLogger->warning( $msg ); |
| 590 |
} else { |
| 591 |
// Strict mode requested but no deprecation logger provided |
| 592 |
throw new \Error( $msg ); |
| 593 |
} |
| 594 |
} |
| 595 |
// This map is dumped from |
| 596 |
// LanguageCode::getNonstandardLanguageCodeMapping() in core. |
| 597 |
// Hopefully we will be able to deprecate and remove this method |
| 598 |
// from Parsoid quickly enough that keeping it in sync with upstream |
| 599 |
// will not be an issue. |
| 600 |
static $MAP = [ |
| 601 |
"als" => "gsw", |
| 602 |
"bat-smg" => "sgs", |
| 603 |
"be-x-old" => "be-tarask", |
| 604 |
"fiu-vro" => "vro", |
| 605 |
"roa-rup" => "rup", |
| 606 |
"zh-classical" => "lzh", |
| 607 |
"zh-min-nan" => "nan", |
| 608 |
"zh-yue" => "yue", |
| 609 |
"cbk-zam" => "cbk", |
| 610 |
"de-formal" => "de-x-formal", |
| 611 |
"eml" => "egl", |
| 612 |
"en-rtl" => "en-x-rtl", |
| 613 |
"es-formal" => "es-x-formal", |
| 614 |
"hu-formal" => "hu-x-formal", |
| 615 |
"map-bms" => "jv-x-bms", |
| 616 |
"mo" => "ro-Cyrl-MD", |
| 617 |
"nrm" => "nrf", |
| 618 |
"nl-informal" => "nl-x-informal", |
| 619 |
"roa-tara" => "nap-x-tara", |
| 620 |
"simple" => "en-simple", |
| 621 |
"sr-ec" => "sr-Cyrl", |
| 622 |
"sr-el" => "sr-Latn", |
| 623 |
"zh-cn" => "zh-Hans-CN", |
| 624 |
"zh-sg" => "zh-Hans-SG", |
| 625 |
"zh-my" => "zh-Hans-MY", |
| 626 |
"zh-tw" => "zh-Hant-TW", |
| 627 |
"zh-hk" => "zh-Hant-HK", |
| 628 |
"zh-mo" => "zh-Hant-MO", |
| 629 |
]; |
| 630 |
$code = $MAP[$code] ?? $code; |
| 631 |
// The rest of this code is copied verbatim from LanguageCode::bcp47() |
| 632 |
// in core. |
| 633 |
$codeSegment = explode( '-', $code ); |
| 634 |
$codeBCP = []; |
| 635 |
foreach ( $codeSegment as $segNo => $seg ) { |
| 636 |
// when previous segment is x, it is a private segment and should be lc |
| 637 |
if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) { |
| 638 |
$codeBCP[$segNo] = strtolower( $seg ); |
| 639 |
// ISO 3166 country code |
| 640 |
} elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) { |
| 641 |
$codeBCP[$segNo] = strtoupper( $seg ); |
| 642 |
// ISO 15924 script code |
| 643 |
} elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) { |
| 644 |
$codeBCP[$segNo] = ucfirst( strtolower( $seg ) ); |
| 645 |
// Use lowercase for other cases |
| 646 |
} else { |
| 647 |
$codeBCP[$segNo] = strtolower( $seg ); |
| 648 |
} |
| 649 |
} |
| 650 |
return new Bcp47CodeValue( implode( '-', $codeBCP ) ); |
| 651 |
} |
| 652 |
|
| 653 |
/** |
| 654 |
* BCP 47 codes are case-insensitive, so this helper does a "proper" |
| 655 |
* comparison of Bcp47Code objects. |
| 656 |
* @param Bcp47Code $a |
| 657 |
* @param Bcp47Code $b |
| 658 |
* @return bool true iff $a and $b represent the same language |
| 659 |
*/ |
| 660 |
public static function isBcp47CodeEqual( Bcp47Code $a, Bcp47Code $b ): bool { |
| 661 |
return strcasecmp( $a->toBcp47Code(), $b->toBcp47Code() ) === 0; |
| 662 |
} |
| 663 |
} |