MediaWiki  master
LanguageConverter.php
Go to the documentation of this file.
1 <?php
29 
35 abstract class LanguageConverter implements ILanguageConverter {
37 
43  public static $languagesWithVariants = [
44  'en',
45  'crh',
46  'gan',
47  'iu',
48  'kk',
49  'ku',
50  'shi',
51  'sr',
52  'tg',
53  'uz',
54  'zh',
55  ];
56 
58 
62  public $mVariants;
65  private $mTablesLoaded = false;
66 
70  protected $mTables;
71 
72  // 'bidirectional' 'unidirectional' 'disable' for each variant
73  public $mManualLevel;
74 
78  private $mLangObj;
79  public $mFlags;
80  public $mDescCodeSep = ':';
81  public $mDescVarSep = ';';
82  private $mUcfirst = false;
83  private $mConvRuleTitle = false;
84  private $mURLVariant;
85  private $mUserVariant;
86  private $mHeaderVariant;
87  private $mMaxDepth = 10;
89 
90  private const CACHE_VERSION_KEY = 'VERSION 7';
91 
100  public function __construct(
101  $langobj,
102  $maincode,
103  $variants = [],
104  $variantfallbacks = [],
105  $flags = [],
106  $manualLevel = []
107  ) {
108  global $wgDisabledVariants;
109 
110  $this->deprecatePublicProperty( 'mURLVariant', '1.35', __CLASS__ );
111  $this->deprecatePublicProperty( 'mURLVariant', '1.35', __CLASS__ );
112  $this->deprecatePublicProperty( 'mUcfirst', '1.35', __CLASS__ );
113  $this->deprecatePublicProperty( 'mConvRuleTitle', '1.35', __CLASS__ );
114  $this->deprecatePublicProperty( 'mURLVariant', '1.35', __CLASS__ );
115  $this->deprecatePublicProperty( 'mUserVariant', '1.35', __CLASS__ );
116  $this->deprecatePublicProperty( 'mHeaderVariant', '1.35', __CLASS__ );
117  $this->deprecatePublicProperty( 'mMaxDepth = 10', '1.35', __CLASS__ );
118  $this->deprecatePublicProperty( 'mVarSeparatorPattern', '1.35', __CLASS__ );
119  $this->deprecatePublicProperty( 'mLangObj', '1.35', __CLASS__ );
120  $this->deprecatePublicProperty( 'mVariantFallbacks', '1.35', __CLASS__ );
121  $this->deprecatePublicProperty( 'mTablesLoaded', '1.35', __CLASS__ );
122  $this->deprecatePublicProperty( 'mTables', '1.35', __CLASS__ );
123 
124  $this->mLangObj = $langobj;
125  $this->mMainLanguageCode = $maincode;
126  $this->mVariants = array_diff( $variants, $wgDisabledVariants );
127  $this->mVariantFallbacks = $variantfallbacks;
128  $this->mVariantNames = MediaWikiServices::getInstance()
129  ->getLanguageNameUtils()
130  ->getLanguageNames();
131  $defaultflags = [
132  // 'S' show converted text
133  // '+' add rules for alltext
134  // 'E' the gave flags is error
135  // these flags above are reserved for program
136  'A' => 'A', // add rule for convert code (all text convert)
137  'T' => 'T', // title convert
138  'R' => 'R', // raw content
139  'D' => 'D', // convert description (subclass implement)
140  '-' => '-', // remove convert (not implement)
141  'H' => 'H', // add rule for convert code (but no display in placed code)
142  'N' => 'N', // current variant name
143  ];
144  $this->mFlags = array_merge( $defaultflags, $flags );
145  foreach ( $this->mVariants as $v ) {
146  if ( array_key_exists( $v, $manualLevel ) ) {
147  $this->mManualLevel[$v] = $manualLevel[$v];
148  } else {
149  $this->mManualLevel[$v] = 'bidirectional';
150  }
151  $this->mFlags[$v] = $v;
152  }
153  }
154 
161  public function getVariants() {
162  return $this->mVariants;
163  }
164 
176  public function getVariantFallbacks( $variant ) {
177  return $this->mVariantFallbacks[$variant] ?? $this->mMainLanguageCode;
178  }
179 
184  public function getConvRuleTitle() {
185  return $this->mConvRuleTitle;
186  }
187 
192  public function getPreferredVariant() {
193  global $wgDefaultLanguageVariant, $wgUser;
194 
195  $req = $this->getURLVariant();
196 
197  Hooks::runner()->onGetLangPreferredVariant( $req );
198 
199  // NOTE: For calls from Setup.php, wgUser or the session might not be set yet (T235360)
200  // Use case: During autocreation, User::isUsableName is called which uses interface
201  // messages for reserved usernames.
202  if ( $wgUser && $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
203  $req = $this->getUserVariant( $wgUser );
204  } elseif ( !$req ) {
205  $req = $this->getHeaderVariant();
206  }
207 
208  if ( $wgDefaultLanguageVariant && !$req ) {
209  $req = $this->validateVariant( $wgDefaultLanguageVariant );
210  }
211 
212  $req = $this->validateVariant( $req );
213 
214  // This function, unlike the other get*Variant functions, is
215  // not memoized (i.e. there return value is not cached) since
216  // new information might appear during processing after this
217  // is first called.
218  if ( $req ) {
219  return $req;
220  }
222  }
223 
229  public function getDefaultVariant() {
231 
232  $req = $this->getURLVariant();
233 
234  if ( !$req ) {
235  $req = $this->getHeaderVariant();
236  }
237 
238  if ( $wgDefaultLanguageVariant && !$req ) {
239  $req = $this->validateVariant( $wgDefaultLanguageVariant );
240  }
241 
242  if ( $req ) {
243  return $req;
244  }
246  }
247 
257  public function validateVariant( $variant = null ) {
258  if ( $variant === null ) {
259  return null;
260  }
261  // Our internal variants are always lower-case; the variant we
262  // are validating may have mixed case.
263  $variant = LanguageCode::replaceDeprecatedCodes( strtolower( $variant ) );
264  if ( in_array( $variant, $this->mVariants ) ) {
265  return $variant;
266  }
267  // Browsers are supposed to use BCP 47 standard in the
268  // Accept-Language header, but not all of our internal
269  // mediawiki variant codes are BCP 47. Map BCP 47 code
270  // to our internal code.
271  foreach ( $this->mVariants as $v ) {
272  // Case-insensitive match (BCP 47 is mixed case)
273  if ( strtolower( LanguageCode::bcp47( $v ) ) === $variant ) {
274  return $v;
275  }
276  }
277  return null;
278  }
279 
285  public function getURLVariant() {
286  global $wgRequest;
287 
288  if ( $this->mURLVariant ) {
289  return $this->mURLVariant;
290  }
291 
292  // see if the preference is set in the request
293  $ret = $wgRequest->getText( 'variant' );
294 
295  if ( !$ret ) {
296  $ret = $wgRequest->getVal( 'uselang' );
297  }
298 
299  $this->mURLVariant = $this->validateVariant( $ret );
300  return $this->mURLVariant;
301  }
302 
309  protected function getUserVariant( User $user ) {
310  // This should only be called within the class after the user is known to be
311  // safe to load and and logged in, but check just in case.
312  if ( !$user->isSafeToLoad() ) {
313  return false;
314  }
315 
316  if ( $user->isLoggedIn() ) {
317  // Get language variant preference from logged in users
318  if (
319  $this->mMainLanguageCode ==
320  MediaWikiServices::getInstance()->getContentLanguage()->getCode()
321  ) {
322  $ret = $user->getOption( 'variant' );
323  } else {
324  $ret = $user->getOption( 'variant-' . $this->mMainLanguageCode );
325  }
326  } else {
327  // figure out user lang without constructing wgLang to avoid
328  // infinite recursion
329  $ret = $user->getOption( 'language' );
330  }
331 
332  $this->mUserVariant = $this->validateVariant( $ret );
333  return $this->mUserVariant;
334  }
335 
341  protected function getHeaderVariant() {
342  global $wgRequest;
343 
344  if ( $this->mHeaderVariant ) {
345  return $this->mHeaderVariant;
346  }
347 
348  // See if some supported language variant is set in the
349  // HTTP header.
350  $languages = array_keys( $wgRequest->getAcceptLang() );
351  if ( empty( $languages ) ) {
352  return null;
353  }
354 
355  $fallbackLanguages = [];
356  foreach ( $languages as $language ) {
357  $this->mHeaderVariant = $this->validateVariant( $language );
358  if ( $this->mHeaderVariant ) {
359  break;
360  }
361 
362  // To see if there are fallbacks of current language.
363  // We record these fallback variants, and process
364  // them later.
365  $fallbacks = $this->getVariantFallbacks( $language );
366  if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
367  $fallbackLanguages[] = $fallbacks;
368  } elseif ( is_array( $fallbacks ) ) {
369  $fallbackLanguages =
370  array_merge( $fallbackLanguages, $fallbacks );
371  }
372  }
373 
374  if ( !$this->mHeaderVariant ) {
375  // process fallback languages now
376  $fallback_languages = array_unique( $fallbackLanguages );
377  foreach ( $fallback_languages as $language ) {
378  $this->mHeaderVariant = $this->validateVariant( $language );
379  if ( $this->mHeaderVariant ) {
380  break;
381  }
382  }
383  }
384 
385  return $this->mHeaderVariant;
386  }
387 
398  public function autoConvert( $text, $toVariant = false ) {
399  $this->loadTables();
400 
401  if ( !$toVariant ) {
402  $toVariant = $this->getPreferredVariant();
403  if ( !$toVariant ) {
404  return $text;
405  }
406  }
407 
408  if ( $this->guessVariant( $text, $toVariant ) ) {
409  return $text;
410  }
411  /* we convert everything except:
412  1. HTML markups (anything between < and >)
413  2. HTML entities
414  3. placeholders created by the parser
415  IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
416  Minimize use of backtracking where possible.
417  */
418  static $reg;
419  if ( $reg === null ) {
420  $marker = '|' . Parser::MARKER_PREFIX . '[^\x7f]++\x7f';
421 
422  // this one is needed when the text is inside an HTML markup
423  $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
424 
425  // Optimize for the common case where these tags have
426  // few or no children. Thus try and possesively get as much as
427  // possible, and only engage in backtracking when we hit a '<'.
428 
429  // disable convert to variants between <code> tags
430  $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
431  // disable conversion of <script> tags
432  $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
433  // disable conversion of <pre> tags
434  $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
435  // The "|.*+)" at the end, is in case we missed some part of html syntax,
436  // we will fail securely (hopefully) by matching the rest of the string.
437  $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
438 
439  $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
440  '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
441  }
442  $startPos = 0;
443  $sourceBlob = '';
444  $literalBlob = '';
445 
446  // Guard against delimiter nulls in the input
447  // (should never happen: see T159174)
448  $text = str_replace( "\000", '', $text );
449  $text = str_replace( "\004", '', $text );
450 
451  $markupMatches = null;
452  $elementMatches = null;
453 
454  // We add a marker (\004) at the end of text, to ensure we always match the
455  // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
456  $textWithMarker = $text . "\004";
457  while ( $startPos < strlen( $text ) ) {
458  if ( preg_match( $reg, $textWithMarker, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
459  $elementPos = $markupMatches[0][1];
460  $element = $markupMatches[0][0];
461  if ( $element === "\004" ) {
462  // We hit the end.
463  $elementPos = strlen( $text );
464  $element = '';
465  } elseif ( substr( $element, -1 ) === "\004" ) {
466  // This can sometimes happen if we have
467  // unclosed html tags (For example
468  // when converting a title attribute
469  // during a recursive call that contains
470  // a &lt; e.g. <div title="&lt;">.
471  $element = substr( $element, 0, -1 );
472  }
473  } else {
474  // If we hit here, then Language Converter could be tricked
475  // into doing an XSS, so we refuse to translate.
476  // If non-crazy input manages to reach this code path,
477  // we should consider it a bug.
478  $log = LoggerFactory::getInstance( 'languageconverter' );
479  $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
480  . ". Disabling language conversion for this page.",
481  [
482  "method" => __METHOD__,
483  "variant" => $toVariant,
484  "startOfText" => substr( $text, 0, 500 )
485  ]
486  );
487  return $text;
488  }
489  // Queue the part before the markup for translation in a batch
490  $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
491 
492  // Advance to the next position
493  $startPos = $elementPos + strlen( $element );
494 
495  // Translate any alt or title attributes inside the matched element
496  if ( $element !== ''
497  && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
498  ) {
499  // FIXME, this decodes entities, so if you have something
500  // like <div title="foo&lt;bar"> the bar won't get
501  // translated since after entity decoding it looks like
502  // unclosed html and we call this method recursively
503  // on attributes.
504  $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
505  // Ensure self-closing tags stay self-closing.
506  $close = substr( $elementMatches[2], -1 ) === '/' ? ' /' : '';
507  $changed = false;
508  foreach ( [ 'title', 'alt' ] as $attrName ) {
509  if ( !isset( $attrs[$attrName] ) ) {
510  continue;
511  }
512  $attr = $attrs[$attrName];
513  // Don't convert URLs
514  if ( !strpos( $attr, '://' ) ) {
515  $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
516  }
517 
518  if ( $attr !== $attrs[$attrName] ) {
519  $attrs[$attrName] = $attr;
520  $changed = true;
521  }
522  }
523  if ( $changed ) {
524  $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
525  $close . $elementMatches[3];
526  }
527  }
528  $literalBlob .= $element . "\000";
529  }
530 
531  // Do the main translation batch
532  $translatedBlob = $this->translate( $sourceBlob, $toVariant );
533 
534  // Put the output back together
535  $translatedIter = StringUtils::explode( "\000", $translatedBlob );
536  $literalIter = StringUtils::explode( "\000", $literalBlob );
537  $output = '';
538  while ( $translatedIter->valid() && $literalIter->valid() ) {
539  $output .= $translatedIter->current();
540  $output .= $literalIter->current();
541  $translatedIter->next();
542  $literalIter->next();
543  }
544 
545  return $output;
546  }
547 
557  public function translate( $text, $variant ) {
558  // If $text is empty or only includes spaces, do nothing
559  // Otherwise translate it
560  if ( trim( $text ) ) {
561  $this->loadTables();
562  $text = $this->mTables[$variant]->replace( $text );
563  }
564  return $text;
565  }
566 
573  public function autoConvertToAllVariants( $text ) {
574  $this->loadTables();
575 
576  $ret = [];
577  foreach ( $this->mVariants as $variant ) {
578  $ret[$variant] = $this->translate( $text, $variant );
579  }
580 
581  return $ret;
582  }
583 
589  protected function applyManualConv( ConverterRule $convRule ) {
590  // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
591  // title conversion.
592  // T26072: $mConvRuleTitle was overwritten by other manual
593  // rule(s) not for title, this breaks the title conversion.
594  $newConvRuleTitle = $convRule->getTitle();
595  if ( $newConvRuleTitle ) {
596  // So I add an empty check for getTitle()
597  $this->mConvRuleTitle = $newConvRuleTitle;
598  }
599 
600  // merge/remove manual conversion rules to/from global table
601  $convTable = $convRule->getConvTable();
602  $action = $convRule->getRulesAction();
603  foreach ( $convTable as $variant => $pair ) {
604  $v = $this->validateVariant( $variant );
605  if ( !$v ) {
606  continue;
607  }
608 
609  if ( $action == 'add' ) {
610  // More efficient than array_merge(), about 2.5 times.
611  foreach ( $pair as $from => $to ) {
612  $this->mTables[$v]->setPair( $from, $to );
613  }
614  } elseif ( $action == 'remove' ) {
615  $this->mTables[$v]->removeArray( $pair );
616  }
617  }
618  }
619 
627  public function convertTitle( LinkTarget $linkTarget ) {
628  $variant = $this->getPreferredVariant();
629  $index = $linkTarget->getNamespace();
630  if ( $index !== NS_MAIN ) {
631  $text = $this->convertNamespace( $index, $variant ) . ':';
632  } else {
633  $text = '';
634  }
635  $text .= $this->translate( $linkTarget->getText(), $variant );
636 
637  return $text;
638  }
639 
647  public function convertNamespace( $index, $variant = null ) {
648  if ( $index === NS_MAIN ) {
649  return '';
650  }
651 
652  if ( $variant === null ) {
653  $variant = $this->getPreferredVariant();
654  }
655 
656  $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
657  $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
658  $nsVariantText = $cache->get( $key );
659  if ( $nsVariantText !== false ) {
660  return $nsVariantText;
661  }
662 
663  // First check if a message gives a converted name in the target variant.
664  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
665  if ( $nsConvMsg->exists() ) {
666  $nsVariantText = $nsConvMsg->plain();
667  }
668 
669  // Then check if a message gives a converted name in content language
670  // which needs extra translation to the target variant.
671  if ( $nsVariantText === false ) {
672  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
673  if ( $nsConvMsg->exists() ) {
674  $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
675  }
676  }
677 
678  if ( $nsVariantText === false ) {
679  // No message exists, retrieve it from the target variant's namespace names.
680  $mLangObj = MediaWikiServices::getInstance()
681  ->getLanguageFactory()
682  ->getLanguage( $variant );
683  $nsVariantText = $mLangObj->getFormattedNsText( $index );
684  }
685 
686  $cache->set( $key, $nsVariantText, 60 );
687 
688  return $nsVariantText;
689  }
690 
709  public function convert( $text ) {
710  $variant = $this->getPreferredVariant();
711  return $this->convertTo( $text, $variant );
712  }
713 
723  public function convertTo( $text, $variant ) {
725  if ( $wgDisableLangConversion ) {
726  return $text;
727  }
728  // Reset converter state for a new converter run.
729  $this->mConvRuleTitle = false;
730  return $this->recursiveConvertTopLevel( $text, $variant );
731  }
732 
742  protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
743  $startPos = 0;
744  $out = '';
745  $length = strlen( $text );
746  $shouldConvert = !$this->guessVariant( $text, $variant );
747  $continue = true;
748 
749  $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
750  $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
751  // phpcs:ignore Generic.Files.LineLength
752  $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
753  // @phan-suppress-next-line PhanRedundantConditionInLoop
754  while ( $startPos < $length && $continue ) {
755  $continue = preg_match(
756  // Only match -{ outside of html.
757  "/$noScript|$noStyle|$noHtml|-\{/",
758  $text,
759  $m,
760  PREG_OFFSET_CAPTURE,
761  $startPos
762  );
763 
764  if ( !$continue ) {
765  // No more markup, append final segment
766  $fragment = substr( $text, $startPos );
767  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
768  return $out;
769  }
770 
771  // Offset of the match of the regex pattern.
772  $pos = $m[0][1];
773 
774  // Append initial segment
775  $fragment = substr( $text, $startPos, $pos - $startPos );
776  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
777  // -{ marker found, not in attribute
778  // Advance position up to -{ marker.
779  $startPos = $pos;
780  // Do recursive conversion
781  // Note: This passes $startPos by reference, and advances it.
782  $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
783  }
784  return $out;
785  }
786 
798  protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
799  // Quick sanity check (no function calls)
800  if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
801  throw new MWException( __METHOD__ . ': invalid input string' );
802  }
803 
804  $startPos += 2;
805  $inner = '';
806  $warningDone = false;
807  $length = strlen( $text );
808 
809  while ( $startPos < $length ) {
810  $m = false;
811  preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
812  if ( !$m ) {
813  // Unclosed rule
814  break;
815  }
816 
817  $token = $m[0][0];
818  $pos = $m[0][1];
819 
820  // Markup found
821  // Append initial segment
822  $inner .= substr( $text, $startPos, $pos - $startPos );
823 
824  // Advance position
825  $startPos = $pos;
826 
827  switch ( $token ) {
828  case '-{':
829  // Check max depth
830  if ( $depth >= $this->mMaxDepth ) {
831  $inner .= '-{';
832  if ( !$warningDone ) {
833  $inner .= '<span class="error">' .
834  wfMessage( 'language-converter-depth-warning' )
835  ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
836  '</span>';
837  $warningDone = true;
838  }
839  $startPos += 2;
840  break;
841  }
842  // Recursively parse another rule
843  $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
844  break;
845  case '}-':
846  // Apply the rule
847  $startPos += 2;
848  $rule = new ConverterRule( $inner, $this );
849  $rule->parse( $variant );
850  $this->applyManualConv( $rule );
851  return $rule->getDisplay();
852  default:
853  throw new MWException( __METHOD__ . ': invalid regex match' );
854  }
855  }
856 
857  // Unclosed rule
858  if ( $startPos < $length ) {
859  $inner .= substr( $text, $startPos );
860  }
861  $startPos = $length;
862  return '-{' . $this->autoConvert( $inner, $variant );
863  }
864 
876  public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
877  # If the article has already existed, there is no need to
878  # check it again, otherwise it may cause a fault.
879  if ( is_object( $nt ) && $nt->exists() ) {
880  return;
881  }
882 
884  $isredir = $wgRequest->getText( 'redirect', 'yes' );
885  $action = $wgRequest->getText( 'action' );
886  if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
887  $action = 'view';
888  }
889  $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
890  $disableLinkConversion = $wgDisableLangConversion
892  $linkBatch = new LinkBatch();
893 
894  $ns = NS_MAIN;
895 
896  if ( $disableLinkConversion ||
897  ( !$ignoreOtherCond &&
898  ( $isredir == 'no'
899  || $action == 'edit'
900  || $action == 'submit'
901  || $linkconvert == 'no' ) ) ) {
902  return;
903  }
904 
905  if ( is_object( $nt ) ) {
906  $ns = $nt->getNamespace();
907  }
908 
909  $variants = $this->autoConvertToAllVariants( $link );
910  if ( !$variants ) { // give up
911  return;
912  }
913 
914  $titles = [];
915 
916  foreach ( $variants as $v ) {
917  if ( $v != $link ) {
918  $varnt = Title::newFromText( $v, $ns );
919  if ( $varnt !== null ) {
920  $linkBatch->addObj( $varnt );
921  $titles[] = $varnt;
922  }
923  }
924  }
925 
926  // fetch all variants in single query
927  $linkBatch->execute();
928 
929  foreach ( $titles as $varnt ) {
930  if ( $varnt->getArticleID() > 0 ) {
931  $nt = $varnt;
932  $link = $varnt->getText();
933  break;
934  }
935  }
936  }
937 
943  public function getExtraHashOptions() {
944  $variant = $this->getPreferredVariant();
945 
946  return '!' . $variant;
947  }
948 
959  public function guessVariant( $text, $variant ) {
960  return false;
961  }
962 
969  protected function loadDefaultTables() {
970  $class = static::class;
971  throw new MWException( "Must implement loadDefaultTables() method in class $class" );
972  }
973 
979  protected function loadTables( $fromCache = true ) {
981 
982  if ( $this->mTablesLoaded ) {
983  return;
984  }
985 
986  $this->mTablesLoaded = true;
987  // Do not use null as starting value, as that would confuse phan a lot.
988  $this->mTables = [];
990  $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode );
991  if ( $fromCache ) {
992  $this->mTables = $cache->get( $cacheKey );
993  }
994  if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
995  // not in cache, or we need a fresh reload.
996  // We will first load the default tables
997  // then update them using things in MediaWiki:Conversiontable/*
998  $this->loadDefaultTables();
999  foreach ( $this->mVariants as $var ) {
1000  $cached = $this->parseCachedTable( $var );
1001  // @phan-suppress-next-next-line PhanTypeArraySuspiciousNullable
1002  // FIXME: $this->mTables could theoretically be null here
1003  $this->mTables[$var]->mergeArray( $cached );
1004  }
1005 
1006  $this->postLoadTables();
1007  $this->mTables[self::CACHE_VERSION_KEY] = true;
1008 
1009  $cache->set( $cacheKey, $this->mTables, 43200 );
1010  }
1011  }
1012 
1016  protected function postLoadTables() {
1017  }
1018 
1026  private function reloadTables() {
1027  if ( $this->mTables ) {
1028  // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
1029  unset( $this->mTables );
1030  }
1031 
1032  $this->mTablesLoaded = false;
1033  $this->loadTables( false );
1034  }
1035 
1055  private function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1056  static $parsed = [];
1057 
1058  $key = 'Conversiontable/' . $code;
1059  if ( $subpage ) {
1060  $key .= '/' . $subpage;
1061  }
1062  if ( array_key_exists( $key, $parsed ) ) {
1063  return [];
1064  }
1065 
1066  $parsed[$key] = true;
1067 
1068  if ( $subpage === '' ) {
1069  $messageCache = MediaWikiServices::getInstance()->getMessageCache();
1070  $txt = $messageCache->getMsgFromNamespace( $key, $code );
1071  } else {
1072  $txt = false;
1074  if ( $title && $title->exists() ) {
1075  $revision = MediaWikiServices::getInstance()
1076  ->getRevisionLookup()
1077  ->getRevisionByTitle( $title );
1078  if ( $revision ) {
1079  $model = $revision->getSlot(
1080  SlotRecord::MAIN,
1081  RevisionRecord::RAW
1082  )->getModel();
1083  if ( $model == CONTENT_MODEL_WIKITEXT ) {
1084  // @phan-suppress-next-line PhanUndeclaredMethod
1085  $txt = $revision->getContent(
1086  SlotRecord::MAIN,
1087  RevisionRecord::RAW
1088  )->getText();
1089  }
1090 
1091  // @todo in the future, use a specialized content model, perhaps based on json!
1092  }
1093  }
1094  }
1095 
1096  # Nothing to parse if there's no text
1097  if ( $txt === false || $txt === null || $txt === '' ) {
1098  return [];
1099  }
1100 
1101  // get all subpage links of the form
1102  // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1103  $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
1104  ':Conversiontable';
1105  $subs = StringUtils::explode( '[[', $txt );
1106  $sublinks = [];
1107  foreach ( $subs as $sub ) {
1108  $link = explode( ']]', $sub, 2 );
1109  if ( count( $link ) != 2 ) {
1110  continue;
1111  }
1112  $b = explode( '|', $link[0], 2 );
1113  $b = explode( '/', trim( $b[0] ), 3 );
1114  if ( count( $b ) == 3 ) {
1115  $sublink = $b[2];
1116  } else {
1117  $sublink = '';
1118  }
1119 
1120  if ( $b[0] == $linkhead && $b[1] == $code ) {
1121  $sublinks[] = $sublink;
1122  }
1123  }
1124 
1125  // parse the mappings in this page
1126  $blocks = StringUtils::explode( '-{', $txt );
1127  $ret = [];
1128  $first = true;
1129  foreach ( $blocks as $block ) {
1130  if ( $first ) {
1131  // Skip the part before the first -{
1132  $first = false;
1133  continue;
1134  }
1135  $mappings = explode( '}-', $block, 2 )[0];
1136  $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1137  $table = StringUtils::explode( ';', $stripped );
1138  foreach ( $table as $t ) {
1139  $m = explode( '=>', $t, 3 );
1140  if ( count( $m ) != 2 ) {
1141  continue;
1142  }
1143  // trim any trailling comments starting with '//'
1144  $tt = explode( '//', $m[1], 2 );
1145  $ret[trim( $m[0] )] = trim( $tt[0] );
1146  }
1147  }
1148 
1149  // recursively parse the subpages
1150  if ( $recursive ) {
1151  foreach ( $sublinks as $link ) {
1152  $s = $this->parseCachedTable( $code, $link, $recursive );
1153  $ret = $s + $ret;
1154  }
1155  }
1156 
1157  if ( $this->mUcfirst ) {
1158  foreach ( $ret as $k => $v ) {
1159  $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1160  }
1161  }
1162  return $ret;
1163  }
1164 
1173  public function markNoConversion( $text, $noParse = false ) {
1174  # don't mark if already marked
1175  if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1176  return $text;
1177  }
1178 
1179  $ret = "-{R|$text}-";
1180  return $ret;
1181  }
1182 
1191  public function convertCategoryKey( $key ) {
1192  return $key;
1193  }
1194 
1201  public function updateConversionTable( LinkTarget $linkTarget ) {
1202  if ( $linkTarget->getNamespace() === NS_MEDIAWIKI ) {
1203  $t = explode( '/', $linkTarget->getDBkey(), 3 );
1204  $c = count( $t );
1205  if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1206  if ( $this->validateVariant( $t[1] ) ) {
1207  $this->reloadTables();
1208  }
1209  }
1210  }
1211  }
1212 
1217  public function getVarSeparatorPattern() {
1218  if ( $this->mVarSeparatorPattern === null ) {
1219  // varsep_pattern for preg_split:
1220  // text should be splited by ";" only if a valid variant
1221  // name exist after the markup, for example:
1222  // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1223  // <span style="font-size:120%;">yyy</span>;}-
1224  // we should split it as:
1225  // [
1226  // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1227  // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1228  // [2] => ''
1229  // ]
1230  $expandedVariants = [];
1231  foreach ( $this->mVariants as $variant ) {
1232  $expandedVariants[ $variant ] = 1;
1233  // Accept standard BCP 47 names for variants as well.
1234  $expandedVariants[ LanguageCode::bcp47( $variant ) ] = 1;
1235  }
1236  // Accept old deprecated names for variants
1237  foreach ( LanguageCode::getDeprecatedCodeMapping() as $old => $new ) {
1238  if ( isset( $expandedVariants[ $new ] ) ) {
1239  $expandedVariants[ $old ] = 1;
1240  }
1241  }
1242 
1243  $pat = '/;\s*(?=';
1244  foreach ( $expandedVariants as $variant => $ignore ) {
1245  // zh-hans:xxx;zh-hant:yyy
1246  $pat .= $variant . '\s*:|';
1247  // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1248  $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1249  }
1250  $pat .= '\s*$)/';
1251  $this->mVarSeparatorPattern = $pat;
1252  }
1254  }
1255 
1263  public function hasVariants() {
1264  return count( $this->getVariants() ) > 1;
1265  }
1266 
1277  public function hasVariant( $variant ) {
1278  return $variant && ( $variant === $this->validateVariant( $variant ) );
1279  }
1280 
1289  public function convertHtml( $text ) {
1290  return htmlspecialchars( $this->convert( $text ) );
1291  }
1292 }
LanguageConverter\getVarSeparatorPattern
getVarSeparatorPattern()
Get the cached separator pattern for ConverterRule::parseRules()
Definition: LanguageConverter.php:1217
LanguageCode\replaceDeprecatedCodes
static replaceDeprecatedCodes( $code)
Replace deprecated language codes that were used in previous versions of MediaWiki to up-to-date,...
Definition: LanguageCode.php:161
LanguageConverter\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: LanguageConverter.php:1277
ConverterRule
The rules used for language conversion, this processes the rules extracted by Parser from the -{ }- w...
Definition: ConverterRule.php:28
LanguageCode\getDeprecatedCodeMapping
static getDeprecatedCodeMapping()
Returns a mapping of deprecated language codes that were used in previous versions of MediaWiki to up...
Definition: LanguageCode.php:124
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:328
LanguageConverter\$mMaxDepth
$mMaxDepth
Definition: LanguageConverter.php:87
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
MediaWiki\Linker\LinkTarget\getText
getText()
Returns the link in text form, without namespace prefix or fragment.
LanguageConverter\getConvRuleTitle
getConvRuleTitle()
Get the title produced by the conversion rule.
Definition: LanguageConverter.php:184
LanguageConverter\__construct
__construct( $langobj, $maincode, $variants=[], $variantfallbacks=[], $flags=[], $manualLevel=[])
Definition: LanguageConverter.php:100
$wgDisabledVariants
$wgDisabledVariants
Disabled variants array of language variant conversion.
Definition: DefaultSettings.php:3269
LanguageConverter\getExtraHashOptions
getExtraHashOptions()
Returns language specific hash options.
Definition: LanguageConverter.php:943
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:35
LanguageConverter\CACHE_VERSION_KEY
const CACHE_VERSION_KEY
Definition: LanguageConverter.php:90
LanguageConverter\$mUcfirst
$mUcfirst
Definition: LanguageConverter.php:82
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:157
LanguageConverter\$mLangObj
Language $mLangObj
Definition: LanguageConverter.php:78
LanguageConverter\$mURLVariant
$mURLVariant
Definition: LanguageConverter.php:84
LanguageConverter\$mManualLevel
$mManualLevel
Definition: LanguageConverter.php:73
LanguageConverter\updateConversionTable
updateConversionTable(LinkTarget $linkTarget)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
Definition: LanguageConverter.php:1201
LanguageConverter\loadDefaultTables
loadDefaultTables()
Load default conversion tables.
Definition: LanguageConverter.php:969
LanguageConverter\$mConvRuleTitle
$mConvRuleTitle
Definition: LanguageConverter.php:83
LanguageConverter\$mVarSeparatorPattern
$mVarSeparatorPattern
Definition: LanguageConverter.php:88
Html\expandAttributes
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition: Html.php:480
LanguageConverter\$mVariants
string[] $mVariants
Definition: LanguageConverter.php:62
$wgDisableTitleConversion
$wgDisableTitleConversion
Whether to enable language variant conversion for links.
Definition: DefaultSettings.php:3247
LanguageConverter\getURLVariant
getURLVariant()
Get the variant specified in the URL.
Definition: LanguageConverter.php:285
LanguageConverter\findVariantLink
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
Definition: LanguageConverter.php:876
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
LanguageConverter\$mVariantNames
$mVariantNames
Definition: LanguageConverter.php:64
$s
$s
Definition: mergeMessageFileList.php:185
User\isSafeToLoad
isSafeToLoad()
Test if it's safe to load this User object.
Definition: User.php:301
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:224
LanguageConverter\$mTables
ReplacementArray[] bool[] $mTables
Definition: LanguageConverter.php:70
Parser\MARKER_PREFIX
const MARKER_PREFIX
Definition: Parser.php:145
LanguageConverter\$mMainLanguageCode
$mMainLanguageCode
Definition: LanguageConverter.php:57
LanguageConverter\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: LanguageConverter.php:1263
LanguageConverter\$mHeaderVariant
$mHeaderVariant
Definition: LanguageConverter.php:86
LanguageConverter\$mUserVariant
$mUserVariant
Definition: LanguageConverter.php:85
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
LanguageConverter\getVariantFallbacks
getVariantFallbacks( $variant)
In case some variant is not defined in the markup, we need to have some fallback.
Definition: LanguageConverter.php:176
LanguageConverter\reloadTables
reloadTables()
Reload the conversion tables.
Definition: LanguageConverter.php:1026
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
LanguageConverter\validateVariant
validateVariant( $variant=null)
Validate the variant and return an appropriate strict internal variant code if one exists.
Definition: LanguageConverter.php:257
MWException
MediaWiki exception.
Definition: MWException.php:29
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
LanguageConverter\getVariants
getVariants()
Get all valid variants.
Definition: LanguageConverter.php:161
$wgLanguageConverterCacheType
$wgLanguageConverterCacheType
The cache type for storing language conversion tables, which are used when parsing certain text and i...
Definition: DefaultSettings.php:2481
LanguageConverter\recursiveConvertTopLevel
recursiveConvertTopLevel( $text, $variant, $depth=0)
Recursively convert text on the outside.
Definition: LanguageConverter.php:742
$wgDefaultLanguageVariant
$wgDefaultLanguageVariant
Default variant code, if false, the default will be the language code.
Definition: DefaultSettings.php:3252
StringUtils\explode
static explode( $separator, $subject)
Workalike for explode() with limited memory usage.
Definition: StringUtils.php:326
LanguageConverter\translate
translate( $text, $variant)
Translate a string to a variant.
Definition: LanguageConverter.php:557
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:78
LanguageConverter\getDefaultVariant
getDefaultVariant()
Get default variant.
Definition: LanguageConverter.php:229
$title
$title
Definition: testCompression.php:38
LanguageConverter\recursiveConvertRule
recursiveConvertRule( $text, $variant, &$startPos, $depth=0)
Recursively convert text on the inside.
Definition: LanguageConverter.php:798
$wgDisableLangConversion
$wgDisableLangConversion
Whether to enable language variant conversion.
Definition: DefaultSettings.php:3242
deprecatePublicProperty
deprecatePublicProperty( $property, $version, $class=null, $component=null)
Mark a property as deprecated.
Definition: DeprecationHelper.php:68
LanguageConverter\postLoadTables
postLoadTables()
Hook for post processing after conversion tables are loaded.
Definition: LanguageConverter.php:1016
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
LanguageConverter\$mTablesLoaded
$mTablesLoaded
Definition: LanguageConverter.php:65
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:28
ConverterRule\getConvTable
getConvTable()
Get conversion table.
Definition: ConverterRule.php:492
User\getOption
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2591
LanguageConverter\convertCategoryKey
convertCategoryKey( $key)
Convert the sorting key for category links.
Definition: LanguageConverter.php:1191
LanguageConverter\parseCachedTable
parseCachedTable( $code, $subpage='', $recursive=true)
Parse the conversion table stored in the cache.
Definition: LanguageConverter.php:1055
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:682
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
LanguageConverter\getPreferredVariant
getPreferredVariant()
Get preferred language variant.
Definition: LanguageConverter.php:192
LanguageConverter\markNoConversion
markNoConversion( $text, $noParse=false)
Enclose a string with the "no conversion" tag.
Definition: LanguageConverter.php:1173
LanguageConverter\autoConvert
autoConvert( $text, $toVariant=false)
Dictionary-based conversion.
Definition: LanguageConverter.php:398
LanguageConverter\$mDescCodeSep
$mDescCodeSep
Definition: LanguageConverter.php:80
LanguageConverter\convert
convert( $text)
Convert text to different variants of a language.
Definition: LanguageConverter.php:709
LanguageConverter\loadTables
loadTables( $fromCache=true)
Load conversion tables either from the cache or the disk.
Definition: LanguageConverter.php:979
LanguageConverter\getUserVariant
getUserVariant(User $user)
Determine if the user has a variant set.
Definition: LanguageConverter.php:309
LanguageConverter\$mFlags
$mFlags
Definition: LanguageConverter.php:79
LanguageConverter\$languagesWithVariants
static array $languagesWithVariants
languages supporting variants
Definition: LanguageConverter.php:43
ConverterRule\getRulesAction
getRulesAction()
Return how deal with conversion rules.
Definition: ConverterRule.php:483
$cache
$cache
Definition: mcc.php:33
User\isLoggedIn
isLoggedIn()
Get whether the user is logged in.
Definition: User.php:3003
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
LanguageConverter\$mDescVarSep
$mDescVarSep
Definition: LanguageConverter.php:81
LanguageConverter\convertTitle
convertTitle(LinkTarget $linkTarget)
Auto convert a LinkTarget object to a readable string in the preferred variant.
Definition: LanguageConverter.php:627
LanguageConverter\applyManualConv
applyManualConv(ConverterRule $convRule)
Apply manual conversion rules.
Definition: LanguageConverter.php:589
LanguageConverter\autoConvertToAllVariants
autoConvertToAllVariants( $text)
Call translate() to convert text to all valid variants.
Definition: LanguageConverter.php:573
Sanitizer\decodeTagAttributes
static decodeTagAttributes( $text)
Return an associative array of attribute names and values from a partial tag string.
Definition: Sanitizer.php:1008
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:77
LanguageConverter\convertTo
convertTo( $text, $variant)
Same as convert() except a extra parameter to custom variant.
Definition: LanguageConverter.php:723
$t
$t
Definition: testCompression.php:74
LanguageConverter\getHeaderVariant
getHeaderVariant()
Determine the language variant from the Accept-Language header.
Definition: LanguageConverter.php:341
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:644
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
DeprecationHelper
trait DeprecationHelper
Use this trait in classes which have properties for which public access is deprecated.
Definition: DeprecationHelper.php:45
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:55
LanguageConverter\guessVariant
guessVariant( $text, $variant)
Guess if a text is written in a variant.
Definition: LanguageConverter.php:959
LanguageConverter\$mVariantFallbacks
$mVariantFallbacks
Definition: LanguageConverter.php:63
LanguageConverter
Base class for multi-variant language conversion.
Definition: LanguageConverter.php:35
ConverterRule\getTitle
getTitle()
Get converted title.
Definition: ConverterRule.php:475
LanguageConverter\convertHtml
convertHtml( $text)
Perform output conversion on a string, and encode for safe HTML output.
Definition: LanguageConverter.php:1289
LanguageConverter\convertNamespace
convertNamespace( $index, $variant=null)
Get the namespace display name in the preferred variant.
Definition: LanguageConverter.php:647
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:41
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:39