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