Messages files rebuilt and partially stylized.
[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 // 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 // recursively parse the subpages
910 if ( $recursive ) {
911 foreach ( $sublinks as $link ) {
912 $s = $this->parseCachedTable( $code, $link, $recursive );
913 $ret = array_merge( $ret, $s );
914 }
915 }
916
917 if ( $this->mUcfirst ) {
918 foreach ( $ret as $k => $v ) {
919 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
920 }
921 }
922 return $ret;
923 }
924
925 /**
926 * Enclose a string with the "no conversion" tag. This is used by
927 * various functions in the Parser.
928 *
929 * @param $text String: text to be tagged for no conversion
930 * @param $noParse Unused (?)
931 * @return String: the tagged text
932 */
933 public function markNoConversion( $text, $noParse = false ) {
934 # don't mark if already marked
935 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
936 return $text;
937 }
938
939 $ret = "-{R|$text}-";
940 return $ret;
941 }
942
943 /**
944 * Convert the sorting key for category links. This should make different
945 * keys that are variants of each other map to the same key.
946 */
947 function convertCategoryKey( $key ) {
948 return $key;
949 }
950
951 /**
952 * Hook to refresh the cache of conversion tables when
953 * MediaWiki:conversiontable* is updated.
954 * @private
955 */
956 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
957 $iswatch, $section, $flags, $revision ) {
958 $titleobj = $article->getTitle();
959 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
960 $title = $titleobj->getDBkey();
961 $t = explode( '/', $title, 3 );
962 $c = count( $t );
963 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
964 if ( $this->validateVariant( $t[1] ) ) {
965 $this->reloadTables();
966 }
967 }
968 }
969 return true;
970 }
971
972 /**
973 * Armour rendered math against conversion.
974 * Wrap math into rawoutput -{R| math }- syntax.
975 */
976 public function armourMath( $text ) {
977 // we need to convert '-{' and '}-' to '-&#123;' and '&#125;-'
978 // to avoid a unwanted '}-' appeared after the math-image.
979 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
980 $ret = "-{R|$text}-";
981 return $ret;
982 }
983
984 /**
985 * Get the cached separator pattern for ConverterRule::parseRules()
986 */
987 function getVarSeparatorPattern() {
988 if ( is_null( $this->mVarSeparatorPattern ) ) {
989 // varsep_pattern for preg_split:
990 // text should be splited by ";" only if a valid variant
991 // name exist after the markup, for example:
992 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
993 // <span style="font-size:120%;">yyy</span>;}-
994 // we should split it as:
995 // array(
996 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
997 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
998 // [2] => ''
999 // )
1000 $pat = '/;\s*(?=';
1001 foreach ( $this->mVariants as $variant ) {
1002 // zh-hans:xxx;zh-hant:yyy
1003 $pat .= $variant . '\s*:|';
1004 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1005 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1006 }
1007 $pat .= '\s*$)/';
1008 $this->mVarSeparatorPattern = $pat;
1009 }
1010 return $this->mVarSeparatorPattern;
1011 }
1012 }
1013
1014 /**
1015 * Parser for rules of language conversion , parse rules in -{ }- tag.
1016 * @ingroup Language
1017 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1018 */
1019 class ConverterRule {
1020 var $mText; // original text in -{text}-
1021 var $mConverter; // LanguageConverter object
1022 var $mManualCodeError = '<strong class="error">code error!</strong>';
1023 var $mRuleDisplay = '';
1024 var $mRuleTitle = false;
1025 var $mRules = '';// string : the text of the rules
1026 var $mRulesAction = 'none';
1027 var $mFlags = array();
1028 var $mVariantFlags = array();
1029 var $mConvTable = array();
1030 var $mBidtable = array();// array of the translation in each variant
1031 var $mUnidtable = array();// array of the translation in each variant
1032
1033 /**
1034 * Constructor
1035 *
1036 * @param $text String: the text between -{ and }-
1037 * @param $converter LanguageConverter object
1038 */
1039 public function __construct( $text, $converter ) {
1040 $this->mText = $text;
1041 $this->mConverter = $converter;
1042 }
1043
1044 /**
1045 * Check if variants array in convert array.
1046 *
1047 * @param $variants Array or string: variant language code
1048 * @return String: translated text
1049 */
1050 public function getTextInBidtable( $variants ) {
1051 $variants = (array)$variants;
1052 if ( !$variants ) {
1053 return false;
1054 }
1055 foreach ( $variants as $variant ) {
1056 if ( isset( $this->mBidtable[$variant] ) ) {
1057 return $this->mBidtable[$variant];
1058 }
1059 }
1060 return false;
1061 }
1062
1063 /**
1064 * Parse flags with syntax -{FLAG| ... }-
1065 * @private
1066 */
1067 function parseFlags() {
1068 $text = $this->mText;
1069 $flags = array();
1070 $variantFlags = array();
1071
1072 $sepPos = strpos( $text, '|' );
1073 if ( $sepPos !== false ) {
1074 $validFlags = $this->mConverter->mFlags;
1075 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1076 foreach ( $f as $ff ) {
1077 $ff = trim( $ff );
1078 if ( isset( $validFlags[$ff] ) ) {
1079 $flags[$validFlags[$ff]] = true;
1080 }
1081 }
1082 $text = strval( substr( $text, $sepPos + 1 ) );
1083 }
1084
1085 if ( !$flags ) {
1086 $flags['S'] = true;
1087 } elseif ( isset( $flags['R'] ) ) {
1088 $flags = array( 'R' => true );// remove other flags
1089 } elseif ( isset( $flags['N'] ) ) {
1090 $flags = array( 'N' => true );// remove other flags
1091 } elseif ( isset( $flags['-'] ) ) {
1092 $flags = array( '-' => true );// remove other flags
1093 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1094 $flags['H'] = true;
1095 } elseif ( isset( $flags['H'] ) ) {
1096 // replace A flag, and remove other flags except T
1097 $temp = array( '+' => true, 'H' => true );
1098 if ( isset( $flags['T'] ) ) {
1099 $temp['T'] = true;
1100 }
1101 if ( isset( $flags['D'] ) ) {
1102 $temp['D'] = true;
1103 }
1104 $flags = $temp;
1105 } else {
1106 if ( isset( $flags['A'] ) ) {
1107 $flags['+'] = true;
1108 $flags['S'] = true;
1109 }
1110 if ( isset( $flags['D'] ) ) {
1111 unset( $flags['S'] );
1112 }
1113 // try to find flags like "zh-hans", "zh-hant"
1114 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1115 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1116 if ( $variantFlags ) {
1117 $variantFlags = array_flip( $variantFlags );
1118 $flags = array();
1119 }
1120 }
1121 $this->mVariantFlags = $variantFlags;
1122 $this->mRules = $text;
1123 $this->mFlags = $flags;
1124 }
1125
1126 /**
1127 * Generate conversion table.
1128 * @private
1129 */
1130 function parseRules() {
1131 $rules = $this->mRules;
1132 $flags = $this->mFlags;
1133 $bidtable = array();
1134 $unidtable = array();
1135 $variants = $this->mConverter->mVariants;
1136 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1137
1138 $choice = preg_split( $varsep_pattern, $rules );
1139
1140 foreach ( $choice as $c ) {
1141 $v = explode( ':', $c, 2 );
1142 if ( count( $v ) != 2 ) {
1143 // syntax error, skip
1144 continue;
1145 }
1146 $to = trim( $v[1] );
1147 $v = trim( $v[0] );
1148 $u = explode( '=>', $v, 2 );
1149 // if $to is empty, strtr() could return a wrong result
1150 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1151 $bidtable[$v] = $to;
1152 } elseif ( count( $u ) == 2 ) {
1153 $from = trim( $u[0] );
1154 $v = trim( $u[1] );
1155 if ( array_key_exists( $v, $unidtable )
1156 && !is_array( $unidtable[$v] )
1157 && $to
1158 && in_array( $v, $variants ) ) {
1159 $unidtable[$v] = array( $from => $to );
1160 } elseif ( $to && in_array( $v, $variants ) ) {
1161 $unidtable[$v][$from] = $to;
1162 }
1163 }
1164 // syntax error, pass
1165 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1166 $bidtable = array();
1167 $unidtable = array();
1168 break;
1169 }
1170 }
1171 $this->mBidtable = $bidtable;
1172 $this->mUnidtable = $unidtable;
1173 }
1174
1175 /**
1176 * @private
1177 */
1178 function getRulesDesc() {
1179 $codesep = $this->mConverter->mDescCodeSep;
1180 $varsep = $this->mConverter->mDescVarSep;
1181 $text = '';
1182 foreach ( $this->mBidtable as $k => $v ) {
1183 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1184 }
1185 foreach ( $this->mUnidtable as $k => $a ) {
1186 foreach ( $a as $from => $to ) {
1187 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1188 "$codesep$to$varsep";
1189 }
1190 }
1191 return $text;
1192 }
1193
1194 /**
1195 * Parse rules conversion.
1196 * @private
1197 */
1198 function getRuleConvertedStr( $variant ) {
1199 $bidtable = $this->mBidtable;
1200 $unidtable = $this->mUnidtable;
1201
1202 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1203 return $this->mRules;
1204 } else {
1205 // display current variant in bidirectional array
1206 $disp = $this->getTextInBidtable( $variant );
1207 // or display current variant in fallbacks
1208 if ( !$disp ) {
1209 $disp = $this->getTextInBidtable(
1210 $this->mConverter->getVariantFallbacks( $variant ) );
1211 }
1212 // or display current variant in unidirectional array
1213 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1214 $disp = array_values( $unidtable[$variant] );
1215 $disp = $disp[0];
1216 }
1217 // or display frist text under disable manual convert
1218 if ( !$disp
1219 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1220 if ( count( $bidtable ) > 0 ) {
1221 $disp = array_values( $bidtable );
1222 $disp = $disp[0];
1223 } else {
1224 $disp = array_values( $unidtable );
1225 $disp = array_values( $disp[0] );
1226 $disp = $disp[0];
1227 }
1228 }
1229 return $disp;
1230 }
1231 }
1232
1233 /**
1234 * Generate conversion table for all text.
1235 * @private
1236 */
1237 function generateConvTable() {
1238 // Special case optimisation
1239 if ( !$this->mBidtable && !$this->mUnidtable ) {
1240 $this->mConvTable = array();
1241 return;
1242 }
1243
1244 $bidtable = $this->mBidtable;
1245 $unidtable = $this->mUnidtable;
1246 $manLevel = $this->mConverter->mManualLevel;
1247
1248 $vmarked = array();
1249 foreach ( $this->mConverter->mVariants as $v ) {
1250 /* for bidirectional array
1251 fill in the missing variants, if any,
1252 with fallbacks */
1253 if ( !isset( $bidtable[$v] ) ) {
1254 $variantFallbacks =
1255 $this->mConverter->getVariantFallbacks( $v );
1256 $vf = $this->getTextInBidtable( $variantFallbacks );
1257 if ( $vf ) {
1258 $bidtable[$v] = $vf;
1259 }
1260 }
1261
1262 if ( isset( $bidtable[$v] ) ) {
1263 foreach ( $vmarked as $vo ) {
1264 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1265 // or -{H|zh:WordZh;zh-tw:WordTw}-
1266 // or -{-|zh:WordZh;zh-tw:WordTw}-
1267 // to introduce a custom mapping between
1268 // words WordZh and WordTw in the whole text
1269 if ( $manLevel[$v] == 'bidirectional' ) {
1270 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1271 }
1272 if ( $manLevel[$vo] == 'bidirectional' ) {
1273 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1274 }
1275 }
1276 $vmarked[] = $v;
1277 }
1278 /*for unidirectional array fill to convert tables */
1279 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1280 && isset( $unidtable[$v] ) )
1281 {
1282 if ( isset( $this->mConvTable[$v] ) ) {
1283 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1284 } else {
1285 $this->mConvTable[$v] = $unidtable[$v];
1286 }
1287 }
1288 }
1289 }
1290
1291 /**
1292 * Parse rules and flags.
1293 * @public
1294 */
1295 function parse( $variant = NULL ) {
1296 if ( !$variant ) {
1297 $variant = $this->mConverter->getPreferredVariant();
1298 }
1299
1300 $variants = $this->mConverter->mVariants;
1301 $this->parseFlags();
1302 $flags = $this->mFlags;
1303
1304 // convert to specified variant
1305 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1306 if ( $this->mVariantFlags ) {
1307 // check if current variant in flags
1308 if ( isset( $this->mVariantFlags[$variant] ) ) {
1309 // then convert <text to convert> to current language
1310 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1311 $variant );
1312 } else { // if current variant no in flags,
1313 // then we check its fallback variants.
1314 $variantFallbacks =
1315 $this->mConverter->getVariantFallbacks( $variant );
1316 foreach ( $variantFallbacks as $variantFallback ) {
1317 // if current variant's fallback exist in flags
1318 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1319 // then convert <text to convert> to fallback language
1320 $this->mRules =
1321 $this->mConverter->autoConvert( $this->mRules,
1322 $variantFallback );
1323 break;
1324 }
1325 }
1326 }
1327 $this->mFlags = $flags = array( 'R' => true );
1328 }
1329
1330 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1331 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1332 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1333 $this->parseRules();
1334 }
1335 $rules = $this->mRules;
1336
1337 if ( !$this->mBidtable && !$this->mUnidtable ) {
1338 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1339 // fill all variants if text in -{A/H/-|text} without rules
1340 foreach ( $this->mConverter->mVariants as $v ) {
1341 $this->mBidtable[$v] = $rules;
1342 }
1343 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1344 $this->mFlags = $flags = array( 'R' => true );
1345 }
1346 }
1347
1348 $this->mRuleDisplay = false;
1349 foreach ( $flags as $flag => $unused ) {
1350 switch ( $flag ) {
1351 case 'R':
1352 // if we don't do content convert, still strip the -{}- tags
1353 $this->mRuleDisplay = $rules;
1354 break;
1355 case 'N':
1356 // process N flag: output current variant name
1357 $ruleVar = trim( $rules );
1358 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1359 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1360 } else {
1361 $this->mRuleDisplay = '';
1362 }
1363 break;
1364 case 'D':
1365 // process D flag: output rules description
1366 $this->mRuleDisplay = $this->getRulesDesc();
1367 break;
1368 case 'H':
1369 // process H,- flag or T only: output nothing
1370 $this->mRuleDisplay = '';
1371 break;
1372 case '-':
1373 $this->mRulesAction = 'remove';
1374 $this->mRuleDisplay = '';
1375 break;
1376 case '+':
1377 $this->mRulesAction = 'add';
1378 $this->mRuleDisplay = '';
1379 break;
1380 case 'S':
1381 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1382 break;
1383 case 'T':
1384 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1385 $this->mRuleDisplay = '';
1386 break;
1387 default:
1388 // ignore unknown flags (but see error case below)
1389 }
1390 }
1391 if ( $this->mRuleDisplay === false ) {
1392 $this->mRuleDisplay = $this->mManualCodeError;
1393 }
1394
1395 $this->generateConvTable();
1396 }
1397
1398 /**
1399 * @public
1400 */
1401 function hasRules() {
1402 // TODO:
1403 }
1404
1405 /**
1406 * Get display text on markup -{...}-
1407 * @public
1408 */
1409 function getDisplay() {
1410 return $this->mRuleDisplay;
1411 }
1412
1413 /**
1414 * Get converted title.
1415 * @public
1416 */
1417 function getTitle() {
1418 return $this->mRuleTitle;
1419 }
1420
1421 /**
1422 * Return how deal with conversion rules.
1423 * @public
1424 */
1425 function getRulesAction() {
1426 return $this->mRulesAction;
1427 }
1428
1429 /**
1430 * Get conversion table. ( bidirectional and unidirectional
1431 * conversion table )
1432 * @public
1433 */
1434 function getConvTable() {
1435 return $this->mConvTable;
1436 }
1437
1438 /**
1439 * Get conversion rules string.
1440 * @public
1441 */
1442 function getRules() {
1443 return $this->mRules;
1444 }
1445
1446 /**
1447 * Get conversion flags.
1448 * @public
1449 */
1450 function getFlags() {
1451 return $this->mFlags;
1452 }
1453 }