Revert r51128, and its follow-up revisions r51129, r51130, r51390.
[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 $wgDisableLangConversion;
429 /* don't do anything if this is the conversion table */
430 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
431 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
432 {
433 return $text;
434 }
435
436 if ( $wgDisableLangConversion )
437 return $text;
438
439 $text = $this->convert( $text );
440
441 if ( $this->mTitleFromFlag )
442 $parser->mOutput->setTitleText( $this->mTitleDisplay );
443 return $text;
444 }
445
446 /**
447 * convert namespace
448 * @param string $title the title included namespace
449 * @return array of string
450 * @private
451 */
452 function convertNamespace( $title, $variant ) {
453 $splittitle = explode( ':', $title );
454 if (count($splittitle) < 2)
455 return $title;
456 if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) )
457 $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
458 $ret = implode(':', $splittitle );
459 return $ret;
460 }
461
462 /**
463 * convert title
464 * @private
465 */
466 function convertTitle( $text, $variant ){
467 global $wgDisableTitleConversion, $wgUser;
468
469 // check for global param and __NOTC__ tag
470 if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
471 $this->mTitleDisplay = $text;
472 return $text;
473 }
474
475 // use the title from the T flag if any
476 if( $this->mTitleFromFlag ){
477 $this->mTitleFromFlag = false;
478 return $this->mTitleDisplay;
479 }
480
481 global $wgRequest;
482 $isredir = $wgRequest->getText( 'redirect', 'yes' );
483 $action = $wgRequest->getText( 'action' );
484 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
485 if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
486 return $text;
487 } else {
488 $text = $this->convertNamespace( $text, $variant );
489 $this->mTitleDisplay = $this->convert( $text );
490 return $this->mTitleDisplay;
491 }
492 }
493
494 /**
495 * convert text to different variants of a language. the automatic
496 * conversion is done in autoConvert(). here we parse the text
497 * marked with -{}-, which specifies special conversions of the
498 * text that can not be accomplished in autoConvert()
499 *
500 * syntax of the markup:
501 * -{code1:text1;code2:text2;...}- or
502 * -{flags|code1:text1;code2:text2;...}- or
503 * -{text}- in which case no conversion should take place for text
504 *
505 * @param string $text text to be converted
506 * @param bool $isTitle whether this conversion is for the article title
507 * @return string converted text
508 * @public
509 */
510 function convert( $text, $isTitle = false ) {
511
512 $mw =& MagicWord::get( 'notitleconvert' );
513 if( $mw->matchAndRemove( $text ) )
514 $this->mDoTitleConvert = false;
515 $mw =& MagicWord::get( 'nocontentconvert' );
516 if( $mw->matchAndRemove( $text ) ) {
517 $this->mDoContentConvert = false;
518 }
519
520 // no conversion if redirecting
521 $mw =& MagicWord::get( 'redirect' );
522 if( $mw->matchStart( $text ) )
523 return $text;
524
525 $plang = $this->getPreferredVariant();
526
527 // for title convertion
528 if ( $isTitle ) return $this->convertTitle( $text, $plang );
529
530 $tarray = StringUtils::explode( $this->mMarkup['end'], $text );
531 $text = '';
532
533 $marks = array();
534 foreach ( $tarray as $txt ) {
535 $marked = explode( $this->mMarkup['begin'], $txt, 2 );
536 if ( array_key_exists( 1, $marked ) ) {
537 $crule = new ConverterRule($marked[1], $this);
538 $crule->parse( $plang );
539 $marked[1] = $crule->getDisplay();
540 $this->prepareManualConv( $crule );
541 }
542 else
543 $marked[0] .= $this->mMarkup['end'];
544 array_push( $marks, $marked );
545 }
546 $this->applyManualConv();
547 foreach ( $marks as $marked ) {
548 if( $this->mDoContentConvert )
549 $text .= $this->autoConvert( $marked[0], $plang );
550 else
551 $text .= $marked[0];
552 if( array_key_exists( 1, $marked ) )
553 $text .= $marked[1];
554 }
555 // Remove the last delimiter (wasn't real)
556 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
557
558 return $text;
559 }
560
561 /**
562 * if a language supports multiple variants, it is
563 * possible that non-existing link in one variant
564 * actually exists in another variant. this function
565 * tries to find it. See e.g. LanguageZh.php
566 *
567 * @param string $link the name of the link
568 * @param mixed $nt the title object of the link
569 * @param boolean $ignoreOtherCond: to disable other conditions when
570 * we need to transclude a template or update a category's link
571 * @return null the input parameters may be modified upon return
572 * @public
573 */
574 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
575 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
576 $isredir = $wgRequest->getText( 'redirect', 'yes' );
577 $action = $wgRequest->getText( 'action' );
578 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
579 $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
580 $linkBatch = new LinkBatch();
581
582 $ns=NS_MAIN;
583
584 if ( $disableLinkConversion || ( !$ignoreOtherCond && ( $isredir == 'no' || $action == 'edit'
585 || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) )
586 return;
587
588 if(is_object($nt))
589 $ns = $nt->getNamespace();
590
591 $variants = $this->autoConvertToAllVariants($link);
592 if($variants == false) //give up
593 return;
594
595 $titles = array();
596
597 foreach( $variants as $v ) {
598 if($v != $link){
599 $varnt = Title::newFromText( $v, $ns );
600 if(!is_null($varnt)){
601 $linkBatch->addObj($varnt);
602 $titles[]=$varnt;
603 }
604 }
605 }
606
607 // fetch all variants in single query
608 $linkBatch->execute();
609
610 foreach( $titles as $varnt ) {
611 if( $varnt->getArticleID() > 0 ) {
612 $nt = $varnt;
613 $link = $varnt->getText();
614 break;
615 }
616 }
617 }
618
619 /**
620 * returns language specific hash options
621 *
622 * @public
623 */
624 function getExtraHashOptions() {
625 $variant = $this->getPreferredVariant();
626 return '!' . $variant ;
627 }
628
629 /**
630 * get title text as defined in the body of the article text
631 *
632 * @public
633 */
634 function getParsedTitle() {
635 return $this->mTitleDisplay;
636 }
637
638 /**
639 * a write lock to the cache
640 *
641 * @private
642 */
643 function lockCache() {
644 global $wgMemc;
645 $success = false;
646 for($i=0; $i<30; $i++) {
647 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
648 break;
649 sleep(1);
650 }
651 return $success;
652 }
653
654 /**
655 * unlock cache
656 *
657 * @private
658 */
659 function unlockCache() {
660 global $wgMemc;
661 $wgMemc->delete($this->mCacheKey . "lock");
662 }
663
664
665 /**
666 * Load default conversion tables
667 * This method must be implemented in derived class
668 *
669 * @private
670 */
671 function loadDefaultTables() {
672 $name = get_class($this);
673 wfDie("Must implement loadDefaultTables() method in class $name");
674 }
675
676 /**
677 * load conversion tables either from the cache or the disk
678 * @private
679 */
680 function loadTables($fromcache=true) {
681 global $wgMemc;
682 if( $this->mTablesLoaded )
683 return;
684 wfProfileIn( __METHOD__ );
685 $this->mTablesLoaded = true;
686 $this->mTables = false;
687 if($fromcache) {
688 wfProfileIn( __METHOD__.'-cache' );
689 $this->mTables = $wgMemc->get( $this->mCacheKey );
690 wfProfileOut( __METHOD__.'-cache' );
691 }
692 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
693 wfProfileIn( __METHOD__.'-recache' );
694 // not in cache, or we need a fresh reload.
695 // we will first load the default tables
696 // then update them using things in MediaWiki:Zhconversiontable/*
697 $this->loadDefaultTables();
698 foreach($this->mVariants as $var) {
699 $cached = $this->parseCachedTable($var);
700 $this->mTables[$var]->mergeArray($cached);
701 }
702
703 $this->postLoadTables();
704 $this->mTables[self::CACHE_VERSION_KEY] = true;
705
706 if($this->lockCache()) {
707 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
708 $this->unlockCache();
709 }
710 wfProfileOut( __METHOD__.'-recache' );
711 }
712 wfProfileOut( __METHOD__ );
713 }
714
715 /**
716 * Hook for post processig after conversion tables are loaded
717 *
718 */
719 function postLoadTables() {}
720
721 /**
722 * Reload the conversion tables
723 *
724 * @private
725 */
726 function reloadTables() {
727 if($this->mTables)
728 unset($this->mTables);
729 $this->mTablesLoaded = false;
730 $this->loadTables(false);
731 }
732
733
734 /**
735 * parse the conversion table stored in the cache
736 *
737 * the tables should be in blocks of the following form:
738 * -{
739 * word => word ;
740 * word => word ;
741 * ...
742 * }-
743 *
744 * to make the tables more manageable, subpages are allowed
745 * and will be parsed recursively if $recursive=true
746 *
747 */
748 function parseCachedTable($code, $subpage='', $recursive=true) {
749 global $wgMessageCache;
750 static $parsed = array();
751
752 if(!is_object($wgMessageCache))
753 return array();
754
755 $key = 'Conversiontable/'.$code;
756 if($subpage)
757 $key .= '/' . $subpage;
758
759 if(array_key_exists($key, $parsed))
760 return array();
761
762 if ( strpos( $code, '/' ) === false ) {
763 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
764 } else {
765 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
766 if ( $title && $title->exists() ) {
767 $article = new Article( $title );
768 $txt = $article->getContents();
769 } else {
770 $txt = '';
771 }
772 }
773
774 // get all subpage links of the form
775 // [[MediaWiki:conversiontable/zh-xx/...|...]]
776 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
777 $subs = explode('[[', $txt);
778 $sublinks = array();
779 foreach( $subs as $sub ) {
780 $link = explode(']]', $sub, 2);
781 if(count($link) != 2)
782 continue;
783 $b = explode('|', $link[0]);
784 $b = explode('/', trim($b[0]), 3);
785 if(count($b)==3)
786 $sublink = $b[2];
787 else
788 $sublink = '';
789
790 if($b[0] == $linkhead && $b[1] == $code) {
791 $sublinks[] = $sublink;
792 }
793 }
794
795
796 // parse the mappings in this page
797 $blocks = explode($this->mMarkup['begin'], $txt);
798 array_shift($blocks);
799 $ret = array();
800 foreach($blocks as $block) {
801 $mappings = explode($this->mMarkup['end'], $block, 2);
802 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
803 $table = explode( ';', $stripped );
804 foreach( $table as $t ) {
805 $m = explode( '=>', $t );
806 if( count( $m ) != 2)
807 continue;
808 // trim any trailling comments starting with '//'
809 $tt = explode('//', $m[1], 2);
810 $ret[trim($m[0])] = trim($tt[0]);
811 }
812 }
813 $parsed[$key] = true;
814
815
816 // recursively parse the subpages
817 if($recursive) {
818 foreach($sublinks as $link) {
819 $s = $this->parseCachedTable($code, $link, $recursive);
820 $ret = array_merge($ret, $s);
821 }
822 }
823
824 if ($this->mUcfirst) {
825 foreach ($ret as $k => $v) {
826 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
827 }
828 }
829 return $ret;
830 }
831
832 /**
833 * Enclose a string with the "no conversion" tag. This is used by
834 * various functions in the Parser
835 *
836 * @param string $text text to be tagged for no conversion
837 * @return string the tagged text
838 * @public
839 */
840 function markNoConversion($text, $noParse=false) {
841 # don't mark if already marked
842 if(strpos($text, $this->mMarkup['begin']) ||
843 strpos($text, $this->mMarkup['end']))
844 return $text;
845
846 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
847 return $ret;
848 }
849
850 /**
851 * convert the sorting key for category links. this should make different
852 * keys that are variants of each other map to the same key
853 */
854 function convertCategoryKey( $key ) {
855 return $key;
856 }
857 /**
858 * hook to refresh the cache of conversion tables when
859 * MediaWiki:conversiontable* is updated
860 * @private
861 */
862 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
863 $titleobj = $article->getTitle();
864 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
865 $title = $titleobj->getDBkey();
866 $t = explode('/', $title, 3);
867 $c = count($t);
868 if( $c > 1 && $t[0] == 'Conversiontable' ) {
869 if(in_array($t[1], $this->mVariants)) {
870 $this->reloadTables();
871 }
872 }
873 }
874 return true;
875 }
876
877 /**
878 * Armour rendered math against conversion
879 * Wrap math into rawoutput -{R| math }- syntax
880 * @public
881 */
882 function armourMath($text){
883 // we need to convert '-{' and '}-' to '-&#123;' and '&#125;-'
884 // to avoid a unwanted '}-' appeared after the math-image.
885 $text = strtr( $text, array('-{' => '-&#123;', '}-' => '&#125;-') );
886 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
887 return $ret;
888 }
889 }
890
891 /**
892 * parser for rules of language conversion , parse rules in -{ }- tag
893 * @ingroup Language
894 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
895 */
896 class ConverterRule {
897 var $mText; // original text in -{text}-
898 var $mConverter; // LanguageConverter object
899 var $mManualCodeError='<strong class="error">code error!</strong>';
900 var $mRuleDisplay = '',$mRuleTitle=false;
901 var $mRules = '';// string : the text of the rules
902 var $mRulesAction = 'none';
903 var $mFlags = array();
904 var $mConvTable = array();
905 var $mBidtable = array();// array of the translation in each variant
906 var $mUnidtable = array();// array of the translation in each variant
907
908 /**
909 * Constructor
910 *
911 * @param string $text the text between -{ and }-
912 * @param object $converter a LanguageConverter object
913 * @access public
914 */
915 function __construct($text,$converter){
916 $this->mText = $text;
917 $this->mConverter=$converter;
918 foreach($converter->mVariants as $v){
919 $this->mConvTable[$v]=array();
920 }
921 }
922
923 /**
924 * check if variants array in convert array
925 *
926 * @param string $variant Variant language code
927 * @return string Translated text
928 * @public
929 */
930 function getTextInBidtable($variants){
931 if(is_string($variants)){ $variants=array($variants); }
932 if(!is_array($variants)) return false;
933 foreach ($variants as $variant){
934 if(array_key_exists($variant, $this->mBidtable)){
935 return $this->mBidtable[$variant];
936 }
937 }
938 return false;
939 }
940
941 /**
942 * Parse flags with syntax -{FLAG| ... }-
943 * @private
944 */
945 function parseFlags(){
946 $text = $this->mText;
947 if(strlen($text) < 2 ) {
948 $this->mFlags = array( 'R' );
949 $this->mRules = $text;
950 return;
951 }
952
953 $flags = array();
954 $markup = $this->mConverter->mMarkup;
955 $validFlags = $this->mConverter->mFlags;
956 $variants = $this->mConverter->mVariants;
957
958 $tt = explode($markup['flagsep'], $text, 2);
959 if(count($tt) == 2) {
960 $f = explode($markup['varsep'], $tt[0]);
961 foreach($f as $ff) {
962 $ff = trim($ff);
963 if(array_key_exists($ff, $validFlags) &&
964 !in_array($validFlags[$ff], $flags))
965 $flags[] = $validFlags[$ff];
966 }
967 $rules = $tt[1];
968 } else {
969 $rules = $text;
970 }
971
972 //check flags
973 if( in_array('R',$flags) ){
974 $flags = array('R');// remove other flags
975 } elseif ( in_array('N',$flags) ){
976 $flags = array('N');// remove other flags
977 } elseif ( in_array('-',$flags) ){
978 $flags = array('-');// remove other flags
979 } elseif (count($flags)==1 && $flags[0]=='T'){
980 $flags[]='H';
981 } elseif ( in_array('H',$flags) ){
982 // replace A flag, and remove other flags except T
983 $temp=array('+','H');
984 if(in_array('T',$flags)) $temp[] = 'T';
985 if(in_array('D',$flags)) $temp[] = 'D';
986 $flags = $temp;
987 } else {
988 if ( in_array('A',$flags) ) {
989 $flags[]='+';
990 $flags[]='S';
991 }
992 if ( in_array('D',$flags) )
993 $flags=array_diff($flags,array('S'));
994 $flags_temp = array();
995 foreach ($variants as $variant) {
996 // try to find flags like "zh-hans", "zh-hant"
997 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
998 if ( in_array($variant, $flags) )
999 $flags_temp[] = $variant;
1000 }
1001 if ( count($flags_temp) !== 0 )
1002 $flags = $flags_temp;
1003 }
1004 if ( count($flags) == 0 )
1005 $flags = array('S');
1006 $this->mRules=$rules;
1007 $this->mFlags=$flags;
1008 }
1009
1010 /**
1011 * generate conversion table
1012 * @private
1013 */
1014 function parseRules() {
1015 $rules = $this->mRules;
1016 $flags = $this->mFlags;
1017 $bidtable = array();
1018 $unidtable = array();
1019 $markup = $this->mConverter->mMarkup;
1020 $variants = $this->mConverter->mVariants;
1021
1022 // varsep_pattern for preg_split:
1023 // text should be splited by ";" only if a valid variant
1024 // name exist after the markup, for example:
1025 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1026 // we should split it as:
1027 // array(
1028 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1029 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1030 // [2] => ''
1031 // )
1032 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1033 foreach( $variants as $variant ) {
1034 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1035 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1036 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1037 }
1038 $varsep_pattern .= '\s*$)/';
1039
1040 $choice = preg_split($varsep_pattern, $rules);
1041
1042 foreach( $choice as $c ) {
1043 $v = explode($markup['codesep'], $c, 2);
1044 if( count($v) != 2 )
1045 continue;// syntax error, skip
1046 $to = trim($v[1]);
1047 $v = trim($v[0]);
1048 $u = explode($markup['unidsep'], $v);
1049 // if $to is empty, strtr() could return a wrong result
1050 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1051 $bidtable[$v] = $to;
1052 } else if(count($u) == 2){
1053 $from = trim($u[0]);
1054 $v = trim($u[1]);
1055 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1056 && $to && in_array( $v, $variants ) )
1057 $unidtable[$v] = array( $from=>$to );
1058 elseif ( $to && in_array( $v, $variants ) )
1059 $unidtable[$v][$from] = $to;
1060 }
1061 // syntax error, pass
1062 if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ){
1063 $bidtable = array();
1064 $unidtable = array();
1065 break;
1066 }
1067 }
1068 $this->mBidtable = $bidtable;
1069 $this->mUnidtable = $unidtable;
1070 }
1071
1072 /**
1073 * @private
1074 */
1075 function getRulesDesc(){
1076 $codesep = $this->mConverter->mDescCodeSep;
1077 $varsep = $this->mConverter->mDescVarSep;
1078 $text='';
1079 foreach($this->mBidtable as $k => $v)
1080 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
1081 foreach($this->mUnidtable as $k => $a)
1082 foreach($a as $from=>$to)
1083 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
1084 return $text;
1085 }
1086
1087 /**
1088 * Parse rules conversion
1089 * @private
1090 */
1091 function getRuleConvertedStr($variant,$doConvert){
1092 $bidtable = $this->mBidtable;
1093 $unidtable = $this->mUnidtable;
1094
1095 if( count($bidtable) + count($unidtable) == 0 ){
1096 return $this->mRules;
1097 } elseif ($doConvert){// the text converted
1098 // display current variant in bidirectional array
1099 $disp = $this->getTextInBidtable($variant);
1100 // or display current variant in fallbacks
1101 if(!$disp)
1102 $disp = $this->getTextInBidtable(
1103 $this->mConverter->getVariantFallbacks($variant));
1104 // or display current variant in unidirectional array
1105 if(!$disp && array_key_exists($variant,$unidtable)){
1106 $disp = array_values($unidtable[$variant]);
1107 $disp = $disp[0];
1108 }
1109 // or display frist text under disable manual convert
1110 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
1111 if(count($bidtable)>0){
1112 $disp = array_values($bidtable);
1113 $disp = $disp[0];
1114 } else {
1115 $disp = array_values($unidtable);
1116 $disp = array_values($disp[0]);
1117 $disp = $disp[0];
1118 }
1119 }
1120 return $disp;
1121 } else {// no convert
1122 return $this->mRules;
1123 }
1124 }
1125
1126 /**
1127 * generate conversion table for all text
1128 * @private
1129 */
1130 function generateConvTable(){
1131 $flags = $this->mFlags;
1132 $bidtable = $this->mBidtable;
1133 $unidtable = $this->mUnidtable;
1134 $manLevel = $this->mConverter->mManualLevel;
1135
1136 $vmarked=array();
1137 foreach($this->mConverter->mVariants as $v) {
1138 /* for bidirectional array
1139 fill in the missing variants, if any,
1140 with fallbacks */
1141 if(!array_key_exists($v, $bidtable)) {
1142 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
1143 $vf = $this->getTextInBidtable($variantFallbacks);
1144 if($vf) $bidtable[$v] = $vf;
1145 }
1146
1147 if(array_key_exists($v,$bidtable)){
1148 foreach($vmarked as $vo){
1149 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1150 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1151 // to introduce a custom mapping between
1152 // words WordZh and WordTw in the whole text
1153 if($manLevel[$v]=='bidirectional'){
1154 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1155 }
1156 if($manLevel[$vo]=='bidirectional'){
1157 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1158 }
1159 }
1160 $vmarked[]=$v;
1161 }
1162 /*for unidirectional array
1163 fill to convert tables */
1164 $allow_unid = $manLevel[$v]=='bidirectional'
1165 || $manLevel[$v]=='unidirectional';
1166 if($allow_unid && array_key_exists($v,$unidtable)){
1167 $ct=$this->mConvTable[$v];
1168 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1169 }
1170 }
1171 }
1172
1173 /**
1174 * Parse rules and flags
1175 * @public
1176 */
1177 function parse($variant){
1178 if(!$variant)
1179 $variant = $this->mConverter->getPreferredVariant();
1180
1181 $variants = $this->mConverter->mVariants;
1182 $this->parseFlags();
1183 $flags = $this->mFlags;
1184
1185 // convert to specified variant
1186 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1187 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1188 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1189 // then convert <text to convert> to current language
1190 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variant );
1191 else { // if current variant no in flags,
1192 // then we check its fallback variants.
1193 $variantFallbacks = $this->mConverter->getVariantFallbacks($variant);
1194 foreach ( $variantFallbacks as $variantFallback ) {
1195 // if current variant's fallback exist in flags
1196 if ( in_array( $variantFallback, $flags ) ) {
1197 // then convert <text to convert> to fallback language
1198 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variantFallback );
1199 break;
1200 }
1201 }
1202 }
1203 $this->mFlags = $flags = array('R');
1204 }
1205
1206 if( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
1207 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1208 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1209
1210 $this->parseRules();
1211 }
1212 $rules = $this->mRules;
1213
1214 if( count( $this->mBidtable ) == 0 && count( $this->mUnidtable ) == 0 ){
1215 if(in_array('+',$flags) || in_array('-',$flags))
1216 // fill all variants if text in -{A/H/-|text} without rules
1217 foreach($this->mConverter->mVariants as $v)
1218 $this->mBidtable[$v] = $rules;
1219 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1220 $this->mFlags = $flags = array('R');
1221 }
1222
1223 if( in_array('R',$flags) ) {
1224 // if we don't do content convert, still strip the -{}- tags
1225 $this->mRuleDisplay = $rules;
1226 } elseif ( in_array('N',$flags) ){
1227 // proces N flag: output current variant name
1228 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1229 } elseif ( in_array('D',$flags) ){
1230 // proces D flag: output rules description
1231 $this->mRuleDisplay = $this->getRulesDesc();
1232 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1233 // proces H,- flag or T only: output nothing
1234 $this->mRuleDisplay = '';
1235 } elseif ( in_array('S',$flags) ){
1236 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1237 $this->mConverter->mDoContentConvert);
1238 } else {
1239 $this->mRuleDisplay= $this->mManualCodeError;
1240 }
1241 // proces T flag
1242 if ( in_array('T',$flags) ) {
1243 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1244 $this->mConverter->mDoTitleConvert);
1245 }
1246
1247 if (in_array('-', $flags))
1248 $this->mRulesAction='remove';
1249 if (in_array('+', $flags))
1250 $this->mRulesAction='add';
1251
1252 $this->generateConvTable();
1253 }
1254
1255 /**
1256 * @public
1257 */
1258 function hasRules(){
1259 // TODO:
1260 }
1261
1262 /**
1263 * get display text on markup -{...}-
1264 * @public
1265 */
1266 function getDisplay(){
1267 return $this->mRuleDisplay;
1268 }
1269 /**
1270 * get converted title
1271 * @public
1272 */
1273 function getTitle(){
1274 return $this->mRuleTitle;
1275 }
1276
1277 /**
1278 * return how deal with conversion rules
1279 * @public
1280 */
1281 function getRulesAction(){
1282 return $this->mRulesAction;
1283 }
1284
1285 /**
1286 * get conversion table ( bidirectional and unidirectional conversion table )
1287 * @public
1288 */
1289 function getConvTable(){
1290 return $this->mConvTable;
1291 }
1292
1293 /**
1294 * get conversion rules string
1295 * @public
1296 */
1297 function getRules(){
1298 return $this->mRules;
1299 }
1300
1301 /**
1302 * get conversion flags
1303 * @public
1304 */
1305 function getFlags(){
1306 return $this->mFlags;
1307 }
1308 }