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