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