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