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