9a0eac9a8a1dcf4b2595be10349e3dfbdbff1aa1
[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:TitleZh;zh-tw:TitleTw}- for custom
492 // conversion in title
493 $this->mConvRuleTitle = $convRule->getTitle();
494
495 // apply manual conversion table to global table
496 $convTable = $convRule->getConvTable();
497 $action = $convRule->getRulesAction();
498 foreach ( $convTable as $variant => $pair ) {
499 if ( !$this->validateVariant( $variant ) ) {
500 continue;
501 }
502
503 if ( $action == 'add' ) {
504 foreach ( $pair as $from => $to ) {
505 // to ensure that $from and $to not be left blank
506 // so $this->translate() could always return a string
507 if ( $from || $to ) {
508 // more efficient than array_merge(), about 2.5 times.
509 $this->mTables[$variant]->setPair( $from, $to );
510 }
511 }
512 } elseif ( $action == 'remove' ) {
513 $this->mTables[$variant]->removeArray( $pair );
514 }
515 }
516 }
517
518 /**
519 * Convert namespace.
520 * @param $title String: the title included namespace
521 * @return Array of string
522 * @private
523 */
524 function convertNamespace( $title, $variant ) {
525 $splittitle = explode( ':', $title, 2 );
526 if ( count( $splittitle ) < 2 ) {
527 return $title;
528 }
529 if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) ) {
530 $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
531 }
532 $ret = implode( ':', $splittitle );
533 return $ret;
534 }
535
536 /**
537 * Convert text to different variants of a language. The automatic
538 * conversion is done in autoConvert(). Here we parse the text
539 * marked with -{}-, which specifies special conversions of the
540 * text that can not be accomplished in autoConvert().
541 *
542 * Syntax of the markup:
543 * -{code1:text1;code2:text2;...}- or
544 * -{flags|code1:text1;code2:text2;...}- or
545 * -{text}- in which case no conversion should take place for text
546 *
547 * @param $text String: text to be converted
548 * @return String: converted text
549 */
550 public function convert( $text, $istitle = false ) {
551 global $wgDisableLangConversion;
552 if ( $wgDisableLangConversion ) return $text;
553
554 $variant = $this->getPreferredVariant();
555
556 if( $istitle ) {
557 $text = $this->convertNamespace( $text, $variant );
558 }
559
560 return $this->recursiveConvertTopLevel( $text, $variant );
561 }
562
563 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
564 $startPos = 0;
565 $out = '';
566 $length = strlen( $text );
567 while ( $startPos < $length ) {
568 $m = false;
569 $pos = strpos( $text, '-{', $startPos );
570
571 if ( $pos === false ) {
572 // No more markup, append final segment
573 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
574 $startPos = $length;
575 return $out;
576 }
577
578 // Markup found
579 // Append initial segment
580 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
581
582 // Advance position
583 $startPos = $pos;
584
585 // Do recursive conversion
586 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
587 }
588
589 return $out;
590 }
591
592 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
593 // Quick sanity check (no function calls)
594 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
595 throw new MWException( __METHOD__.': invalid input string' );
596 }
597
598 $startPos += 2;
599 $inner = '';
600 $warningDone = false;
601 $length = strlen( $text );
602
603 while ( $startPos < $length ) {
604 $m = false;
605 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
606 if ( !$m ) {
607 // Unclosed rule
608 break;
609 }
610
611 $token = $m[0][0];
612 $pos = $m[0][1];
613
614 // Markup found
615 // Append initial segment
616 $inner .= substr( $text, $startPos, $pos - $startPos );
617
618 // Advance position
619 $startPos = $pos;
620
621 switch ( $token ) {
622 case '-{':
623 // Check max depth
624 if ( $depth >= $this->mMaxDepth ) {
625 $inner .= '-{';
626 if ( !$warningDone ) {
627 $inner .= '<span class="error">' .
628 wfMsgForContent( 'language-converter-depth-warning',
629 $this->mMaxDepth ) .
630 '</span>';
631 $warningDone = true;
632 }
633 $startPos += 2;
634 continue;
635 }
636 // Recursively parse another rule
637 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
638 break;
639 case '}-':
640 // Apply the rule
641 $startPos += 2;
642 $rule = new ConverterRule( $inner, $this );
643 $rule->parse( $variant );
644 $this->applyManualConv( $rule );
645 return $rule->getDisplay();
646 default:
647 throw new MWException( __METHOD__.': invalid regex match' );
648 }
649 }
650
651 // Unclosed rule
652 if ( $startPos < $length ) {
653 $inner .= substr( $text, $startPos );
654 }
655 $startPos = $length;
656 return '-{' . $this->autoConvert( $inner, $variant );
657 }
658
659 /**
660 * If a language supports multiple variants, it is
661 * possible that non-existing link in one variant
662 * actually exists in another variant. This function
663 * tries to find it. See e.g. LanguageZh.php
664 *
665 * @param $link String: the name of the link
666 * @param $nt Mixed: the title object of the link
667 * @param $ignoreOtherCond Boolean: to disable other conditions when
668 * we need to transclude a template or update a category's link
669 * @return Null, the input parameters may be modified upon return
670 */
671 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
672 # If the article has already existed, there is no need to
673 # check it again, otherwise it may cause a fault.
674 if ( is_object( $nt ) && $nt->exists() ) {
675 return;
676 }
677
678 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
679 $wgUser;
680 $isredir = $wgRequest->getText( 'redirect', 'yes' );
681 $action = $wgRequest->getText( 'action' );
682 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
683 $disableLinkConversion = $wgDisableLangConversion
684 || $wgDisableTitleConversion;
685 $linkBatch = new LinkBatch();
686
687 $ns = NS_MAIN;
688
689 if ( $disableLinkConversion ||
690 ( !$ignoreOtherCond &&
691 ( $isredir == 'no'
692 || $action == 'edit'
693 || $action == 'submit'
694 || $linkconvert == 'no'
695 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
696 return;
697 }
698
699 if ( is_object( $nt ) ) {
700 $ns = $nt->getNamespace();
701 }
702
703 $variants = $this->autoConvertToAllVariants( $link );
704 if ( $variants == false ) { // give up
705 return;
706 }
707
708 $titles = array();
709
710 foreach ( $variants as $v ) {
711 if ( $v != $link ) {
712 $varnt = Title::newFromText( $v, $ns );
713 if ( !is_null( $varnt ) ) {
714 $linkBatch->addObj( $varnt );
715 $titles[] = $varnt;
716 }
717 }
718 }
719
720 // fetch all variants in single query
721 $linkBatch->execute();
722
723 foreach ( $titles as $varnt ) {
724 if ( $varnt->getArticleID() > 0 ) {
725 $nt = $varnt;
726 $link = $varnt->getText();
727 break;
728 }
729 }
730 }
731
732 /**
733 * Returns language specific hash options.
734 */
735 public function getExtraHashOptions() {
736 $variant = $this->getPreferredVariant();
737 return '!' . $variant ;
738 }
739
740 /**
741 * Load default conversion tables.
742 * This method must be implemented in derived class.
743 *
744 * @private
745 */
746 function loadDefaultTables() {
747 $name = get_class( $this );
748 wfDie( "Must implement loadDefaultTables() method in class $name" );
749 }
750
751 /**
752 * Load conversion tables either from the cache or the disk.
753 * @private
754 */
755 function loadTables( $fromcache = true ) {
756 global $wgMemc;
757 if ( $this->mTablesLoaded ) {
758 return;
759 }
760 wfProfileIn( __METHOD__ );
761 $this->mTablesLoaded = true;
762 $this->mTables = false;
763 if ( $fromcache ) {
764 wfProfileIn( __METHOD__ . '-cache' );
765 $this->mTables = $wgMemc->get( $this->mCacheKey );
766 wfProfileOut( __METHOD__ . '-cache' );
767 }
768 if ( !$this->mTables
769 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
770 wfProfileIn( __METHOD__ . '-recache' );
771 // not in cache, or we need a fresh reload.
772 // we will first load the default tables
773 // then update them using things in MediaWiki:Zhconversiontable/*
774 $this->loadDefaultTables();
775 foreach ( $this->mVariants as $var ) {
776 $cached = $this->parseCachedTable( $var );
777 $this->mTables[$var]->mergeArray( $cached );
778 }
779
780 $this->postLoadTables();
781 $this->mTables[self::CACHE_VERSION_KEY] = true;
782
783 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
784 wfProfileOut( __METHOD__ . '-recache' );
785 }
786 wfProfileOut( __METHOD__ );
787 }
788
789 /**
790 * Hook for post processig after conversion tables are loaded.
791 *
792 */
793 function postLoadTables() { }
794
795 /**
796 * Reload the conversion tables.
797 *
798 * @private
799 */
800 function reloadTables() {
801 if ( $this->mTables ) {
802 unset( $this->mTables );
803 }
804 $this->mTablesLoaded = false;
805 $this->loadTables( false );
806 }
807
808
809 /**
810 * Parse the conversion table stored in the cache.
811 *
812 * The tables should be in blocks of the following form:
813 * -{
814 * word => word ;
815 * word => word ;
816 * ...
817 * }-
818 *
819 * To make the tables more manageable, subpages are allowed
820 * and will be parsed recursively if $recursive == true.
821 *
822 */
823 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
824 global $wgMessageCache;
825 static $parsed = array();
826
827 if ( !is_object( $wgMessageCache ) ) {
828 return array();
829 }
830
831 $key = 'Conversiontable/' . $code;
832 if ( $subpage ) {
833 $key .= '/' . $subpage;
834 }
835 if ( array_key_exists( $key, $parsed ) ) {
836 return array();
837 }
838
839 if ( strpos( $code, '/' ) === false ) {
840 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
841 if( $txt === false ){
842 # FIXME: this method doesn't seem to be expecting
843 # this possible outcome...
844 $txt = '&lt;Conversiontable&gt;';
845 }
846 } else {
847 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
848 "Conversiontable/$code" );
849 if ( $title && $title->exists() ) {
850 $article = new Article( $title );
851 $txt = $article->getContents();
852 } else {
853 $txt = '';
854 }
855 }
856
857 // get all subpage links of the form
858 // [[MediaWiki:conversiontable/zh-xx/...|...]]
859 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
860 ':Conversiontable';
861 $subs = StringUtils::explode( '[[', $txt );
862 $sublinks = array();
863 foreach ( $subs as $sub ) {
864 $link = explode( ']]', $sub, 2 );
865 if ( count( $link ) != 2 ) {
866 continue;
867 }
868 $b = explode( '|', $link[0], 2 );
869 $b = explode( '/', trim( $b[0] ), 3 );
870 if ( count( $b ) == 3 ) {
871 $sublink = $b[2];
872 } else {
873 $sublink = '';
874 }
875
876 if ( $b[0] == $linkhead && $b[1] == $code ) {
877 $sublinks[] = $sublink;
878 }
879 }
880
881
882 // parse the mappings in this page
883 $blocks = StringUtils::explode( '-{', $txt );
884 $ret = array();
885 $first = true;
886 foreach ( $blocks as $block ) {
887 if ( $first ) {
888 // Skip the part before the first -{
889 $first = false;
890 continue;
891 }
892 $mappings = explode( '}-', $block, 2 );
893 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
894 $mappings[0] );
895 $table = StringUtils::explode( ';', $stripped );
896 foreach ( $table as $t ) {
897 $m = explode( '=>', $t, 3 );
898 if ( count( $m ) != 2 )
899 continue;
900 // trim any trailling comments starting with '//'
901 $tt = explode( '//', $m[1], 2 );
902 $ret[trim( $m[0] )] = trim( $tt[0] );
903 }
904 }
905 $parsed[$key] = true;
906
907
908 // recursively parse the subpages
909 if ( $recursive ) {
910 foreach ( $sublinks as $link ) {
911 $s = $this->parseCachedTable( $code, $link, $recursive );
912 $ret = array_merge( $ret, $s );
913 }
914 }
915
916 if ( $this->mUcfirst ) {
917 foreach ( $ret as $k => $v ) {
918 $ret[Language::ucfirst( $k )] = Language::ucfirst( $v );
919 }
920 }
921 return $ret;
922 }
923
924 /**
925 * Enclose a string with the "no conversion" tag. This is used by
926 * various functions in the Parser.
927 *
928 * @param $text String: text to be tagged for no conversion
929 * @param $noParse Unused (?)
930 * @return String: the tagged text
931 */
932 public function markNoConversion( $text, $noParse = false ) {
933 # don't mark if already marked
934 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
935 return $text;
936 }
937
938 $ret = "-{R|$text}-";
939 return $ret;
940 }
941
942 /**
943 * Convert the sorting key for category links. This should make different
944 * keys that are variants of each other map to the same key.
945 */
946 function convertCategoryKey( $key ) {
947 return $key;
948 }
949
950 /**
951 * Hook to refresh the cache of conversion tables when
952 * MediaWiki:conversiontable* is updated.
953 * @private
954 */
955 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
956 $iswatch, $section, $flags, $revision ) {
957 $titleobj = $article->getTitle();
958 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
959 $title = $titleobj->getDBkey();
960 $t = explode( '/', $title, 3 );
961 $c = count( $t );
962 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
963 if ( $this->validateVariant( $t[1] ) ) {
964 $this->reloadTables();
965 }
966 }
967 }
968 return true;
969 }
970
971 /**
972 * Armour rendered math against conversion.
973 * Wrap math into rawoutput -{R| math }- syntax.
974 */
975 public function armourMath( $text ) {
976 // we need to convert '-{' and '}-' to '-&#123;' and '&#125;-'
977 // to avoid a unwanted '}-' appeared after the math-image.
978 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
979 $ret = "-{R|$text}-";
980 return $ret;
981 }
982
983 /**
984 * Get the cached separator pattern for ConverterRule::parseRules()
985 */
986 function getVarSeparatorPattern() {
987 if ( is_null( $this->mVarSeparatorPattern ) ) {
988 // varsep_pattern for preg_split:
989 // text should be splited by ";" only if a valid variant
990 // name exist after the markup, for example:
991 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
992 // <span style="font-size:120%;">yyy</span>;}-
993 // we should split it as:
994 // array(
995 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
996 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
997 // [2] => ''
998 // )
999 $pat = '/;\s*(?=';
1000 foreach ( $this->mVariants as $variant ) {
1001 // zh-hans:xxx;zh-hant:yyy
1002 $pat .= $variant . '\s*:|';
1003 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1004 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1005 }
1006 $pat .= '\s*$)/';
1007 $this->mVarSeparatorPattern = $pat;
1008 }
1009 return $this->mVarSeparatorPattern;
1010 }
1011 }
1012
1013 /**
1014 * Parser for rules of language conversion , parse rules in -{ }- tag.
1015 * @ingroup Language
1016 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1017 */
1018 class ConverterRule {
1019 var $mText; // original text in -{text}-
1020 var $mConverter; // LanguageConverter object
1021 var $mManualCodeError = '<strong class="error">code error!</strong>';
1022 var $mRuleDisplay = '';
1023 var $mRuleTitle = false;
1024 var $mRules = '';// string : the text of the rules
1025 var $mRulesAction = 'none';
1026 var $mFlags = array();
1027 var $mVariantFlags = array();
1028 var $mConvTable = array();
1029 var $mBidtable = array();// array of the translation in each variant
1030 var $mUnidtable = array();// array of the translation in each variant
1031
1032 /**
1033 * Constructor
1034 *
1035 * @param $text String: the text between -{ and }-
1036 * @param $converter LanguageConverter object
1037 */
1038 public function __construct( $text, $converter ) {
1039 $this->mText = $text;
1040 $this->mConverter = $converter;
1041 }
1042
1043 /**
1044 * Check if variants array in convert array.
1045 *
1046 * @param $variants Array or string: variant language code
1047 * @return String: translated text
1048 */
1049 public function getTextInBidtable( $variants ) {
1050 $variants = (array)$variants;
1051 if ( !$variants ) {
1052 return false;
1053 }
1054 foreach ( $variants as $variant ) {
1055 if ( isset( $this->mBidtable[$variant] ) ) {
1056 return $this->mBidtable[$variant];
1057 }
1058 }
1059 return false;
1060 }
1061
1062 /**
1063 * Parse flags with syntax -{FLAG| ... }-
1064 * @private
1065 */
1066 function parseFlags() {
1067 $text = $this->mText;
1068 $flags = array();
1069 $variantFlags = array();
1070
1071 $sepPos = strpos( $text, '|' );
1072 if ( $sepPos !== false ) {
1073 $validFlags = $this->mConverter->mFlags;
1074 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1075 foreach ( $f as $ff ) {
1076 $ff = trim( $ff );
1077 if ( isset( $validFlags[$ff] ) ) {
1078 $flags[$validFlags[$ff]] = true;
1079 }
1080 }
1081 $text = strval( substr( $text, $sepPos + 1 ) );
1082 }
1083
1084 if ( !$flags ) {
1085 $flags['S'] = true;
1086 } elseif ( isset( $flags['R'] ) ) {
1087 $flags = array( 'R' => true );// remove other flags
1088 } elseif ( isset( $flags['N'] ) ) {
1089 $flags = array( 'N' => true );// remove other flags
1090 } elseif ( isset( $flags['-'] ) ) {
1091 $flags = array( '-' => true );// remove other flags
1092 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1093 $flags['H'] = true;
1094 } elseif ( isset( $flags['H'] ) ) {
1095 // replace A flag, and remove other flags except T
1096 $temp = array( '+' => true, 'H' => true );
1097 if ( isset( $flags['T'] ) ) {
1098 $temp['T'] = true;
1099 }
1100 if ( isset( $flags['D'] ) ) {
1101 $temp['D'] = true;
1102 }
1103 $flags = $temp;
1104 } else {
1105 if ( isset( $flags['A'] ) ) {
1106 $flags['+'] = true;
1107 $flags['S'] = true;
1108 }
1109 if ( isset( $flags['D'] ) ) {
1110 unset( $flags['S'] );
1111 }
1112 // try to find flags like "zh-hans", "zh-hant"
1113 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1114 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1115 if ( $variantFlags ) {
1116 $variantFlags = array_flip( $variantFlags );
1117 $flags = array();
1118 }
1119 }
1120 $this->mVariantFlags = $variantFlags;
1121 $this->mRules = $text;
1122 $this->mFlags = $flags;
1123 }
1124
1125 /**
1126 * Generate conversion table.
1127 * @private
1128 */
1129 function parseRules() {
1130 $rules = $this->mRules;
1131 $flags = $this->mFlags;
1132 $bidtable = array();
1133 $unidtable = array();
1134 $variants = $this->mConverter->mVariants;
1135 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1136
1137 $choice = preg_split( $varsep_pattern, $rules );
1138
1139 foreach ( $choice as $c ) {
1140 $v = explode( ':', $c, 2 );
1141 if ( count( $v ) != 2 ) {
1142 // syntax error, skip
1143 continue;
1144 }
1145 $to = trim( $v[1] );
1146 $v = trim( $v[0] );
1147 $u = explode( '=>', $v, 2 );
1148 // if $to is empty, strtr() could return a wrong result
1149 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1150 $bidtable[$v] = $to;
1151 } elseif ( count( $u ) == 2 ) {
1152 $from = trim( $u[0] );
1153 $v = trim( $u[1] );
1154 if ( array_key_exists( $v, $unidtable )
1155 && !is_array( $unidtable[$v] )
1156 && $to
1157 && in_array( $v, $variants ) ) {
1158 $unidtable[$v] = array( $from => $to );
1159 } elseif ( $to && in_array( $v, $variants ) ) {
1160 $unidtable[$v][$from] = $to;
1161 }
1162 }
1163 // syntax error, pass
1164 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1165 $bidtable = array();
1166 $unidtable = array();
1167 break;
1168 }
1169 }
1170 $this->mBidtable = $bidtable;
1171 $this->mUnidtable = $unidtable;
1172 }
1173
1174 /**
1175 * @private
1176 */
1177 function getRulesDesc() {
1178 $codesep = $this->mConverter->mDescCodeSep;
1179 $varsep = $this->mConverter->mDescVarSep;
1180 $text = '';
1181 foreach ( $this->mBidtable as $k => $v ) {
1182 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1183 }
1184 foreach ( $this->mUnidtable as $k => $a ) {
1185 foreach ( $a as $from => $to ) {
1186 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1187 "$codesep$to$varsep";
1188 }
1189 }
1190 return $text;
1191 }
1192
1193 /**
1194 * Parse rules conversion.
1195 * @private
1196 */
1197 function getRuleConvertedStr( $variant ) {
1198 $bidtable = $this->mBidtable;
1199 $unidtable = $this->mUnidtable;
1200
1201 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1202 return $this->mRules;
1203 } else {
1204 // display current variant in bidirectional array
1205 $disp = $this->getTextInBidtable( $variant );
1206 // or display current variant in fallbacks
1207 if ( !$disp ) {
1208 $disp = $this->getTextInBidtable(
1209 $this->mConverter->getVariantFallbacks( $variant ) );
1210 }
1211 // or display current variant in unidirectional array
1212 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1213 $disp = array_values( $unidtable[$variant] );
1214 $disp = $disp[0];
1215 }
1216 // or display frist text under disable manual convert
1217 if ( !$disp
1218 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1219 if ( count( $bidtable ) > 0 ) {
1220 $disp = array_values( $bidtable );
1221 $disp = $disp[0];
1222 } else {
1223 $disp = array_values( $unidtable );
1224 $disp = array_values( $disp[0] );
1225 $disp = $disp[0];
1226 }
1227 }
1228 return $disp;
1229 }
1230 }
1231
1232 /**
1233 * Generate conversion table for all text.
1234 * @private
1235 */
1236 function generateConvTable() {
1237 // Special case optimisation
1238 if ( !$this->mBidtable && !$this->mUnidtable ) {
1239 $this->mConvTable = array();
1240 return;
1241 }
1242
1243 $bidtable = $this->mBidtable;
1244 $unidtable = $this->mUnidtable;
1245 $manLevel = $this->mConverter->mManualLevel;
1246
1247 $vmarked = array();
1248 foreach ( $this->mConverter->mVariants as $v ) {
1249 /* for bidirectional array
1250 fill in the missing variants, if any,
1251 with fallbacks */
1252 if ( !isset( $bidtable[$v] ) ) {
1253 $variantFallbacks =
1254 $this->mConverter->getVariantFallbacks( $v );
1255 $vf = $this->getTextInBidtable( $variantFallbacks );
1256 if ( $vf ) {
1257 $bidtable[$v] = $vf;
1258 }
1259 }
1260
1261 if ( isset( $bidtable[$v] ) ) {
1262 foreach ( $vmarked as $vo ) {
1263 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1264 // or -{H|zh:WordZh;zh-tw:WordTw}-
1265 // or -{-|zh:WordZh;zh-tw:WordTw}-
1266 // to introduce a custom mapping between
1267 // words WordZh and WordTw in the whole text
1268 if ( $manLevel[$v] == 'bidirectional' ) {
1269 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1270 }
1271 if ( $manLevel[$vo] == 'bidirectional' ) {
1272 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1273 }
1274 }
1275 $vmarked[] = $v;
1276 }
1277 /*for unidirectional array fill to convert tables */
1278 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1279 && isset( $unidtable[$v] ) )
1280 {
1281 if ( isset( $this->mConvTable[$v] ) ) {
1282 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1283 } else {
1284 $this->mConvTable[$v] = $unidtable[$v];
1285 }
1286 }
1287 }
1288 }
1289
1290 /**
1291 * Parse rules and flags.
1292 * @public
1293 */
1294 function parse( $variant = NULL ) {
1295 if ( !$variant ) {
1296 $variant = $this->mConverter->getPreferredVariant();
1297 }
1298
1299 $variants = $this->mConverter->mVariants;
1300 $this->parseFlags();
1301 $flags = $this->mFlags;
1302
1303 // convert to specified variant
1304 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1305 if ( $this->mVariantFlags ) {
1306 // check if current variant in flags
1307 if ( isset( $this->mVariantFlags[$variant] ) ) {
1308 // then convert <text to convert> to current language
1309 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1310 $variant );
1311 } else { // if current variant no in flags,
1312 // then we check its fallback variants.
1313 $variantFallbacks =
1314 $this->mConverter->getVariantFallbacks( $variant );
1315 foreach ( $variantFallbacks as $variantFallback ) {
1316 // if current variant's fallback exist in flags
1317 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1318 // then convert <text to convert> to fallback language
1319 $this->mRules =
1320 $this->mConverter->autoConvert( $this->mRules,
1321 $variantFallback );
1322 break;
1323 }
1324 }
1325 }
1326 $this->mFlags = $flags = array( 'R' => true );
1327 }
1328
1329 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1330 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1331 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1332 $this->parseRules();
1333 }
1334 $rules = $this->mRules;
1335
1336 if ( !$this->mBidtable && !$this->mUnidtable ) {
1337 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1338 // fill all variants if text in -{A/H/-|text} without rules
1339 foreach ( $this->mConverter->mVariants as $v ) {
1340 $this->mBidtable[$v] = $rules;
1341 }
1342 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1343 $this->mFlags = $flags = array( 'R' => true );
1344 }
1345 }
1346
1347 $this->mRuleDisplay = false;
1348 foreach ( $flags as $flag => $unused ) {
1349 switch ( $flag ) {
1350 case 'R':
1351 // if we don't do content convert, still strip the -{}- tags
1352 $this->mRuleDisplay = $rules;
1353 break;
1354 case 'N':
1355 // process N flag: output current variant name
1356 $ruleVar = trim( $rules );
1357 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1358 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1359 } else {
1360 $this->mRuleDisplay = '';
1361 }
1362 break;
1363 case 'D':
1364 // process D flag: output rules description
1365 $this->mRuleDisplay = $this->getRulesDesc();
1366 break;
1367 case 'H':
1368 // process H,- flag or T only: output nothing
1369 $this->mRuleDisplay = '';
1370 break;
1371 case '-':
1372 $this->mRulesAction = 'remove';
1373 $this->mRuleDisplay = '';
1374 break;
1375 case '+':
1376 $this->mRulesAction = 'add';
1377 $this->mRuleDisplay = '';
1378 break;
1379 case 'S':
1380 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1381 break;
1382 case 'T':
1383 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1384 $this->mRuleDisplay = '';
1385 break;
1386 default:
1387 // ignore unknown flags (but see error case below)
1388 }
1389 }
1390 if ( $this->mRuleDisplay === false ) {
1391 $this->mRuleDisplay = $this->mManualCodeError;
1392 }
1393
1394 $this->generateConvTable();
1395 }
1396
1397 /**
1398 * @public
1399 */
1400 function hasRules() {
1401 // TODO:
1402 }
1403
1404 /**
1405 * Get display text on markup -{...}-
1406 * @public
1407 */
1408 function getDisplay() {
1409 return $this->mRuleDisplay;
1410 }
1411
1412 /**
1413 * Get converted title.
1414 * @public
1415 */
1416 function getTitle() {
1417 return $this->mRuleTitle;
1418 }
1419
1420 /**
1421 * Return how deal with conversion rules.
1422 * @public
1423 */
1424 function getRulesAction() {
1425 return $this->mRulesAction;
1426 }
1427
1428 /**
1429 * Get conversion table. ( bidirectional and unidirectional
1430 * conversion table )
1431 * @public
1432 */
1433 function getConvTable() {
1434 return $this->mConvTable;
1435 }
1436
1437 /**
1438 * Get conversion rules string.
1439 * @public
1440 */
1441 function getRules() {
1442 return $this->mRules;
1443 }
1444
1445 /**
1446 * Get conversion flags.
1447 * @public
1448 */
1449 function getFlags() {
1450 return $this->mFlags;
1451 }
1452 }