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