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