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