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