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