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