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