Reverted r49855, r49656, r49401, r49399, r49397. The language converter cannot be...
[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 * @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 $marks = array();
535 foreach ( $tarray as $txt ) {
536 $marked = explode( $this->mMarkup['begin'], $txt, 2 );
537 if ( array_key_exists( 1, $marked ) ) {
538 $crule = new ConverterRule($marked[1], $this);
539 $crule->parse( $plang );
540 $marked[1] = $crule->getDisplay();
541 $this->prepareManualConv( $crule );
542 }
543 else
544 $marked[0] .= $this->mMarkup['end'];
545 array_push( $marks, $marked );
546 }
547 $this->applyManualConv();
548 foreach ( $marks as $marked ) {
549 if( $this->mDoContentConvert )
550 $text .= $this->autoConvert( $marked[0], $plang );
551 else
552 $text .= $marked[0];
553 if( array_key_exists( 1, $marked ) )
554 $text .= $marked[1];
555 }
556 // Remove the last delimiter (wasn't real)
557 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
558
559 return $text;
560 }
561
562 /**
563 * if a language supports multiple variants, it is
564 * possible that non-existing link in one variant
565 * actually exists in another variant. this function
566 * tries to find it. See e.g. LanguageZh.php
567 *
568 * @param string $link the name of the link
569 * @param mixed $nt the title object of the link
570 * @param boolean $ignoreOtherCond: to disable other conditions when
571 * we need to transclude a template or update a category's link
572 * @return null the input parameters may be modified upon return
573 * @public
574 */
575 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
576 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
577 $isredir = $wgRequest->getText( 'redirect', 'yes' );
578 $action = $wgRequest->getText( 'action' );
579 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
580 $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
581 $linkBatch = new LinkBatch();
582
583 $ns=NS_MAIN;
584
585 if ( $disableLinkConversion || ( !$ignoreOtherCond && ( $isredir == 'no' || $action == 'edit'
586 || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) )
587 return;
588
589 if(is_object($nt))
590 $ns = $nt->getNamespace();
591
592 $variants = $this->autoConvertToAllVariants($link);
593 if($variants == false) //give up
594 return;
595
596 $titles = array();
597
598 foreach( $variants as $v ) {
599 if($v != $link){
600 $varnt = Title::newFromText( $v, $ns );
601 if(!is_null($varnt)){
602 $linkBatch->addObj($varnt);
603 $titles[]=$varnt;
604 }
605 }
606 }
607
608 // fetch all variants in single query
609 $linkBatch->execute();
610
611 foreach( $titles as $varnt ) {
612 if( $varnt->getArticleID() > 0 ) {
613 $nt = $varnt;
614 $link = $varnt->getText();
615 break;
616 }
617 }
618 }
619
620 /**
621 * returns language specific hash options
622 *
623 * @public
624 */
625 function getExtraHashOptions() {
626 $variant = $this->getPreferredVariant();
627 return '!' . $variant ;
628 }
629
630 /**
631 * get title text as defined in the body of the article text
632 *
633 * @public
634 */
635 function getParsedTitle() {
636 return $this->mTitleDisplay;
637 }
638
639 /**
640 * a write lock to the cache
641 *
642 * @private
643 */
644 function lockCache() {
645 global $wgMemc;
646 $success = false;
647 for($i=0; $i<30; $i++) {
648 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
649 break;
650 sleep(1);
651 }
652 return $success;
653 }
654
655 /**
656 * unlock cache
657 *
658 * @private
659 */
660 function unlockCache() {
661 global $wgMemc;
662 $wgMemc->delete($this->mCacheKey . "lock");
663 }
664
665
666 /**
667 * Load default conversion tables
668 * This method must be implemented in derived class
669 *
670 * @private
671 */
672 function loadDefaultTables() {
673 $name = get_class($this);
674 wfDie("Must implement loadDefaultTables() method in class $name");
675 }
676
677 /**
678 * load conversion tables either from the cache or the disk
679 * @private
680 */
681 function loadTables( $fromcache = true ) {
682 global $wgMemc;
683 if( $this->mTablesLoaded )
684 return;
685 wfProfileIn( __METHOD__ );
686 $this->mTablesLoaded = true;
687 $this->mTables = false;
688 if($fromcache) {
689 wfProfileIn( __METHOD__.'-cache' );
690 $this->mTables = $wgMemc->get( $this->mCacheKey );
691 wfProfileOut( __METHOD__.'-cache' );
692 }
693 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
694 wfProfileIn( __METHOD__.'-recache' );
695 // not in cache, or we need a fresh reload.
696 // we will first load the default tables
697 // then update them using things in MediaWiki:Zhconversiontable/*
698 $this->loadDefaultTables();
699 foreach( $this->mVariants as $var ) {
700 $cached = $this->parseCachedTable( $var );
701 // load group convert table, e.g. [[MediaWiki:Groupconversiontable-StarTrek]].
702 foreach( $this->mGroups as $group ) {
703 $cachedgroup = $this->parseCachedTable( $var, '', true, "Groupconversiontable-$group" );
704 $cached = array_merge( $cached, $cachedgroup );
705 }
706 $this->mTables[$var]->mergeArray( $cached );
707 }
708
709 $this->postLoadTables();
710 $this->mTables[self::CACHE_VERSION_KEY] = true;
711
712 if($this->lockCache()) {
713 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
714 $this->unlockCache();
715 }
716 wfProfileOut( __METHOD__.'-recache' );
717 }
718 wfProfileOut( __METHOD__ );
719 }
720
721 /**
722 * Hook for post processig after conversion tables are loaded
723 *
724 */
725 function postLoadTables() {}
726
727 /**
728 * Reload the conversion tables
729 *
730 * @private
731 */
732 function reloadTables() {
733 if($this->mTables)
734 unset($this->mTables);
735 $this->mTablesLoaded = false;
736 $this->loadTables(false);
737 }
738
739
740 /**
741 * parse the conversion table stored in the cache
742 *
743 * the tables should be in blocks of the following form:
744 * -{
745 * word => word ;
746 * word => word ;
747 * ...
748 * }-
749 *
750 * to make the tables more manageable, subpages are allowed
751 * and will be parsed recursively if $recursive=true
752 *
753 */
754 function parseCachedTable($code, $subpage='', $recursive=true, $table='Conversiontable') {
755 global $wgMessageCache;
756 static $parsed = array();
757
758 if(!is_object($wgMessageCache))
759 return array();
760
761 $key = "$table/".$code;
762 if($subpage)
763 $key .= '/' . $subpage;
764
765 if(array_key_exists($key, $parsed))
766 return array();
767
768 if ( strpos( $code, '/' ) === false ) {
769 $txt = $wgMessageCache->get( $table, true, $code );
770 } else {
771 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "$table/$code" );
772 if ( $title && $title->exists() ) {
773 $article = new Article( $title );
774 $txt = $article->getContents();
775 } else {
776 $txt = '';
777 }
778 }
779 // get all subpage links of the form
780 // [[MediaWiki:conversiontable/zh-xx/...|...]]
781 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ":$table";
782 $subs = explode('[[', $txt);
783 $sublinks = array();
784 foreach( $subs as $sub ) {
785 $link = explode(']]', $sub, 2);
786 if(count($link) != 2)
787 continue;
788 $b = explode('|', $link[0]);
789 $b = explode('/', trim($b[0]), 3);
790 if(count($b)==3)
791 $sublink = $b[2];
792 else
793 $sublink = '';
794
795 if($b[0] == $linkhead && $b[1] == $code) {
796 $sublinks[] = $sublink;
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 * Callback function for magicword 'groupconvert'
896 *
897 * @param string $group: the group name called for
898 * @return blank string
899 */
900 function groupConvert( $group ) {
901 $this->mGroups[] = $group;
902 return '';
903 }
904 }
905
906 /**
907 * parser for rules of language conversion , parse rules in -{ }- tag
908 * @ingroup Language
909 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
910 */
911 class ConverterRule {
912 var $mText; // original text in -{text}-
913 var $mConverter; // LanguageConverter object
914 var $mManualCodeError='<strong class="error">code error!</strong>';
915 var $mRuleDisplay = '',$mRuleTitle=false;
916 var $mRules = '';// string : the text of the rules
917 var $mRulesAction = 'none';
918 var $mFlags = array();
919 var $mConvTable = array();
920 var $mBidtable = array();// array of the translation in each variant
921 var $mUnidtable = array();// array of the translation in each variant
922
923 /**
924 * Constructor
925 *
926 * @param string $text the text between -{ and }-
927 * @param object $converter a LanguageConverter object
928 * @access public
929 */
930 function __construct($text,$converter){
931 $this->mText = $text;
932 $this->mConverter=$converter;
933 foreach($converter->mVariants as $v){
934 $this->mConvTable[$v]=array();
935 }
936 }
937
938 /**
939 * check if variants array in convert array
940 *
941 * @param string $variant Variant language code
942 * @return string Translated text
943 * @public
944 */
945 function getTextInBidtable($variants){
946 if(is_string($variants)){ $variants=array($variants); }
947 if(!is_array($variants)) return false;
948 foreach ($variants as $variant){
949 if(array_key_exists($variant, $this->mBidtable)){
950 return $this->mBidtable[$variant];
951 }
952 }
953 return false;
954 }
955
956 /**
957 * Parse flags with syntax -{FLAG| ... }-
958 * @private
959 */
960 function parseFlags(){
961 $text = $this->mText;
962 if(strlen($text) < 2 ) {
963 $this->mFlags = array( 'R' );
964 $this->mRules = $text;
965 return;
966 }
967
968 $flags = array();
969 $markup = $this->mConverter->mMarkup;
970 $validFlags = $this->mConverter->mFlags;
971 $variants = $this->mConverter->mVariants;
972
973 $tt = explode($markup['flagsep'], $text, 2);
974 if(count($tt) == 2) {
975 $f = explode($markup['varsep'], $tt[0]);
976 foreach($f as $ff) {
977 $ff = trim($ff);
978 if(array_key_exists($ff, $validFlags) &&
979 !in_array($validFlags[$ff], $flags))
980 $flags[] = $validFlags[$ff];
981 }
982 $rules = $tt[1];
983 } else {
984 $rules = $text;
985 }
986
987 //check flags
988 if( in_array('R',$flags) ){
989 $flags = array('R');// remove other flags
990 } elseif ( in_array('N',$flags) ){
991 $flags = array('N');// remove other flags
992 } elseif ( in_array('-',$flags) ){
993 $flags = array('-');// remove other flags
994 } elseif (count($flags)==1 && $flags[0]=='T'){
995 $flags[]='H';
996 } elseif ( in_array('H',$flags) ){
997 // replace A flag, and remove other flags except T
998 $temp=array('+','H');
999 if(in_array('T',$flags)) $temp[] = 'T';
1000 if(in_array('D',$flags)) $temp[] = 'D';
1001 $flags = $temp;
1002 } else {
1003 if ( in_array('A',$flags) ) {
1004 $flags[]='+';
1005 $flags[]='S';
1006 }
1007 if ( in_array('D',$flags) )
1008 $flags=array_diff($flags,array('S'));
1009 $flags_temp = array();
1010 foreach ($variants as $variant) {
1011 // try to find flags like "zh-hans", "zh-hant"
1012 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1013 if ( in_array($variant, $flags) )
1014 $flags_temp[] = $variant;
1015 }
1016 if ( count($flags_temp) !== 0 )
1017 $flags = $flags_temp;
1018 }
1019 if ( count($flags) == 0 )
1020 $flags = array('S');
1021 $this->mRules=$rules;
1022 $this->mFlags=$flags;
1023 }
1024
1025 /**
1026 * generate conversion table
1027 * @private
1028 */
1029 function parseRules() {
1030 $rules = $this->mRules;
1031 $flags = $this->mFlags;
1032 $bidtable = array();
1033 $unidtable = array();
1034 $markup = $this->mConverter->mMarkup;
1035 $variants = $this->mConverter->mVariants;
1036
1037 // varsep_pattern for preg_split:
1038 // text should be splited by ";" only if a valid variant
1039 // name exist after the markup, for example:
1040 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1041 // we should split it as:
1042 // array(
1043 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1044 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1045 // [2] => ''
1046 // )
1047 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1048 foreach( $variants as $variant ) {
1049 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1050 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1051 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1052 }
1053 $varsep_pattern .= '\s*$)/';
1054
1055 $choice = preg_split($varsep_pattern, $rules);
1056
1057 foreach( $choice as $c ) {
1058 $v = explode($markup['codesep'], $c, 2);
1059 if( count($v) != 2 )
1060 continue;// syntax error, skip
1061 $to = trim($v[1]);
1062 $v = trim($v[0]);
1063 $u = explode($markup['unidsep'], $v);
1064 // if $to is empty, strtr() could return a wrong result
1065 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1066 $bidtable[$v] = $to;
1067 } else if(count($u) == 2){
1068 $from = trim($u[0]);
1069 $v = trim($u[1]);
1070 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1071 && $to && in_array( $v, $variants ) )
1072 $unidtable[$v] = array( $from=>$to );
1073 elseif ( $to && in_array( $v, $variants ) )
1074 $unidtable[$v][$from] = $to;
1075 }
1076 // syntax error, pass
1077 if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ){
1078 $bidtable = array();
1079 $unidtable = array();
1080 break;
1081 }
1082 }
1083 $this->mBidtable = $bidtable;
1084 $this->mUnidtable = $unidtable;
1085 }
1086
1087 /**
1088 * @private
1089 */
1090 function getRulesDesc(){
1091 $codesep = $this->mConverter->mDescCodeSep;
1092 $varsep = $this->mConverter->mDescVarSep;
1093 $text='';
1094 foreach($this->mBidtable as $k => $v)
1095 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
1096 foreach($this->mUnidtable as $k => $a)
1097 foreach($a as $from=>$to)
1098 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
1099 return $text;
1100 }
1101
1102 /**
1103 * Parse rules conversion
1104 * @private
1105 */
1106 function getRuleConvertedStr($variant,$doConvert){
1107 $bidtable = $this->mBidtable;
1108 $unidtable = $this->mUnidtable;
1109
1110 if( count($bidtable) + count($unidtable) == 0 ){
1111 return $this->mRules;
1112 } elseif ($doConvert){// the text converted
1113 // display current variant in bidirectional array
1114 $disp = $this->getTextInBidtable($variant);
1115 // or display current variant in fallbacks
1116 if(!$disp)
1117 $disp = $this->getTextInBidtable(
1118 $this->mConverter->getVariantFallbacks($variant));
1119 // or display current variant in unidirectional array
1120 if(!$disp && array_key_exists($variant,$unidtable)){
1121 $disp = array_values($unidtable[$variant]);
1122 $disp = $disp[0];
1123 }
1124 // or display frist text under disable manual convert
1125 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
1126 if(count($bidtable)>0){
1127 $disp = array_values($bidtable);
1128 $disp = $disp[0];
1129 } else {
1130 $disp = array_values($unidtable);
1131 $disp = array_values($disp[0]);
1132 $disp = $disp[0];
1133 }
1134 }
1135 return $disp;
1136 } else {// no convert
1137 return $this->mRules;
1138 }
1139 }
1140
1141 /**
1142 * generate conversion table for all text
1143 * @private
1144 */
1145 function generateConvTable(){
1146 $flags = $this->mFlags;
1147 $bidtable = $this->mBidtable;
1148 $unidtable = $this->mUnidtable;
1149 $manLevel = $this->mConverter->mManualLevel;
1150
1151 $vmarked=array();
1152 foreach($this->mConverter->mVariants as $v) {
1153 /* for bidirectional array
1154 fill in the missing variants, if any,
1155 with fallbacks */
1156 if(!array_key_exists($v, $bidtable)) {
1157 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
1158 $vf = $this->getTextInBidtable($variantFallbacks);
1159 if($vf) $bidtable[$v] = $vf;
1160 }
1161
1162 if(array_key_exists($v,$bidtable)){
1163 foreach($vmarked as $vo){
1164 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1165 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1166 // to introduce a custom mapping between
1167 // words WordZh and WordTw in the whole text
1168 if($manLevel[$v]=='bidirectional'){
1169 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1170 }
1171 if($manLevel[$vo]=='bidirectional'){
1172 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1173 }
1174 }
1175 $vmarked[]=$v;
1176 }
1177 /*for unidirectional array
1178 fill to convert tables */
1179 $allow_unid = $manLevel[$v]=='bidirectional'
1180 || $manLevel[$v]=='unidirectional';
1181 if($allow_unid && array_key_exists($v,$unidtable)){
1182 $ct=$this->mConvTable[$v];
1183 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1184 }
1185 }
1186 }
1187
1188 /**
1189 * Parse rules and flags
1190 * @public
1191 */
1192 function parse($variant){
1193 if(!$variant)
1194 $variant = $this->mConverter->getPreferredVariant();
1195
1196 $variants = $this->mConverter->mVariants;
1197 $this->parseFlags();
1198 $flags = $this->mFlags;
1199
1200 // convert to specified variant
1201 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1202 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1203 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1204 // then convert <text to convert> to current language
1205 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variant );
1206 else { // if current variant no in flags,
1207 // then we check its fallback variants.
1208 $variantFallbacks = $this->mConverter->getVariantFallbacks($variant);
1209 foreach ( $variantFallbacks as $variantFallback ) {
1210 // if current variant's fallback exist in flags
1211 if ( in_array( $variantFallback, $flags ) ) {
1212 // then convert <text to convert> to fallback language
1213 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variantFallback );
1214 break;
1215 }
1216 }
1217 }
1218 $this->mFlags = $flags = array('R');
1219 }
1220
1221 if( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
1222 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1223 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1224
1225 $this->parseRules();
1226 }
1227 $rules = $this->mRules;
1228
1229 if( count( $this->mBidtable ) == 0 && count( $this->mUnidtable ) == 0 ){
1230 if(in_array('+',$flags) || in_array('-',$flags))
1231 // fill all variants if text in -{A/H/-|text} without rules
1232 foreach($this->mConverter->mVariants as $v)
1233 $this->mBidtable[$v] = $rules;
1234 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1235 $this->mFlags = $flags = array('R');
1236 }
1237
1238 if( in_array('R',$flags) ) {
1239 // if we don't do content convert, still strip the -{}- tags
1240 $this->mRuleDisplay = $rules;
1241 } elseif ( in_array('N',$flags) ){
1242 // proces N flag: output current variant name
1243 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1244 } elseif ( in_array('D',$flags) ){
1245 // proces D flag: output rules description
1246 $this->mRuleDisplay = $this->getRulesDesc();
1247 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1248 // proces H,- flag or T only: output nothing
1249 $this->mRuleDisplay = '';
1250 } elseif ( in_array('S',$flags) ){
1251 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1252 $this->mConverter->mDoContentConvert);
1253 } else {
1254 $this->mRuleDisplay= $this->mManualCodeError;
1255 }
1256 // proces T flag
1257 if ( in_array('T',$flags) ) {
1258 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1259 $this->mConverter->mDoTitleConvert);
1260 }
1261
1262 if (in_array('-', $flags))
1263 $this->mRulesAction='remove';
1264 if (in_array('+', $flags))
1265 $this->mRulesAction='add';
1266
1267 $this->generateConvTable();
1268 }
1269
1270 /**
1271 * @public
1272 */
1273 function hasRules(){
1274 // TODO:
1275 }
1276
1277 /**
1278 * get display text on markup -{...}-
1279 * @public
1280 */
1281 function getDisplay(){
1282 return $this->mRuleDisplay;
1283 }
1284 /**
1285 * get converted title
1286 * @public
1287 */
1288 function getTitle(){
1289 return $this->mRuleTitle;
1290 }
1291
1292 /**
1293 * return how deal with conversion rules
1294 * @public
1295 */
1296 function getRulesAction(){
1297 return $this->mRulesAction;
1298 }
1299
1300 /**
1301 * get conversion table ( bidirectional and unidirectional conversion table )
1302 * @public
1303 */
1304 function getConvTable(){
1305 return $this->mConvTable;
1306 }
1307
1308 /**
1309 * get conversion rules string
1310 * @public
1311 */
1312 function getRules(){
1313 return $this->mRules;
1314 }
1315
1316 /**
1317 * get conversion flags
1318 * @public
1319 */
1320 function getFlags(){
1321 return $this->mFlags;
1322 }
1323 }