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