MediaWiki  1.27.2
LanguageConverter.php
Go to the documentation of this file.
1 <?php
37  static public $languagesWithVariants = [
38  'gan',
39  'iu',
40  'kk',
41  'ku',
42  'shi',
43  'sr',
44  'tg',
45  'uz',
46  'zh',
47  ];
48 
51  public $mTablesLoaded = false;
52  public $mTables;
53  // 'bidirectional' 'unidirectional' 'disable' for each variant
54  public $mManualLevel;
55 
59  public $mCacheKey;
60 
61  public $mLangObj;
62  public $mFlags;
63  public $mDescCodeSep = ':', $mDescVarSep = ';';
64  public $mUcfirst = false;
65  public $mConvRuleTitle = false;
66  public $mURLVariant;
67  public $mUserVariant;
69  public $mMaxDepth = 10;
71 
72  const CACHE_VERSION_KEY = 'VERSION 7';
73 
84  public function __construct( $langobj, $maincode, $variants = [],
85  $variantfallbacks = [], $flags = [],
86  $manualLevel = [] ) {
88  $this->mLangObj = $langobj;
89  $this->mMainLanguageCode = $maincode;
90  $this->mVariants = array_diff( $variants, $wgDisabledVariants );
91  $this->mVariantFallbacks = $variantfallbacks;
92  $this->mVariantNames = Language::fetchLanguageNames();
93  $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
94  $defaultflags = [
95  // 'S' show converted text
96  // '+' add rules for alltext
97  // 'E' the gave flags is error
98  // these flags above are reserved for program
99  'A' => 'A', // add rule for convert code (all text convert)
100  'T' => 'T', // title convert
101  'R' => 'R', // raw content
102  'D' => 'D', // convert description (subclass implement)
103  '-' => '-', // remove convert (not implement)
104  'H' => 'H', // add rule for convert code (but no display in placed code)
105  'N' => 'N' // current variant name
106  ];
107  $this->mFlags = array_merge( $defaultflags, $flags );
108  foreach ( $this->mVariants as $v ) {
109  if ( array_key_exists( $v, $manualLevel ) ) {
110  $this->mManualLevel[$v] = $manualLevel[$v];
111  } else {
112  $this->mManualLevel[$v] = 'bidirectional';
113  }
114  $this->mFlags[$v] = $v;
115  }
116  }
117 
124  public function getVariants() {
125  return $this->mVariants;
126  }
127 
139  public function getVariantFallbacks( $variant ) {
140  if ( isset( $this->mVariantFallbacks[$variant] ) ) {
141  return $this->mVariantFallbacks[$variant];
142  }
144  }
145 
150  public function getConvRuleTitle() {
151  return $this->mConvRuleTitle;
152  }
153 
158  public function getPreferredVariant() {
160 
161  $req = $this->getURLVariant();
162 
163  if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
164  $req = $this->getUserVariant();
165  } elseif ( !$req ) {
166  $req = $this->getHeaderVariant();
167  }
168 
169  if ( $wgDefaultLanguageVariant && !$req ) {
170  $req = $this->validateVariant( $wgDefaultLanguageVariant );
171  }
172 
173  // This function, unlike the other get*Variant functions, is
174  // not memoized (i.e. there return value is not cached) since
175  // new information might appear during processing after this
176  // is first called.
177  if ( $this->validateVariant( $req ) ) {
178  return $req;
179  }
181  }
182 
188  public function getDefaultVariant() {
190 
191  $req = $this->getURLVariant();
192 
193  if ( !$req ) {
194  $req = $this->getHeaderVariant();
195  }
196 
197  if ( $wgDefaultLanguageVariant && !$req ) {
198  $req = $this->validateVariant( $wgDefaultLanguageVariant );
199  }
200 
201  if ( $req ) {
202  return $req;
203  }
205  }
206 
212  public function validateVariant( $variant = null ) {
213  if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
214  return $variant;
215  }
216  return null;
217  }
218 
224  public function getURLVariant() {
226 
227  if ( $this->mURLVariant ) {
228  return $this->mURLVariant;
229  }
230 
231  // see if the preference is set in the request
232  $ret = $wgRequest->getText( 'variant' );
233 
234  if ( !$ret ) {
235  $ret = $wgRequest->getVal( 'uselang' );
236  }
237 
238  $this->mURLVariant = $this->validateVariant( $ret );
239  return $this->mURLVariant;
240  }
241 
247  protected function getUserVariant() {
249 
250  // memoizing this function wreaks havoc on parserTest.php
251  /*
252  if ( $this->mUserVariant ) {
253  return $this->mUserVariant;
254  }
255  */
256 
257  // Get language variant preference from logged in users
258  // Don't call this on stub objects because that causes infinite
259  // recursion during initialisation
260  if ( !$wgUser->isSafeToLoad() ) {
261  return false;
262  }
263  if ( $wgUser->isLoggedIn() ) {
264  if ( $this->mMainLanguageCode == $wgContLang->getCode() ) {
265  $ret = $wgUser->getOption( 'variant' );
266  } else {
267  $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode );
268  }
269  } else {
270  // figure out user lang without constructing wgLang to avoid
271  // infinite recursion
272  $ret = $wgUser->getOption( 'language' );
273  }
274 
275  $this->mUserVariant = $this->validateVariant( $ret );
276  return $this->mUserVariant;
277  }
278 
284  protected function getHeaderVariant() {
286 
287  if ( $this->mHeaderVariant ) {
288  return $this->mHeaderVariant;
289  }
290 
291  // see if some supported language variant is set in the
292  // HTTP header.
293  $languages = array_keys( $wgRequest->getAcceptLang() );
294  if ( empty( $languages ) ) {
295  return null;
296  }
297 
298  $fallbackLanguages = [];
299  foreach ( $languages as $language ) {
300  $this->mHeaderVariant = $this->validateVariant( $language );
301  if ( $this->mHeaderVariant ) {
302  break;
303  }
304 
305  // To see if there are fallbacks of current language.
306  // We record these fallback variants, and process
307  // them later.
308  $fallbacks = $this->getVariantFallbacks( $language );
309  if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
310  $fallbackLanguages[] = $fallbacks;
311  } elseif ( is_array( $fallbacks ) ) {
312  $fallbackLanguages =
313  array_merge( $fallbackLanguages, $fallbacks );
314  }
315  }
316 
317  if ( !$this->mHeaderVariant ) {
318  // process fallback languages now
319  $fallback_languages = array_unique( $fallbackLanguages );
320  foreach ( $fallback_languages as $language ) {
321  $this->mHeaderVariant = $this->validateVariant( $language );
322  if ( $this->mHeaderVariant ) {
323  break;
324  }
325  }
326  }
327 
328  return $this->mHeaderVariant;
329  }
330 
341  public function autoConvert( $text, $toVariant = false ) {
342 
343  $this->loadTables();
344 
345  if ( !$toVariant ) {
346  $toVariant = $this->getPreferredVariant();
347  if ( !$toVariant ) {
348  return $text;
349  }
350  }
351 
352  if ( $this->guessVariant( $text, $toVariant ) ) {
353  return $text;
354  }
355 
356  /* we convert everything except:
357  1. HTML markups (anything between < and >)
358  2. HTML entities
359  3. placeholders created by the parser
360  */
361  $marker = '|' . Parser::MARKER_PREFIX . '[\-a-zA-Z0-9]+';
362 
363  // this one is needed when the text is inside an HTML markup
364  $htmlfix = '|<[^>]+$|^[^<>]*>';
365 
366  // disable convert to variants between <code> tags
367  $codefix = '<code>.+?<\/code>|';
368  // disable conversion of <script> tags
369  $scriptfix = '<script.*?>.*?<\/script>|';
370  // disable conversion of <pre> tags
371  $prefix = '<pre.*?>.*?<\/pre>|';
372 
373  $reg = '/' . $codefix . $scriptfix . $prefix .
374  '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
375  $startPos = 0;
376  $sourceBlob = '';
377  $literalBlob = '';
378 
379  // Guard against delimiter nulls in the input
380  $text = str_replace( "\000", '', $text );
381 
382  $markupMatches = null;
383  $elementMatches = null;
384  while ( $startPos < strlen( $text ) ) {
385  if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
386  $elementPos = $markupMatches[0][1];
387  $element = $markupMatches[0][0];
388  } else {
389  $elementPos = strlen( $text );
390  $element = '';
391  }
392 
393  // Queue the part before the markup for translation in a batch
394  $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
395 
396  // Advance to the next position
397  $startPos = $elementPos + strlen( $element );
398 
399  // Translate any alt or title attributes inside the matched element
400  if ( $element !== ''
401  && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
402  ) {
403  $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
404  $changed = false;
405  foreach ( [ 'title', 'alt' ] as $attrName ) {
406  if ( !isset( $attrs[$attrName] ) ) {
407  continue;
408  }
409  $attr = $attrs[$attrName];
410  // Don't convert URLs
411  if ( !strpos( $attr, '://' ) ) {
412  $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
413  }
414 
415  // Remove HTML tags to avoid disrupting the layout
416  $attr = preg_replace( '/<[^>]+>/', '', $attr );
417  if ( $attr !== $attrs[$attrName] ) {
418  $attrs[$attrName] = $attr;
419  $changed = true;
420  }
421  }
422  if ( $changed ) {
423  $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
424  $elementMatches[3];
425  }
426  }
427  $literalBlob .= $element . "\000";
428  }
429 
430  // Do the main translation batch
431  $translatedBlob = $this->translate( $sourceBlob, $toVariant );
432 
433  // Put the output back together
434  $translatedIter = StringUtils::explode( "\000", $translatedBlob );
435  $literalIter = StringUtils::explode( "\000", $literalBlob );
436  $output = '';
437  while ( $translatedIter->valid() && $literalIter->valid() ) {
438  $output .= $translatedIter->current();
439  $output .= $literalIter->current();
440  $translatedIter->next();
441  $literalIter->next();
442  }
443 
444  return $output;
445  }
446 
456  public function translate( $text, $variant ) {
457  // If $text is empty or only includes spaces, do nothing
458  // Otherwise translate it
459  if ( trim( $text ) ) {
460  $this->loadTables();
461  $text = $this->mTables[$variant]->replace( $text );
462  }
463  return $text;
464  }
465 
472  public function autoConvertToAllVariants( $text ) {
473  $this->loadTables();
474 
475  $ret = [];
476  foreach ( $this->mVariants as $variant ) {
477  $ret[$variant] = $this->translate( $text, $variant );
478  }
479 
480  return $ret;
481  }
482 
488  protected function applyManualConv( $convRule ) {
489  // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
490  // title conversion.
491  // Bug 24072: $mConvRuleTitle was overwritten by other manual
492  // rule(s) not for title, this breaks the title conversion.
493  $newConvRuleTitle = $convRule->getTitle();
494  if ( $newConvRuleTitle ) {
495  // So I add an empty check for getTitle()
496  $this->mConvRuleTitle = $newConvRuleTitle;
497  }
498 
499  // merge/remove manual conversion rules to/from global table
500  $convTable = $convRule->getConvTable();
501  $action = $convRule->getRulesAction();
502  foreach ( $convTable as $variant => $pair ) {
503  if ( !$this->validateVariant( $variant ) ) {
504  continue;
505  }
506 
507  if ( $action == 'add' ) {
508  // More efficient than array_merge(), about 2.5 times.
509  foreach ( $pair as $from => $to ) {
510  $this->mTables[$variant]->setPair( $from, $to );
511  }
512  } elseif ( $action == 'remove' ) {
513  $this->mTables[$variant]->removeArray( $pair );
514  }
515  }
516  }
517 
525  public function convertTitle( $title ) {
526  $variant = $this->getPreferredVariant();
527  $index = $title->getNamespace();
528  if ( $index !== NS_MAIN ) {
529  $text = $this->convertNamespace( $index, $variant ) . ':';
530  } else {
531  $text = '';
532  }
533  $text .= $this->translate( $title->getText(), $variant );
534  return $text;
535  }
536 
544  public function convertNamespace( $index, $variant = null ) {
545  if ( $index === NS_MAIN ) {
546  return '';
547  }
548 
549  if ( $variant === null ) {
550  $variant = $this->getPreferredVariant();
551  }
552 
554  $key = wfMemcKey( 'languageconverter', 'namespace-text', $index, $variant );
555  $nsVariantText = $cache->get( $key );
556  if ( $nsVariantText !== false ) {
557  return $nsVariantText;
558  }
559 
560  // First check if a message gives a converted name in the target variant.
561  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
562  if ( $nsConvMsg->exists() ) {
563  $nsVariantText = $nsConvMsg->plain();
564  }
565 
566  // Then check if a message gives a converted name in content language
567  // which needs extra translation to the target variant.
568  if ( $nsVariantText === false ) {
569  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
570  if ( $nsConvMsg->exists() ) {
571  $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
572  }
573  }
574 
575  if ( $nsVariantText === false ) {
576  // No message exists, retrieve it from the target variant's namespace names.
577  $langObj = $this->mLangObj->factory( $variant );
578  $nsVariantText = $langObj->getFormattedNsText( $index );
579  }
580 
581  $cache->set( $key, $nsVariantText, 60 );
582 
583  return $nsVariantText;
584  }
585 
600  public function convert( $text ) {
601  $variant = $this->getPreferredVariant();
602  return $this->convertTo( $text, $variant );
603  }
604 
612  public function convertTo( $text, $variant ) {
614  if ( $wgDisableLangConversion ) {
615  return $text;
616  }
617  // Reset converter state for a new converter run.
618  $this->mConvRuleTitle = false;
619  return $this->recursiveConvertTopLevel( $text, $variant );
620  }
621 
631  protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
632  $startPos = 0;
633  $out = '';
634  $length = strlen( $text );
635  $shouldConvert = !$this->guessVariant( $text, $variant );
636 
637  while ( $startPos < $length ) {
638  $pos = strpos( $text, '-{', $startPos );
639 
640  if ( $pos === false ) {
641  // No more markup, append final segment
642  $fragment = substr( $text, $startPos );
643  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
644  return $out;
645  }
646 
647  // Markup found
648  // Append initial segment
649  $fragment = substr( $text, $startPos, $pos - $startPos );
650  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
651 
652  // Advance position
653  $startPos = $pos;
654 
655  // Do recursive conversion
656  $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
657  }
658 
659  return $out;
660  }
661 
673  protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
674  // Quick sanity check (no function calls)
675  if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
676  throw new MWException( __METHOD__ . ': invalid input string' );
677  }
678 
679  $startPos += 2;
680  $inner = '';
681  $warningDone = false;
682  $length = strlen( $text );
683 
684  while ( $startPos < $length ) {
685  $m = false;
686  preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
687  if ( !$m ) {
688  // Unclosed rule
689  break;
690  }
691 
692  $token = $m[0][0];
693  $pos = $m[0][1];
694 
695  // Markup found
696  // Append initial segment
697  $inner .= substr( $text, $startPos, $pos - $startPos );
698 
699  // Advance position
700  $startPos = $pos;
701 
702  switch ( $token ) {
703  case '-{':
704  // Check max depth
705  if ( $depth >= $this->mMaxDepth ) {
706  $inner .= '-{';
707  if ( !$warningDone ) {
708  $inner .= '<span class="error">' .
709  wfMessage( 'language-converter-depth-warning' )
710  ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
711  '</span>';
712  $warningDone = true;
713  }
714  $startPos += 2;
715  continue;
716  }
717  // Recursively parse another rule
718  $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
719  break;
720  case '}-':
721  // Apply the rule
722  $startPos += 2;
723  $rule = new ConverterRule( $inner, $this );
724  $rule->parse( $variant );
725  $this->applyManualConv( $rule );
726  return $rule->getDisplay();
727  default:
728  throw new MWException( __METHOD__ . ': invalid regex match' );
729  }
730  }
731 
732  // Unclosed rule
733  if ( $startPos < $length ) {
734  $inner .= substr( $text, $startPos );
735  }
736  $startPos = $length;
737  return '-{' . $this->autoConvert( $inner, $variant );
738  }
739 
751  public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
752  # If the article has already existed, there is no need to
753  # check it again, otherwise it may cause a fault.
754  if ( is_object( $nt ) && $nt->exists() ) {
755  return;
756  }
757 
759  $isredir = $wgRequest->getText( 'redirect', 'yes' );
760  $action = $wgRequest->getText( 'action' );
761  if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
762  $action = 'view';
763  }
764  $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
765  $disableLinkConversion = $wgDisableLangConversion
767  $linkBatch = new LinkBatch();
768 
769  $ns = NS_MAIN;
770 
771  if ( $disableLinkConversion ||
772  ( !$ignoreOtherCond &&
773  ( $isredir == 'no'
774  || $action == 'edit'
775  || $action == 'submit'
776  || $linkconvert == 'no' ) ) ) {
777  return;
778  }
779 
780  if ( is_object( $nt ) ) {
781  $ns = $nt->getNamespace();
782  }
783 
784  $variants = $this->autoConvertToAllVariants( $link );
785  if ( !$variants ) { // give up
786  return;
787  }
788 
789  $titles = [];
790 
791  foreach ( $variants as $v ) {
792  if ( $v != $link ) {
793  $varnt = Title::newFromText( $v, $ns );
794  if ( !is_null( $varnt ) ) {
795  $linkBatch->addObj( $varnt );
796  $titles[] = $varnt;
797  }
798  }
799  }
800 
801  // fetch all variants in single query
802  $linkBatch->execute();
803 
804  foreach ( $titles as $varnt ) {
805  if ( $varnt->getArticleID() > 0 ) {
806  $nt = $varnt;
807  $link = $varnt->getText();
808  break;
809  }
810  }
811  }
812 
818  public function getExtraHashOptions() {
819  $variant = $this->getPreferredVariant();
820 
821  return '!' . $variant;
822  }
823 
834  public function guessVariant( $text, $variant ) {
835  return false;
836  }
837 
845  function loadDefaultTables() {
846  $name = get_class( $this );
847 
848  throw new MWException( "Must implement loadDefaultTables() method in class $name" );
849  }
850 
856  function loadTables( $fromCache = true ) {
858 
859  if ( $this->mTablesLoaded ) {
860  return;
861  }
862 
863  $this->mTablesLoaded = true;
864  $this->mTables = false;
865  $cache = ObjectCache::getInstance( $wgLanguageConverterCacheType );
866  if ( $fromCache ) {
867  wfProfileIn( __METHOD__ . '-cache' );
868  $this->mTables = $cache->get( $this->mCacheKey );
869  wfProfileOut( __METHOD__ . '-cache' );
870  }
871  if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
872  wfProfileIn( __METHOD__ . '-recache' );
873  // not in cache, or we need a fresh reload.
874  // We will first load the default tables
875  // then update them using things in MediaWiki:Conversiontable/*
876  $this->loadDefaultTables();
877  foreach ( $this->mVariants as $var ) {
878  $cached = $this->parseCachedTable( $var );
879  $this->mTables[$var]->mergeArray( $cached );
880  }
881 
882  $this->postLoadTables();
883  $this->mTables[self::CACHE_VERSION_KEY] = true;
884 
885  $cache->set( $this->mCacheKey, $this->mTables, 43200 );
886  wfProfileOut( __METHOD__ . '-recache' );
887  }
888  }
889 
893  function postLoadTables() {
894  }
895 
901  function reloadTables() {
902  if ( $this->mTables ) {
903  unset( $this->mTables );
904  }
905 
906  $this->mTablesLoaded = false;
907  $this->loadTables( false );
908  }
909 
929  function parseCachedTable( $code, $subpage = '', $recursive = true ) {
930  static $parsed = [];
931 
932  $key = 'Conversiontable/' . $code;
933  if ( $subpage ) {
934  $key .= '/' . $subpage;
935  }
936  if ( array_key_exists( $key, $parsed ) ) {
937  return [];
938  }
939 
940  $parsed[$key] = true;
941 
942  if ( $subpage === '' ) {
943  $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
944  } else {
945  $txt = false;
947  if ( $title && $title->exists() ) {
948  $revision = Revision::newFromTitle( $title );
949  if ( $revision ) {
950  if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
951  $txt = $revision->getContent( Revision::RAW )->getNativeData();
952  }
953 
954  // @todo in the future, use a specialized content model, perhaps based on json!
955  }
956  }
957  }
958 
959  # Nothing to parse if there's no text
960  if ( $txt === false || $txt === null || $txt === '' ) {
961  return [];
962  }
963 
964  // get all subpage links of the form
965  // [[MediaWiki:Conversiontable/zh-xx/...|...]]
966  $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
967  ':Conversiontable';
968  $subs = StringUtils::explode( '[[', $txt );
969  $sublinks = [];
970  foreach ( $subs as $sub ) {
971  $link = explode( ']]', $sub, 2 );
972  if ( count( $link ) != 2 ) {
973  continue;
974  }
975  $b = explode( '|', $link[0], 2 );
976  $b = explode( '/', trim( $b[0] ), 3 );
977  if ( count( $b ) == 3 ) {
978  $sublink = $b[2];
979  } else {
980  $sublink = '';
981  }
982 
983  if ( $b[0] == $linkhead && $b[1] == $code ) {
984  $sublinks[] = $sublink;
985  }
986  }
987 
988  // parse the mappings in this page
989  $blocks = StringUtils::explode( '-{', $txt );
990  $ret = [];
991  $first = true;
992  foreach ( $blocks as $block ) {
993  if ( $first ) {
994  // Skip the part before the first -{
995  $first = false;
996  continue;
997  }
998  $mappings = explode( '}-', $block, 2 )[0];
999  $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1000  $table = StringUtils::explode( ';', $stripped );
1001  foreach ( $table as $t ) {
1002  $m = explode( '=>', $t, 3 );
1003  if ( count( $m ) != 2 ) {
1004  continue;
1005  }
1006  // trim any trailling comments starting with '//'
1007  $tt = explode( '//', $m[1], 2 );
1008  $ret[trim( $m[0] )] = trim( $tt[0] );
1009  }
1010  }
1011 
1012  // recursively parse the subpages
1013  if ( $recursive ) {
1014  foreach ( $sublinks as $link ) {
1015  $s = $this->parseCachedTable( $code, $link, $recursive );
1016  $ret = $s + $ret;
1017  }
1018  }
1019 
1020  if ( $this->mUcfirst ) {
1021  foreach ( $ret as $k => $v ) {
1022  $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1023  }
1024  }
1025  return $ret;
1026  }
1027 
1036  public function markNoConversion( $text, $noParse = false ) {
1037  # don't mark if already marked
1038  if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1039  return $text;
1040  }
1041 
1042  $ret = "-{R|$text}-";
1043  return $ret;
1044  }
1045 
1054  function convertCategoryKey( $key ) {
1055  return $key;
1056  }
1057 
1064  public function updateConversionTable( Title $titleobj ) {
1065  if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1066  $title = $titleobj->getDBkey();
1067  $t = explode( '/', $title, 3 );
1068  $c = count( $t );
1069  if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1070  if ( $this->validateVariant( $t[1] ) ) {
1071  $this->reloadTables();
1072  }
1073  }
1074  }
1075  }
1076 
1082  if ( is_null( $this->mVarSeparatorPattern ) ) {
1083  // varsep_pattern for preg_split:
1084  // text should be splited by ";" only if a valid variant
1085  // name exist after the markup, for example:
1086  // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1087  // <span style="font-size:120%;">yyy</span>;}-
1088  // we should split it as:
1089  // array(
1090  // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1091  // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1092  // [2] => ''
1093  // )
1094  $pat = '/;\s*(?=';
1095  foreach ( $this->mVariants as $variant ) {
1096  // zh-hans:xxx;zh-hant:yyy
1097  $pat .= $variant . '\s*:|';
1098  // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1099  $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1100  }
1101  $pat .= '\s*$)/';
1102  $this->mVarSeparatorPattern = $pat;
1103  }
1105  }
1106 }
convertCategoryKey($key)
Convert the sorting key for category links.
const MARKER_PREFIX
Definition: Parser.php:141
updateConversionTable(Title $titleobj)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
static decodeTagAttributes($text)
Return an associative array of attribute names and values from a partial tag string.
Definition: Sanitizer.php:1249
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:762
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:277
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
__construct($langobj, $maincode, $variants=[], $variantfallbacks=[], $flags=[], $manualLevel=[])
Constructor.
const NS_MAIN
Definition: Defines.php:69
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:893
convertTo($text, $variant)
Same as convert() except a extra parameter to custom variant.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
getVarSeparatorPattern()
Get the cached separator pattern for ConverterRule::parseRules()
static getInstance($id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:92
wfProfileIn($functionname)
Begin profiling of a function.
recursiveConvertTopLevel($text, $variant, $depth=0)
Recursively convert text on the outside.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
Base class for language conversion.
getExtraHashOptions()
Returns language specific hash options.
markNoConversion($text, $noParse=false)
Enclose a string with the "no conversion" tag.
parseCachedTable($code, $subpage= '', $recursive=true)
Parse the conversion table stored in the cache.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
loadTables($fromCache=true)
Load conversion tables either from the cache or the disk.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target...
Definition: Revision.php:117
static fetchLanguageNames($inLanguage=null, $include= 'mw')
Get an array of language names, indexed by code.
Definition: Language.php:798
postLoadTables()
Hook for post processing after conversion tables are loaded.
wfProfileOut($functionname= 'missing')
Stop profiling of a function.
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2581
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:31
getVariantFallbacks($variant)
In case some variant is not defined in the markup, we need to have some fallback. ...
getDBkey()
Get the main part with underscores.
Definition: Title.php:911
switch($options['output']) $languages
Definition: transstat.php:76
getURLVariant()
Get the variant specified in the URL.
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
recursiveConvertRule($text, $variant, &$startPos, $depth=0)
Recursively convert text on the inside.
reloadTables()
Reload the conversion tables.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
static newAccelerator($params=[], $fallback=null)
$cache
Definition: mcc.php:33
Parser for rules of language conversion , parse rules in -{ }- tag.
getUserVariant()
Determine if the user has a variant set.
translate($text, $variant)
Translate a string to a variant.
$wgLanguageConverterCacheType
The cache type for storing language conversion tables, which are used when parsing certain text and i...
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:548
$wgDisableTitleConversion
Whether to enable language variant conversion for links.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
$wgDisabledVariants
Disabled variants array of language variant conversion.
getVariants()
Get all valid variants.
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:934
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition: Html.php:472
const RAW
Definition: Revision.php:85
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$wgDisableLangConversion
Whether to enable language variant conversion.
$wgDefaultLanguageVariant
Default variant code, if false, the default will be the language code.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:762
const NS_MEDIAWIKI
Definition: Defines.php:77
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1004
$from
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:965
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
getHeaderVariant()
Determine the language variant from the Accept-Language header.
guessVariant($text, $variant)
Guess if a text is written in a variant.
string $mCacheKey
Memcached key name.
getDefaultVariant()
Get default variant.
applyManualConv($convRule)
Apply manual conversion rules.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
autoConvert($text, $toVariant=false)
Dictionary-based conversion.
getConvRuleTitle()
Get the title produced by the conversion rule.
convert($text)
Convert text to different variants of a language.
wfMemcKey()
Make a cache key for the local wiki.
static explode($separator, $subject)
Workalike for explode() with limited memory usage.
validateVariant($variant=null)
Validate the variant.
convertNamespace($index, $variant=null)
Get the namespace display name in the preferred variant.
const CACHE_NONE
Definition: Defines.php:102
static array $languagesWithVariants
languages supporting variants
getPreferredVariant()
Get preferred language variant.
autoConvertToAllVariants($text)
Call translate() to convert text to all valid variants.
loadDefaultTables()
Load default conversion tables.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:657
static singleton()
Get the signleton instance of this class.
$wgUser
Definition: Setup.php:794
convertTitle($title)
Auto convert a Title object to a readable string in the preferred variant.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310