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