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