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