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