28cfea93cc297e0a017fcad4827392b0e30f8168
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2
3 /**
4 * Contains the LanguageConverter class and ConverterRule class
5 * @ingroup Language
6 *
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @file
9 */
10
11 /**
12 * Base class for language conversion.
13 * @ingroup Language
14 *
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
17 */
18 class LanguageConverter {
19 var $mPreferredVariant = '';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
23 var $mTables;
24 var $mNamespaceTables;
25 var $mDoTitleConvert = true, $mDoContentConvert = true;
26 // 'bidirectional' 'unidirectional' 'disable' for each variant
27 var $mManualLevel;
28 var $mTitleFromFlag = false;
29 var $mCacheKey;
30 var $mLangObj;
31 var $mMarkup;
32 var $mFlags;
33 var $mDescCodeSep = ':', $mDescVarSep = ';';
34 var $mUcfirst = false;
35 var $mTitleOriginal = '';
36 var $mTitleDisplay = '';
37
38 const CACHE_VERSION_KEY = 'VERSION 6';
39
40 /**
41 * Constructor
42 *
43 * @param $langobj The Language Object
44 * @param string $maincode the main language code of this language
45 * @param array $variants the supported variants of this language
46 * @param array $variantfallback the fallback language of each variant
47 * @param array $markup array defining the markup used for manual conversion
48 * @param array $flags array defining the custom strings that maps to the
49 * flags
50 * @param array $manualLevel limit for supported variants
51 * @public
52 */
53 function __construct( $langobj, $maincode,
54 $variants = array(),
55 $variantfallbacks = array(),
56 $markup = array(),
57 $flags = array(),
58 $manualLevel = array() ) {
59 $this->mLangObj = $langobj;
60 $this->mMainLanguageCode = $maincode;
61
62 global $wgDisabledVariants;
63 $this->mVariants = array();
64 foreach ( $variants as $variant ) {
65 if ( !in_array( $variant, $wgDisabledVariants ) ) {
66 $this->mVariants[] = $variant;
67 }
68 }
69 $this->mVariantFallbacks = $variantfallbacks;
70 global $wgLanguageNames;
71 $this->mVariantNames = $wgLanguageNames;
72 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
73 $m = array(
74 'begin' => '-{',
75 'flagsep' => '|',
76 'unidsep' => '=>', // for unidirectional conversion
77 'codesep' => ':',
78 'varsep' => ';',
79 'end' => '}-'
80 );
81 $this->mMarkup = array_merge( $m, $markup );
82 $f = array(
83 // 'S' show converted text
84 // '+' add rules for alltext
85 // 'E' the gave flags is error
86 // these flags above are reserved for program
87 'A' => 'A', // add rule for convert code (all text convert)
88 'T' => 'T', // title convert
89 'R' => 'R', // raw content
90 'D' => 'D', // convert description (subclass implement)
91 '-' => '-', // remove convert (not implement)
92 'H' => 'H', // add rule for convert code
93 // (but no display in placed code )
94 'N' => 'N' // current variant name
95 );
96 $this->mFlags = array_merge( $f, $flags );
97 foreach ( $this->mVariants as $v ) {
98 if ( array_key_exists( $v, $manualLevel ) ) {
99 $this->mManualLevel[$v] = $manualLevel[$v];
100 } else {
101 $this->mManualLevel[$v] = 'bidirectional';
102 }
103 $this->mNamespaceTables[$v] = array();
104 $this->mFlags[$v] = $v;
105 }
106 }
107
108 /**
109 * @public
110 */
111 function getVariants() {
112 return $this->mVariants;
113 }
114
115 /**
116 * In case some variant is not defined in the markup, we need
117 * to have some fallback. For example, in zh, normally people
118 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
119 * when zh-sg is preferred but not defined, we will pick zh-hans
120 * in this case. Right now this is only used by zh.
121 *
122 * @param string $v The language code of the variant
123 * @return string array The code of the fallback language or false if there
124 * is no fallback
125 * @public
126 */
127 function getVariantFallbacks( $v ) {
128 if ( isset( $this->mVariantFallbacks[$v] ) ) {
129 return $this->mVariantFallbacks[$v];
130 }
131 return $this->mMainLanguageCode;
132 }
133
134 /**
135 * Get preferred language variants.
136 * @param boolean $fromUser Get it from $wgUser's preferences
137 * @param boolean $fromHeader Get it from Accept-Language
138 * @return string the preferred language code
139 * @public
140 */
141 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
142 global $wgUser, $wgRequest, $wgVariantArticlePath,
143 $wgDefaultLanguageVariant, $wgOut;
144
145 // bug 21974, don't return $this->mPreferredVariant if $fromUser = false
146 if ( $fromUser && $this->mPreferredVariant ) {
147 return $this->mPreferredVariant;
148 }
149
150 // figure out user lang without constructing wgLang to avoid
151 // infinite recursion
152 if ( $fromUser ) {
153 $defaultUserLang = $wgUser->getOption( 'language' );
154 } else {
155 $defaultUserLang = $this->mMainLanguageCode;
156 }
157
158 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
159 // see if interface language is same as content, if not, prevent
160 // conversion
161
162 if ( ! in_array( $userLang, $this->mVariants ) ) {
163 // no conversion
164 $this->mPreferredVariant = $this->mMainLanguageCode;
165 return $this->mPreferredVariant;
166 }
167
168 // see if the preference is set in the request
169 $req = $wgRequest->getText( 'variant' );
170 if ( in_array( $req, $this->mVariants ) ) {
171 $this->mPreferredVariant = $req;
172 return $this->mPreferredVariant;
173 }
174
175 // get language variant preference from logged in users
176 // Don't call this on stub objects because that causes infinite
177 // recursion during initialisation
178 if ( $fromUser && $wgUser->isLoggedIn() ) {
179 $this->mPreferredVariant = $wgUser->getOption( 'variant' );
180 return $this->mPreferredVariant;
181 }
182
183 // see if default variant is globaly set
184 if ( $wgDefaultLanguageVariant != false
185 && in_array( $wgDefaultLanguageVariant, $this->mVariants ) ) {
186 $this->mPreferredVariant = $wgDefaultLanguageVariant;
187 return $this->mPreferredVariant;
188 }
189
190 if ( !$this->mPreferredVariant ) {
191 // see if some supported language variant is set in the
192 // http header, but we don't set the mPreferredVariant
193 // variable in case this is called before the user's
194 // preference is loaded
195
196 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
197 if ( $fromHeader && $acceptLanguage ) {
198 // explode by comma
199 $result = explode( ',', strtolower( $acceptLanguage ) );
200
201 $languages = array();
202
203 foreach ( $result as $elem ) {
204 // if $elem likes 'zh-cn;q=0.9'
205 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
206 // get the real language code likes 'zh-cn'
207 $languages[] = substr( $elem, 0, $posi );
208 } else {
209 $languages[] = $elem;
210 }
211 }
212
213 $fallback_languages = array();
214 foreach ( $languages as $language ) {
215 // strip whitespace
216 $language = trim( $language );
217 if ( in_array( $language, $this->mVariants ) ) {
218 return $language;
219 } else {
220 // To see if there are fallbacks of current language.
221 // We record these fallback variants, and process
222 // them later.
223 $fallbacks = $this->getVariantFallbacks( $language );
224 if ( is_string( $fallbacks ) ) {
225 $fallback_languages[] = $fallbacks;
226 } elseif ( is_array( $fallbacks ) ) {
227 $fallback_languages =
228 array_merge( $fallback_languages,
229 $fallbacks );
230 }
231 }
232 }
233
234 // process fallback languages now
235 $fallback_languages = array_unique( $fallback_languages );
236 foreach ( $fallback_languages as $language ) {
237 if ( in_array( $language, $this->mVariants ) ) {
238 return $language;
239 }
240 }
241 }
242 }
243 return $this->mMainLanguageCode;
244 }
245
246 /**
247 * Caption convert, base on preg_replace_callback.
248 *
249 * To convert text in "title" or "alt", like '<img alt="text" ... '
250 * or '<span title="text" ... '
251 *
252 * @return string like ' alt="yyyy"' or ' title="yyyy"'
253 * @private
254 */
255 function captionConvert( $matches ) {
256 $toVariant = $this->getPreferredVariant();
257 $title = $matches[1];
258 $text = $matches[2];
259 // we convert captions except URL
260 if ( !strpos( $text, '://' ) ) {
261 $text = $this->translate( $text, $toVariant );
262 }
263 return " $title=\"$text\"";
264 }
265
266 /**
267 * Dictionary-based conversion.
268 *
269 * @param string $text the text to be converted
270 * @param string $toVariant the target language code
271 * @return string the converted text
272 * @private
273 */
274 function autoConvert( $text, $toVariant = false ) {
275 $fname = 'LanguageConverter::autoConvert';
276
277 wfProfileIn( $fname );
278
279 if ( !$this->mTablesLoaded ) {
280 $this->loadTables();
281 }
282
283 if ( !$toVariant ) {
284 $toVariant = $this->getPreferredVariant();
285 }
286 if ( !in_array( $toVariant, $this->mVariants ) ) {
287 return $text;
288 }
289
290 /* we convert everything except:
291 1. html markups (anything between < and >)
292 2. html entities
293 3. place holders created by the parser
294 */
295 global $wgParser;
296 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
297 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
298 } else {
299 $marker = '';
300 }
301
302 // this one is needed when the text is inside an html markup
303 $htmlfix = '|<[^>]+$|^[^<>]*>';
304
305 // disable convert to variants between <code></code> tags
306 $codefix = '<code>.+?<\/code>|';
307 // disable convertsion of <script type="text/javascript"> ... </script>
308 $scriptfix = '<script.*?>.*?<\/script>|';
309 // disable conversion of <pre xxxx> ... </pre>
310 $prefix = '<pre.*?>.*?<\/pre>|';
311
312 $reg = '/' . $codefix . $scriptfix . $prefix .
313 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
314
315 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE );
316
317 $m = array_shift( $matches );
318
319 $ret = $this->translate( $m[0], $toVariant );
320 $mstart = $m[1] + strlen( $m[0] );
321
322 // enable convertsion of '<img alt="xxxx" ... '
323 // or '<span title="xxxx" ... '
324 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
325
326 $trtext = '';
327 $trtextmark = "\0";
328 $notrtext = array();
329 foreach ( $matches as $m ) {
330 $mark = substr( $text, $mstart, $m[1] - $mstart );
331 $mark = preg_replace_callback( $captionpattern,
332 array( &$this, 'captionConvert' ),
333 $mark );
334 // Let's convert the trtext only once,
335 // it would give us more performance improvement
336 $notrtext[] = $mark;
337 $trtext .= $m[0] . $trtextmark;
338 $mstart = $m[1] + strlen( $m[0] );
339 }
340 $notrtext[] = '';
341 $trtext = $this->translate( $trtext, $toVariant );
342 $trtext = StringUtils::explode( $trtextmark, $trtext );
343 foreach ( $trtext as $t ) {
344 $ret .= array_shift( $notrtext );
345 $ret .= $t;
346 }
347 wfProfileOut( $fname );
348 return $ret;
349 }
350
351 /**
352 * Translate a string to a variant.
353 * Doesn't process markup or do any of that other stuff, for that use
354 * convert().
355 *
356 * @param string $text Text to convert
357 * @param string $variant Variant language code
358 * @return string Translated text
359 * @private
360 */
361 function translate( $text, $variant ) {
362 wfProfileIn( __METHOD__ );
363 // If $text is empty or only includes spaces, do nothing
364 // Otherwise translate it
365 if ( trim( $text ) ) {
366 if ( !$this->mTablesLoaded ) {
367 $this->loadTables();
368 }
369 $text = $this->mTables[$variant]->replace( $text );
370 }
371 wfProfileOut( __METHOD__ );
372 return $text;
373 }
374
375 /**
376 * Convert text to all supported variants.
377 *
378 * @param string $text the text to be converted
379 * @return array of string
380 * @public
381 */
382 function autoConvertToAllVariants( $text ) {
383 $fname = 'LanguageConverter::autoConvertToAllVariants';
384 wfProfileIn( $fname );
385 if ( !$this->mTablesLoaded ) {
386 $this->loadTables();
387 }
388
389 $ret = array();
390 foreach ( $this->mVariants as $variant ) {
391 $ret[$variant] = $this->translate( $text, $variant );
392 }
393
394 wfProfileOut( $fname );
395 return $ret;
396 }
397
398 /**
399 * Convert link text to all supported variants.
400 *
401 * @param string $text the text to be converted
402 * @return array of string
403 * @public
404 */
405 function convertLinkToAllVariants( $text ) {
406 if ( !$this->mTablesLoaded ) {
407 $this->loadTables();
408 }
409
410 $ret = array();
411 $tarray = explode( $this->mMarkup['begin'], $text );
412 $tfirst = array_shift( $tarray );
413
414 foreach ( $this->mVariants as $variant ) {
415 $ret[$variant] = $this->translate( $tfirst, $variant );
416 }
417
418 foreach ( $tarray as $txt ) {
419 $marked = explode( $this->mMarkup['end'], $txt, 2 );
420
421 foreach ( $this->mVariants as $variant ) {
422 $ret[$variant] .= $this->mMarkup['begin'] . $marked[0] .
423 $this->mMarkup['end'];
424 if ( array_key_exists( 1, $marked ) ) {
425 $ret[$variant] .= $this->translate( $marked[1], $variant );
426 }
427 }
428
429 }
430
431 return $ret;
432 }
433
434 /**
435 * Prepare manual conversion table.
436 * @private
437 */
438 function applyManualConv( $convRule ) {
439 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
440 // conversion in title
441 $title = $convRule->getTitle();
442 if ( $title ) {
443 $this->mTitleFromFlag = true;
444 $this->mTitleDisplay = $title;
445 }
446
447 // apply manual conversion table to global table
448 $convTable = $convRule->getConvTable();
449 $action = $convRule->getRulesAction();
450 foreach ( $convTable as $variant => $pair ) {
451 if ( !in_array( $variant, $this->mVariants ) ) {
452 continue;
453 }
454
455 if ( $action == 'add' ) {
456 foreach ( $pair as $from => $to ) {
457 // to ensure that $from and $to not be left blank
458 // so $this->translate() could always return a string
459 if ( $from || $to ) {
460 // more efficient than array_merge(), about 2.5 times.
461 $this->mTables[$variant]->setPair( $from, $to );
462 }
463 }
464 } elseif ( $action == 'remove' ) {
465 $this->mTables[$variant]->removeArray( $pair );
466 }
467 }
468 }
469
470 /**
471 * Convert text using a parser object for context.
472 * @public
473 */
474 function parserConvert( $text, &$parser ) {
475 global $wgDisableLangConversion;
476 /* don't do anything if this is the conversion table */
477 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
478 && strpos( $parser->mTitle->getText(),
479 'Conversiontable' ) !== false ) {
480 return $text;
481 }
482
483 if ( $wgDisableLangConversion ) {
484 return $text;
485 }
486
487 $text = $this->convert( $text );
488
489 $this->convertTitle();
490 $parser->mOutput->setTitleText( $this->mTitleDisplay );
491
492 return $text;
493 }
494
495 /**
496 * Convert namespace.
497 * @param string $title the title included namespace
498 * @return array of string
499 * @private
500 */
501 function convertNamespace( $title, $variant ) {
502 $splittitle = explode( ':', $title );
503 if ( count( $splittitle ) < 2 ) {
504 return $title;
505 }
506 if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) ) {
507 $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
508 }
509 $ret = implode( ':', $splittitle );
510 return $ret;
511 }
512
513 /**
514 * Pre convert title. Store the original title $this->mTitleOrginal;
515 * store the default converted title to $this->mTitleDisplay.
516 * @private
517 */
518 function preConvertTitle( $text, $variant ) {
519 $this->mTitleOriginal = $text;
520
521 $text = $this->convertNamespace( $text, $variant );
522 $this->mTitleDisplay = $this->convert( $text );
523 }
524
525 /**
526 * Convert title.
527 * @private
528 */
529 function convertTitle() {
530 global $wgDisableTitleConversion, $wgUser, $wgRequest;
531 $isredir = $wgRequest->getText( 'redirect', 'yes' );
532 $action = $wgRequest->getText( 'action' );
533 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
534
535 // check for the global variable, __NOTC__ magic word, and user setting
536 if ( $wgDisableTitleConversion || !$this->mDoTitleConvert ||
537 $wgUser->getOption( 'noconvertlink' ) == 1 ) {
538 $this->mTitleDisplay = $this->mTitleOriginal;
539 } elseif ( $isredir == 'no'
540 || $action == 'edit'
541 || $linkconvert == 'no' ) {
542 // check for GET params
543 $this->mTitleDisplay = $this->mTitleOriginal;
544 }
545 }
546
547 /**
548 * Convert text to different variants of a language. The automatic
549 * conversion is done in autoConvert(). Here we parse the text
550 * marked with -{}-, which specifies special conversions of the
551 * text that can not be accomplished in autoConvert().
552 *
553 * Syntax of the markup:
554 * -{code1:text1;code2:text2;...}- or
555 * -{flags|code1:text1;code2:text2;...}- or
556 * -{text}- in which case no conversion should take place for text
557 *
558 * @param string $text text to be converted
559 * @param bool $isTitle whether this conversion is for the article title
560 * @return string converted text
561 * @public
562 */
563 function convert( $text, $isTitle = false ) {
564
565 $mw =& MagicWord::get( 'notitleconvert' );
566 if ( $mw->matchAndRemove( $text ) ) {
567 $this->mDoTitleConvert = false;
568 }
569 $mw =& MagicWord::get( 'nocontentconvert' );
570 if ( $mw->matchAndRemove( $text ) ) {
571 $this->mDoContentConvert = false;
572 }
573
574 // no conversion if redirecting
575 $mw =& MagicWord::get( 'redirect' );
576 if ( $mw->matchStart( $text ) ) {
577 return $text;
578 }
579
580 $plang = $this->getPreferredVariant();
581
582 // for title convertion
583 if ( $isTitle ) {
584 $this->preConvertTitle( $text, $plang );
585 return $text;
586 }
587
588 $tarray = StringUtils::explode( $this->mMarkup['end'], $text );
589 $text = '';
590
591 foreach ( $tarray as $txt ) {
592
593 $marked = explode( $this->mMarkup['begin'], $txt, 2 );
594
595 if ( $this->mDoContentConvert ) {
596 // Bug 19620: should convert a string immediately after a
597 // new rule added.
598 $text .= $this->autoConvert( $marked[0], $plang );
599 } else {
600 $text .= $marked[0];
601 }
602
603 if ( array_key_exists( 1, $marked ) ) {
604 $crule = new ConverterRule( $marked[1], $this );
605 $crule->parse( $plang );
606 $text .= $crule->getDisplay();
607 $this->applyManualConv( $crule );
608 } else {
609 $text .= $this->mMarkup['end'];
610 }
611 }
612
613 // Remove the last delimiter (wasn't real)
614 $text = substr( $text, 0, - strlen( $this->mMarkup['end'] ) );
615 return $text;
616 }
617
618 /**
619 * If a language supports multiple variants, it is
620 * possible that non-existing link in one variant
621 * actually exists in another variant. This function
622 * tries to find it. See e.g. LanguageZh.php
623 *
624 * @param string $link the name of the link
625 * @param mixed $nt the title object of the link
626 * @param boolean $ignoreOtherCond: to disable other conditions when
627 * we need to transclude a template or update a category's link
628 * @return null the input parameters may be modified upon return
629 * @public
630 */
631 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
632 # If the article has already existed, there is no need to
633 # check it again, otherwise it may cause a fault.
634 if ( is_object( $nt ) && $nt->exists() ) {
635 return;
636 }
637
638 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
639 $wgUser;
640 $isredir = $wgRequest->getText( 'redirect', 'yes' );
641 $action = $wgRequest->getText( 'action' );
642 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
643 $disableLinkConversion = $wgDisableLangConversion
644 || $wgDisableTitleConversion;
645 $linkBatch = new LinkBatch();
646
647 $ns = NS_MAIN;
648
649 if ( $disableLinkConversion ||
650 ( !$ignoreOtherCond &&
651 ( $isredir == 'no'
652 || $action == 'edit'
653 || $action == 'submit'
654 || $linkconvert == 'no'
655 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
656 return;
657 }
658
659 if ( is_object( $nt ) ) {
660 $ns = $nt->getNamespace();
661 }
662
663 $variants = $this->autoConvertToAllVariants( $link );
664 if ( $variants == false ) { // give up
665 return;
666 }
667
668 $titles = array();
669
670 foreach ( $variants as $v ) {
671 if ( $v != $link ) {
672 $varnt = Title::newFromText( $v, $ns );
673 if ( !is_null( $varnt ) ) {
674 $linkBatch->addObj( $varnt );
675 $titles[] = $varnt;
676 }
677 }
678 }
679
680 // fetch all variants in single query
681 $linkBatch->execute();
682
683 foreach ( $titles as $varnt ) {
684 if ( $varnt->getArticleID() > 0 ) {
685 $nt = $varnt;
686 $link = $varnt->getText();
687 break;
688 }
689 }
690 }
691
692 /**
693 * Returns language specific hash options.
694 *
695 * @public
696 */
697 function getExtraHashOptions() {
698 $variant = $this->getPreferredVariant();
699 return '!' . $variant ;
700 }
701
702 /**
703 * Get title text as defined in the body of the article text.
704 *
705 * @public
706 */
707 function getParsedTitle() {
708 return $this->mTitleDisplay;
709 }
710
711 /**
712 * Load default conversion tables.
713 * This method must be implemented in derived class.
714 *
715 * @private
716 */
717 function loadDefaultTables() {
718 $name = get_class( $this );
719 wfDie( "Must implement loadDefaultTables() method in class $name" );
720 }
721
722 /**
723 * Load conversion tables either from the cache or the disk.
724 * @private
725 */
726 function loadTables( $fromcache = true ) {
727 global $wgMemc;
728 if ( $this->mTablesLoaded ) {
729 return;
730 }
731 wfProfileIn( __METHOD__ );
732 $this->mTablesLoaded = true;
733 $this->mTables = false;
734 if ( $fromcache ) {
735 wfProfileIn( __METHOD__ . '-cache' );
736 $this->mTables = $wgMemc->get( $this->mCacheKey );
737 wfProfileOut( __METHOD__ . '-cache' );
738 }
739 if ( !$this->mTables
740 || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
741 wfProfileIn( __METHOD__ . '-recache' );
742 // not in cache, or we need a fresh reload.
743 // we will first load the default tables
744 // then update them using things in MediaWiki:Zhconversiontable/*
745 $this->loadDefaultTables();
746 foreach ( $this->mVariants as $var ) {
747 $cached = $this->parseCachedTable( $var );
748 $this->mTables[$var]->mergeArray( $cached );
749 }
750
751 $this->postLoadTables();
752 $this->mTables[self::CACHE_VERSION_KEY] = true;
753
754 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
755 wfProfileOut( __METHOD__ . '-recache' );
756 }
757 wfProfileOut( __METHOD__ );
758 }
759
760 /**
761 * Hook for post processig after conversion tables are loaded.
762 *
763 */
764 function postLoadTables() { }
765
766 /**
767 * Reload the conversion tables.
768 *
769 * @private
770 */
771 function reloadTables() {
772 if ( $this->mTables ) {
773 unset( $this->mTables );
774 }
775 $this->mTablesLoaded = false;
776 $this->loadTables( false );
777 }
778
779
780 /**
781 * Parse the conversion table stored in the cache.
782 *
783 * The tables should be in blocks of the following form:
784 * -{
785 * word => word ;
786 * word => word ;
787 * ...
788 * }-
789 *
790 * To make the tables more manageable, subpages are allowed
791 * and will be parsed recursively if $recursive == true.
792 *
793 */
794 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
795 global $wgMessageCache;
796 static $parsed = array();
797
798 if ( !is_object( $wgMessageCache ) ) {
799 return array();
800 }
801
802 $key = 'Conversiontable/' . $code;
803 if ( $subpage ) {
804 $key .= '/' . $subpage;
805 }
806 if ( array_key_exists( $key, $parsed ) ) {
807 return array();
808 }
809
810 if ( strpos( $code, '/' ) === false ) {
811 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
812 } else {
813 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
814 "Conversiontable/$code" );
815 if ( $title && $title->exists() ) {
816 $article = new Article( $title );
817 $txt = $article->getContents();
818 } else {
819 $txt = '';
820 }
821 }
822
823 // get all subpage links of the form
824 // [[MediaWiki:conversiontable/zh-xx/...|...]]
825 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
826 ':Conversiontable';
827 $subs = explode( '[[', $txt );
828 $sublinks = array();
829 foreach ( $subs as $sub ) {
830 $link = explode( ']]', $sub, 2 );
831 if ( count( $link ) != 2 ) {
832 continue;
833 }
834 $b = explode( '|', $link[0] );
835 $b = explode( '/', trim( $b[0] ), 3 );
836 if ( count( $b ) == 3 ) {
837 $sublink = $b[2];
838 } else {
839 $sublink = '';
840 }
841
842 if ( $b[0] == $linkhead && $b[1] == $code ) {
843 $sublinks[] = $sublink;
844 }
845 }
846
847
848 // parse the mappings in this page
849 $blocks = explode( $this->mMarkup['begin'], $txt );
850 array_shift( $blocks );
851 $ret = array();
852 foreach ( $blocks as $block ) {
853 $mappings = explode( $this->mMarkup['end'], $block, 2 );
854 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
855 $mappings[0] );
856 $table = explode( ';', $stripped );
857 foreach ( $table as $t ) {
858 $m = explode( '=>', $t );
859 if ( count( $m ) != 2 )
860 continue;
861 // trim any trailling comments starting with '//'
862 $tt = explode( '//', $m[1], 2 );
863 $ret[trim( $m[0] )] = trim( $tt[0] );
864 }
865 }
866 $parsed[$key] = true;
867
868
869 // recursively parse the subpages
870 if ( $recursive ) {
871 foreach ( $sublinks as $link ) {
872 $s = $this->parseCachedTable( $code, $link, $recursive );
873 $ret = array_merge( $ret, $s );
874 }
875 }
876
877 if ( $this->mUcfirst ) {
878 foreach ( $ret as $k => $v ) {
879 $ret[Language::ucfirst( $k )] = Language::ucfirst( $v );
880 }
881 }
882 return $ret;
883 }
884
885 /**
886 * Enclose a string with the "no conversion" tag. This is used by
887 * various functions in the Parser.
888 *
889 * @param string $text text to be tagged for no conversion
890 * @return string the tagged text
891 * @public
892 */
893 function markNoConversion( $text, $noParse = false ) {
894 # don't mark if already marked
895 if ( strpos( $text, $this->mMarkup['begin'] )
896 || strpos( $text, $this->mMarkup['end'] ) ) {
897 return $text;
898 }
899
900 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
901 return $ret;
902 }
903
904 /**
905 * Convert the sorting key for category links. This should make different
906 * keys that are variants of each other map to the same key.
907 */
908 function convertCategoryKey( $key ) {
909 return $key;
910 }
911
912 /**
913 * Hook to refresh the cache of conversion tables when
914 * MediaWiki:conversiontable* is updated.
915 * @private
916 */
917 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
918 $iswatch, $section, $flags, $revision ) {
919 $titleobj = $article->getTitle();
920 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
921 $title = $titleobj->getDBkey();
922 $t = explode( '/', $title, 3 );
923 $c = count( $t );
924 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
925 if ( in_array( $t[1], $this->mVariants ) ) {
926 $this->reloadTables();
927 }
928 }
929 }
930 return true;
931 }
932
933 /**
934 * Armour rendered math against conversion.
935 * Wrap math into rawoutput -{R| math }- syntax.
936 * @public
937 */
938 function armourMath( $text ) {
939 // we need to convert '-{' and '}-' to '-&#123;' and '&#125;-'
940 // to avoid a unwanted '}-' appeared after the math-image.
941 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
942 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
943 return $ret;
944 }
945 }
946
947 /**
948 * Parser for rules of language conversion , parse rules in -{ }- tag.
949 * @ingroup Language
950 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
951 */
952 class ConverterRule {
953 var $mText; // original text in -{text}-
954 var $mConverter; // LanguageConverter object
955 var $mManualCodeError = '<strong class="error">code error!</strong>';
956 var $mRuleDisplay = '';
957 var $mRuleTitle = false;
958 var $mRules = '';// string : the text of the rules
959 var $mRulesAction = 'none';
960 var $mFlags = array();
961 var $mConvTable = array();
962 var $mBidtable = array();// array of the translation in each variant
963 var $mUnidtable = array();// array of the translation in each variant
964
965 /**
966 * Constructor
967 *
968 * @param string $text the text between -{ and }-
969 * @param object $converter a LanguageConverter object
970 * @access public
971 */
972 function __construct( $text, $converter ) {
973 $this->mText = $text;
974 $this->mConverter = $converter;
975 foreach ( $converter->mVariants as $v ) {
976 $this->mConvTable[$v] = array();
977 }
978 }
979
980 /**
981 * Check if variants array in convert array.
982 *
983 * @param string $variant Variant language code
984 * @return string Translated text
985 * @public
986 */
987 function getTextInBidtable( $variants ) {
988 if ( is_string( $variants ) ) {
989 $variants = array( $variants );
990 }
991 if ( !is_array( $variants ) ) {
992 return false;
993 }
994 foreach ( $variants as $variant ) {
995 if ( array_key_exists( $variant, $this->mBidtable ) ) {
996 return $this->mBidtable[$variant];
997 }
998 }
999 return false;
1000 }
1001
1002 /**
1003 * Parse flags with syntax -{FLAG| ... }-
1004 * @private
1005 */
1006 function parseFlags() {
1007 $text = $this->mText;
1008 if ( strlen( $text ) < 2 ) {
1009 $this->mFlags = array( 'R' );
1010 $this->mRules = $text;
1011 return;
1012 }
1013
1014 $flags = array();
1015 $markup = $this->mConverter->mMarkup;
1016 $validFlags = $this->mConverter->mFlags;
1017 $variants = $this->mConverter->mVariants;
1018
1019 $tt = explode( $markup['flagsep'], $text, 2 );
1020 if ( count( $tt ) == 2 ) {
1021 $f = explode( $markup['varsep'], $tt[0] );
1022 foreach ( $f as $ff ) {
1023 $ff = trim( $ff );
1024 if ( array_key_exists( $ff, $validFlags )
1025 && !in_array( $validFlags[$ff], $flags ) ) {
1026 $flags[] = $validFlags[$ff];
1027 }
1028 }
1029 $rules = $tt[1];
1030 } else {
1031 $rules = $text;
1032 }
1033
1034 // check flags
1035 if ( in_array( 'R', $flags ) ) {
1036 $flags = array( 'R' );// remove other flags
1037 } elseif ( in_array( 'N', $flags ) ) {
1038 $flags = array( 'N' );// remove other flags
1039 } elseif ( in_array( '-', $flags ) ) {
1040 $flags = array( '-' );// remove other flags
1041 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1042 $flags[] = 'H';
1043 } elseif ( in_array( 'H', $flags ) ) {
1044 // replace A flag, and remove other flags except T
1045 $temp = array( '+', 'H' );
1046 if ( in_array( 'T', $flags ) ) {
1047 $temp[] = 'T';
1048 }
1049 if ( in_array( 'D', $flags ) ) {
1050 $temp[] = 'D';
1051 }
1052 $flags = $temp;
1053 } else {
1054 if ( in_array( 'A', $flags ) ) {
1055 $flags[] = '+';
1056 $flags[] = 'S';
1057 }
1058 if ( in_array( 'D', $flags ) ) {
1059 $flags = array_diff( $flags, array( 'S' ) );
1060 }
1061 $flags_temp = array();
1062 foreach ( $variants as $variant ) {
1063 // try to find flags like "zh-hans", "zh-hant"
1064 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1065 if ( in_array( $variant, $flags ) )
1066 $flags_temp[] = $variant;
1067 }
1068 if ( count( $flags_temp ) !== 0 ) {
1069 $flags = $flags_temp;
1070 }
1071 }
1072 if ( count( $flags ) == 0 ) {
1073 $flags = array( 'S' );
1074 }
1075 $this->mRules = $rules;
1076 $this->mFlags = $flags;
1077 }
1078
1079 /**
1080 * Generate conversion table.
1081 * @private
1082 */
1083 function parseRules() {
1084 $rules = $this->mRules;
1085 $flags = $this->mFlags;
1086 $bidtable = array();
1087 $unidtable = array();
1088 $markup = $this->mConverter->mMarkup;
1089 $variants = $this->mConverter->mVariants;
1090
1091 // varsep_pattern for preg_split:
1092 // text should be splited by ";" only if a valid variant
1093 // name exist after the markup, for example:
1094 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1095 // <span style="font-size:120%;">yyy</span>;}-
1096 // we should split it as:
1097 // array(
1098 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1099 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1100 // [2] => ''
1101 // )
1102 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1103 foreach ( $variants as $variant ) {
1104 // zh-hans:xxx;zh-hant:yyy
1105 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1106 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1107 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1108 . '\s*' . $markup['codesep'] . '|';
1109 }
1110 $varsep_pattern .= '\s*$)/';
1111
1112 $choice = preg_split( $varsep_pattern, $rules );
1113
1114 foreach ( $choice as $c ) {
1115 $v = explode( $markup['codesep'], $c, 2 );
1116 if ( count( $v ) != 2 ) {
1117 // syntax error, skip
1118 continue;
1119 }
1120 $to = trim( $v[1] );
1121 $v = trim( $v[0] );
1122 $u = explode( $markup['unidsep'], $v, 2 );
1123 // if $to is empty, strtr() could return a wrong result
1124 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1125 $bidtable[$v] = $to;
1126 } elseif ( count( $u ) == 2 ) {
1127 $from = trim( $u[0] );
1128 $v = trim( $u[1] );
1129 if ( array_key_exists( $v, $unidtable )
1130 && !is_array( $unidtable[$v] )
1131 && $to
1132 && in_array( $v, $variants ) ) {
1133 $unidtable[$v] = array( $from => $to );
1134 } elseif ( $to && in_array( $v, $variants ) ) {
1135 $unidtable[$v][$from] = $to;
1136 }
1137 }
1138 // syntax error, pass
1139 if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ) {
1140 $bidtable = array();
1141 $unidtable = array();
1142 break;
1143 }
1144 }
1145 $this->mBidtable = $bidtable;
1146 $this->mUnidtable = $unidtable;
1147 }
1148
1149 /**
1150 * @private
1151 */
1152 function getRulesDesc() {
1153 $codesep = $this->mConverter->mDescCodeSep;
1154 $varsep = $this->mConverter->mDescVarSep;
1155 $text = '';
1156 foreach ( $this->mBidtable as $k => $v ) {
1157 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1158 }
1159 foreach ( $this->mUnidtable as $k => $a ) {
1160 foreach ( $a as $from => $to ) {
1161 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1162 "$codesep$to$varsep";
1163 }
1164 }
1165 return $text;
1166 }
1167
1168 /**
1169 * Parse rules conversion.
1170 * @private
1171 */
1172 function getRuleConvertedStr( $variant, $doConvert ) {
1173 $bidtable = $this->mBidtable;
1174 $unidtable = $this->mUnidtable;
1175
1176 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1177 return $this->mRules;
1178 } elseif ( $doConvert ) { // the text converted
1179 // display current variant in bidirectional array
1180 $disp = $this->getTextInBidtable( $variant );
1181 // or display current variant in fallbacks
1182 if ( !$disp ) {
1183 $disp = $this->getTextInBidtable(
1184 $this->mConverter->getVariantFallbacks( $variant ) );
1185 }
1186 // or display current variant in unidirectional array
1187 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1188 $disp = array_values( $unidtable[$variant] );
1189 $disp = $disp[0];
1190 }
1191 // or display frist text under disable manual convert
1192 if ( !$disp
1193 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1194 if ( count( $bidtable ) > 0 ) {
1195 $disp = array_values( $bidtable );
1196 $disp = $disp[0];
1197 } else {
1198 $disp = array_values( $unidtable );
1199 $disp = array_values( $disp[0] );
1200 $disp = $disp[0];
1201 }
1202 }
1203 return $disp;
1204 } else { // no convert
1205 return $this->mRules;
1206 }
1207 }
1208
1209 /**
1210 * Generate conversion table for all text.
1211 * @private
1212 */
1213 function generateConvTable() {
1214 $flags = $this->mFlags;
1215 $bidtable = $this->mBidtable;
1216 $unidtable = $this->mUnidtable;
1217 $manLevel = $this->mConverter->mManualLevel;
1218
1219 $vmarked = array();
1220 foreach ( $this->mConverter->mVariants as $v ) {
1221 /* for bidirectional array
1222 fill in the missing variants, if any,
1223 with fallbacks */
1224 if ( !array_key_exists( $v, $bidtable ) ) {
1225 $variantFallbacks =
1226 $this->mConverter->getVariantFallbacks( $v );
1227 $vf = $this->getTextInBidtable( $variantFallbacks );
1228 if ( $vf ) {
1229 $bidtable[$v] = $vf;
1230 }
1231 }
1232
1233 if ( array_key_exists( $v, $bidtable ) ) {
1234 foreach ( $vmarked as $vo ) {
1235 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1236 // or -{H|zh:WordZh;zh-tw:WordTw}-
1237 // or -{-|zh:WordZh;zh-tw:WordTw}-
1238 // to introduce a custom mapping between
1239 // words WordZh and WordTw in the whole text
1240 if ( $manLevel[$v] == 'bidirectional' ) {
1241 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1242 }
1243 if ( $manLevel[$vo] == 'bidirectional' ) {
1244 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1245 }
1246 }
1247 $vmarked[] = $v;
1248 }
1249 /*for unidirectional array fill to convert tables */
1250 if ( ( $manLevel[$v] == 'bidirectional'
1251 || $manLevel[$v] == 'unidirectional' )
1252 && array_key_exists( $v, $unidtable ) ) {
1253 $ct = $this->mConvTable[$v];
1254 $this->mConvTable[$v] = array_merge( $ct, $unidtable[$v] );
1255 }
1256 }
1257 }
1258
1259 /**
1260 * Parse rules and flags.
1261 * @public
1262 */
1263 function parse( $variant = NULL ) {
1264 if ( !$variant ) {
1265 $variant = $this->mConverter->getPreferredVariant();
1266 }
1267
1268 $variants = $this->mConverter->mVariants;
1269 $this->parseFlags();
1270 $flags = $this->mFlags;
1271
1272 // convert to specified variant
1273 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1274 if ( count( array_diff( $flags, $variants ) ) == 0
1275 and count( $flags ) != 0 ) {
1276 // check if current variant in flags
1277 if ( in_array( $variant, $flags ) ) {
1278 // then convert <text to convert> to current language
1279 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1280 $variant );
1281 } else { // if current variant no in flags,
1282 // then we check its fallback variants.
1283 $variantFallbacks =
1284 $this->mConverter->getVariantFallbacks( $variant );
1285 foreach ( $variantFallbacks as $variantFallback ) {
1286 // if current variant's fallback exist in flags
1287 if ( in_array( $variantFallback, $flags ) ) {
1288 // then convert <text to convert> to fallback language
1289 $this->mRules =
1290 $this->mConverter->autoConvert( $this->mRules,
1291 $variantFallback );
1292 break;
1293 }
1294 }
1295 }
1296 $this->mFlags = $flags = array( 'R' );
1297 }
1298
1299 if ( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
1300 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1301 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1302
1303 $this->parseRules();
1304 }
1305 $rules = $this->mRules;
1306
1307 if ( count( $this->mBidtable ) == 0
1308 && count( $this->mUnidtable ) == 0 ) {
1309 if ( in_array( '+', $flags ) || in_array( '-', $flags ) ) {
1310 // fill all variants if text in -{A/H/-|text} without rules
1311 foreach ( $this->mConverter->mVariants as $v ) {
1312 $this->mBidtable[$v] = $rules;
1313 }
1314 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1315 $this->mFlags = $flags = array( 'R' );
1316 }
1317 }
1318
1319 if ( in_array( 'R', $flags ) ) {
1320 // if we don't do content convert, still strip the -{}- tags
1321 $this->mRuleDisplay = $rules;
1322 } elseif ( in_array( 'N', $flags ) ) {
1323 // proces N flag: output current variant name
1324 $this->mRuleDisplay =
1325 $this->mConverter->mVariantNames[ trim( $rules ) ];
1326 } elseif ( in_array( 'D', $flags ) ) {
1327 // proces D flag: output rules description
1328 $this->mRuleDisplay = $this->getRulesDesc();
1329 } elseif ( in_array( 'H', $flags ) || in_array( '-', $flags ) ) {
1330 // proces H,- flag or T only: output nothing
1331 $this->mRuleDisplay = '';
1332 } elseif ( in_array( 'S', $flags ) ) {
1333 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant,
1334 $this->mConverter->mDoContentConvert );
1335 } else {
1336 $this->mRuleDisplay = $this->mManualCodeError;
1337 }
1338 // proces T flag
1339 if ( in_array( 'T', $flags ) ) {
1340 $this->mRuleTitle = $this->getRuleConvertedStr( $variant,
1341 $this->mConverter->mDoTitleConvert );
1342 }
1343
1344 if ( in_array( '-', $flags ) ) {
1345 $this->mRulesAction = 'remove';
1346 }
1347 if ( in_array( '+', $flags ) ) {
1348 $this->mRulesAction = 'add';
1349 }
1350
1351 $this->generateConvTable();
1352 }
1353
1354 /**
1355 * @public
1356 */
1357 function hasRules() {
1358 // TODO:
1359 }
1360
1361 /**
1362 * Get display text on markup -{...}-
1363 * @public
1364 */
1365 function getDisplay() {
1366 return $this->mRuleDisplay;
1367 }
1368
1369 /**
1370 * Get converted title.
1371 * @public
1372 */
1373 function getTitle() {
1374 return $this->mRuleTitle;
1375 }
1376
1377 /**
1378 * Return how deal with conversion rules.
1379 * @public
1380 */
1381 function getRulesAction() {
1382 return $this->mRulesAction;
1383 }
1384
1385 /**
1386 * Get conversion table. ( bidirectional and unidirectional
1387 * conversion table )
1388 * @public
1389 */
1390 function getConvTable() {
1391 return $this->mConvTable;
1392 }
1393
1394 /**
1395 * Get conversion rules string.
1396 * @public
1397 */
1398 function getRules() {
1399 return $this->mRules;
1400 }
1401
1402 /**
1403 * Get conversion flags.
1404 * @public
1405 */
1406 function getFlags() {
1407 return $this->mFlags;
1408 }
1409 }