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