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