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