1. Follow up on r49157, r50902 and r50938. According RFC 2616 section 14.4, language...
[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 = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
187
188 // explode by comma
189 $result = explode(',', $acceptLanguage);
190
191 $languages = array();
192
193 foreach( $result as $elem ) {
194 // if $elem likes 'zh-cn;q=0.9'
195 if(($posi = strpos( $elem, ';' )) !== false ) {
196 // get the real language code likes 'zh-cn'
197 $languages[] = substr( $elem, 0, $posi );
198 }
199 else {
200 $languages[] = $elem;
201 }
202 }
203
204 foreach( $languages as $language ) {
205 // strip whitespace
206 $language = trim( $language );
207 if( in_array( $language, $this->mVariants ) ) {
208 return $language;
209 break;
210 }
211 }
212 }
213 }
214
215 return $this->mMainLanguageCode;
216
217 }
218
219 /**
220 * caption convert, base on preg_replace_callback
221 *
222 * to convert text in "title" or "alt", like '<img alt="text" ... '
223 * or '<span title="text" ... '
224 *
225 * @return string like ' alt="yyyy"' or ' title="yyyy"'
226 * @private
227 */
228 function captionConvert( $matches ) {
229 $toVariant = $this->getPreferredVariant();
230 $title = $matches[1];
231 $text = $matches[2];
232 // we convert captions except URL
233 if( !strpos( $text, '://' ) )
234 $text = $this->translate($text, $toVariant);
235 return " $title=\"$text\"";
236 }
237
238 /**
239 * dictionary-based conversion
240 *
241 * @param string $text the text to be converted
242 * @param string $toVariant the target language code
243 * @return string the converted text
244 * @private
245 */
246 function autoConvert($text, $toVariant=false) {
247 $fname="LanguageConverter::autoConvert";
248
249 wfProfileIn( $fname );
250
251 if(!$this->mTablesLoaded)
252 $this->loadTables();
253
254 if(!$toVariant)
255 $toVariant = $this->getPreferredVariant();
256 if(!in_array($toVariant, $this->mVariants))
257 return $text;
258
259 /* we convert everything except:
260 1. html markups (anything between < and >)
261 2. html entities
262 3. place holders created by the parser
263 */
264 global $wgParser;
265 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
266 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
267 } else
268 $marker = "";
269
270 // this one is needed when the text is inside an html markup
271 $htmlfix = '|<[^>]+$|^[^<>]*>';
272
273 // disable convert to variants between <code></code> tags
274 $codefix = '<code>.+?<\/code>|';
275 // disable convertsion of <script type="text/javascript"> ... </script>
276 $scriptfix = '<script.*?>.*?<\/script>|';
277 // disable conversion of <pre xxxx> ... </pre>
278 $prefix = '<pre.*?>.*?<\/pre>|';
279
280 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
281
282 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
283
284 $m = array_shift($matches);
285
286 $ret = $this->translate($m[0], $toVariant);
287 $mstart = $m[1]+strlen($m[0]);
288
289 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
290 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
291 foreach($matches as $m) {
292 $mark = substr($text, $mstart, $m[1]-$mstart);
293 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
294 $ret .= $mark;
295 $ret .= $this->translate($m[0], $toVariant);
296 $mstart = $m[1] + strlen($m[0]);
297 }
298 wfProfileOut( $fname );
299 return $ret;
300 }
301
302 /**
303 * Translate a string to a variant
304 * Doesn't process markup or do any of that other stuff, for that use convert()
305 *
306 * @param string $text Text to convert
307 * @param string $variant Variant language code
308 * @return string Translated text
309 * @private
310 */
311 function translate( $text, $variant ) {
312 wfProfileIn( __METHOD__ );
313 if( !$this->mTablesLoaded )
314 $this->loadTables();
315 $text = $this->mTables[$variant]->replace( $text );
316 wfProfileOut( __METHOD__ );
317 return $text;
318 }
319
320 /**
321 * convert text to all supported variants
322 *
323 * @param string $text the text to be converted
324 * @return array of string
325 * @public
326 */
327 function autoConvertToAllVariants($text) {
328 $fname="LanguageConverter::autoConvertToAllVariants";
329 wfProfileIn( $fname );
330 if( !$this->mTablesLoaded )
331 $this->loadTables();
332
333 $ret = array();
334 foreach($this->mVariants as $variant) {
335 $ret[$variant] = $this->translate($text, $variant);
336 }
337
338 wfProfileOut( $fname );
339 return $ret;
340 }
341
342 /**
343 * convert link text to all supported variants
344 *
345 * @param string $text the text to be converted
346 * @return array of string
347 * @public
348 */
349 function convertLinkToAllVariants($text) {
350 if( !$this->mTablesLoaded )
351 $this->loadTables();
352
353 $ret = array();
354 $tarray = explode($this->mMarkup['begin'], $text);
355 $tfirst = array_shift($tarray);
356
357 foreach($this->mVariants as $variant)
358 $ret[$variant] = $this->translate($tfirst,$variant);
359
360 foreach($tarray as $txt) {
361 $marked = explode($this->mMarkup['end'], $txt, 2);
362
363 foreach($this->mVariants as $variant){
364 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
365 if(array_key_exists(1, $marked))
366 $ret[$variant] .= $this->translate($marked[1],$variant);
367 }
368
369 }
370
371 return $ret;
372 }
373
374 /**
375 * prepare manual conversion table
376 * @private
377 */
378 function prepareManualConv( $convRule ){
379 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
380 $title = $convRule->getTitle();
381 if( $title ){
382 $this->mTitleFromFlag = true;
383 $this->mTitleDisplay = $title;
384 }
385
386 //apply manual conversion table to global table
387 $convTable = $convRule->getConvTable();
388 $action = $convRule->getRulesAction();
389 foreach( $convTable as $v => $t ) {
390 if( !in_array( $v, $this->mVariants ) )continue;
391 if( $action=="add" ) {
392 foreach( $t as $from => $to ) {
393 // to ensure that $from and $to not be left blank
394 // so $this->translate() could always return a string
395 if ( $from || $to )
396 // more efficient than array_merge(), about 2.5 times.
397 $this->mManualAddTables[$v][$from] = $to;
398 }
399 }
400 elseif ( $action == "remove" ) {
401 foreach ( $t as $from=>$to ) {
402 if ( $from || $to )
403 $this->mManualRemoveTables[$v][$from] = $to;
404 }
405 }
406 }
407 }
408
409 /**
410 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
411 * @private
412 */
413 function applyManualConv(){
414 //apply manual conversion table to global table
415 foreach($this->mVariants as $v) {
416 if (count($this->mManualAddTables[$v]) > 0) {
417 $this->mTables[$v]->mergeArray($this->mManualAddTables[$v]);
418 }
419 if (count($this->mManualRemoveTables[$v]) > 0)
420 $this->mTables[$v]->removeArray($this->mManualRemoveTables[$v]);
421 }
422 }
423
424 /**
425 * Convert text using a parser object for context
426 * @public
427 */
428 function parserConvert( $text, &$parser ) {
429 global $wgUser, $wgEnableVariants;
430
431 /* disable entire conversion engine if the user had been disabled it */
432 $variantConv = $wgUser->getOption( 'variantconversion' );
433 if ( ( $wgEnableVariants == true ) && ( $variantConv == 0 ) ) {
434 $wgEnableVariants = false;
435 }
436
437 /* don't do anything if this is the conversion table */
438 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
439 strpos($parser->mTitle->getText(), 'onversiontable') !== false )
440 {
441 return $text;
442 }
443
444 if ( !$wgEnableVariants )
445 return $text;
446
447 $text = $this->convert( $text );
448
449 if ( $this->mTitleFromFlag )
450 $parser->mOutput->setTitleText( $this->mTitleDisplay );
451 return $text;
452 }
453
454 /**
455 * convert namespace
456 * @param string $title the title included namespace
457 * @return array of string
458 * @private
459 */
460 function convertNamespace( $title, $variant ) {
461 $splittitle = explode( ':', $title );
462 if (count($splittitle) < 2)
463 return $title;
464 if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) )
465 $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
466 $ret = implode(':', $splittitle );
467 return $ret;
468 }
469
470 /**
471 * convert title
472 * @private
473 */
474 function convertTitle( $text, $variant ){
475 global $wgDisableTitleConversion, $wgUser;
476
477 // check for global param and __NOTC__ tag
478 if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
479 $this->mTitleDisplay = $text;
480 return $text;
481 }
482
483 // use the title from the T flag if any
484 if( $this->mTitleFromFlag ){
485 $this->mTitleFromFlag = false;
486 return $this->mTitleDisplay;
487 }
488
489 global $wgRequest;
490 $isredir = $wgRequest->getText( 'redirect', 'yes' );
491 $action = $wgRequest->getText( 'action' );
492 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
493 if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
494 return $text;
495 } else {
496 $text = $this->convertNamespace( $text, $variant );
497 $this->mTitleDisplay = $this->convert( $text );
498 return $this->mTitleDisplay;
499 }
500 }
501
502 /**
503 * convert text to different variants of a language. the automatic
504 * conversion is done in autoConvert(). here we parse the text
505 * marked with -{}-, which specifies special conversions of the
506 * text that can not be accomplished in autoConvert()
507 *
508 * syntax of the markup:
509 * -{code1:text1;code2:text2;...}- or
510 * -{flags|code1:text1;code2:text2;...}- or
511 * -{text}- in which case no conversion should take place for text
512 *
513 * @param string $text text to be converted
514 * @param bool $isTitle whether this conversion is for the article title
515 * @return string converted text
516 * @public
517 */
518 function convert( $text, $isTitle = false ) {
519
520 $mw =& MagicWord::get( 'notitleconvert' );
521 if( $mw->matchAndRemove( $text ) )
522 $this->mDoTitleConvert = false;
523 $mw =& MagicWord::get( 'nocontentconvert' );
524 if( $mw->matchAndRemove( $text ) ) {
525 $this->mDoContentConvert = false;
526 }
527
528 // no conversion if redirecting
529 $mw =& MagicWord::get( 'redirect' );
530 if( $mw->matchStart( $text ) )
531 return $text;
532
533 $plang = $this->getPreferredVariant();
534
535 // for title convertion
536 if ( $isTitle ) return $this->convertTitle( $text, $plang );
537
538 $tarray = StringUtils::explode( $this->mMarkup['end'], $text );
539 $text = '';
540
541 $marks = array();
542 foreach ( $tarray as $txt ) {
543 $marked = explode( $this->mMarkup['begin'], $txt, 2 );
544 if ( array_key_exists( 1, $marked ) ) {
545 $crule = new ConverterRule($marked[1], $this);
546 $crule->parse( $plang );
547 $marked[1] = $crule->getDisplay();
548 $this->prepareManualConv( $crule );
549 }
550 else
551 $marked[0] .= $this->mMarkup['end'];
552 array_push( $marks, $marked );
553 }
554 $this->applyManualConv();
555 foreach ( $marks as $marked ) {
556 if( $this->mDoContentConvert )
557 $text .= $this->autoConvert( $marked[0], $plang );
558 else
559 $text .= $marked[0];
560 if( array_key_exists( 1, $marked ) )
561 $text .= $marked[1];
562 }
563 // Remove the last delimiter (wasn't real)
564 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
565
566 return $text;
567 }
568
569 /**
570 * if a language supports multiple variants, it is
571 * possible that non-existing link in one variant
572 * actually exists in another variant. this function
573 * tries to find it. See e.g. LanguageZh.php
574 *
575 * @param string $link the name of the link
576 * @param mixed $nt the title object of the link
577 * @param boolean $ignoreOtherCond: to disable other conditions when
578 * we need to transclude a template or update a category's link
579 * @return null the input parameters may be modified upon return
580 * @public
581 */
582 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
583 global $wgEnableVariants, $wgDisableTitleConversion, $wgRequest, $wgUser;
584 $isredir = $wgRequest->getText( 'redirect', 'yes' );
585 $action = $wgRequest->getText( 'action' );
586 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
587 $disableLinkConversion = !$wgEnableVariants || $wgDisableTitleConversion;
588 $linkBatch = new LinkBatch();
589
590 $ns=NS_MAIN;
591
592 if ( $disableLinkConversion || ( !$ignoreOtherCond && ( $isredir == 'no' || $action == 'edit'
593 || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) )
594 return;
595
596 if(is_object($nt))
597 $ns = $nt->getNamespace();
598
599 $variants = $this->autoConvertToAllVariants($link);
600 if($variants == false) //give up
601 return;
602
603 $titles = array();
604
605 foreach( $variants as $v ) {
606 if($v != $link){
607 $varnt = Title::newFromText( $v, $ns );
608 if(!is_null($varnt)){
609 $linkBatch->addObj($varnt);
610 $titles[]=$varnt;
611 }
612 }
613 }
614
615 // fetch all variants in single query
616 $linkBatch->execute();
617
618 foreach( $titles as $varnt ) {
619 if( $varnt->getArticleID() > 0 ) {
620 $nt = $varnt;
621 $link = $varnt->getText();
622 break;
623 }
624 }
625 }
626
627 /**
628 * returns language specific hash options
629 *
630 * @public
631 */
632 function getExtraHashOptions() {
633 $variant = $this->getPreferredVariant();
634 return '!' . $variant ;
635 }
636
637 /**
638 * get title text as defined in the body of the article text
639 *
640 * @public
641 */
642 function getParsedTitle() {
643 return $this->mTitleDisplay;
644 }
645
646 /**
647 * a write lock to the cache
648 *
649 * @private
650 */
651 function lockCache() {
652 global $wgMemc;
653 $success = false;
654 for($i=0; $i<30; $i++) {
655 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
656 break;
657 sleep(1);
658 }
659 return $success;
660 }
661
662 /**
663 * unlock cache
664 *
665 * @private
666 */
667 function unlockCache() {
668 global $wgMemc;
669 $wgMemc->delete($this->mCacheKey . "lock");
670 }
671
672
673 /**
674 * Load default conversion tables
675 * This method must be implemented in derived class
676 *
677 * @private
678 */
679 function loadDefaultTables() {
680 $name = get_class($this);
681 wfDie("Must implement loadDefaultTables() method in class $name");
682 }
683
684 /**
685 * load conversion tables either from the cache or the disk
686 * @private
687 */
688 function loadTables( $fromcache = true ) {
689 global $wgMemc;
690 if( $this->mTablesLoaded )
691 return;
692 wfProfileIn( __METHOD__ );
693 $this->mTablesLoaded = true;
694 $this->mTables = false;
695 if($fromcache) {
696 wfProfileIn( __METHOD__.'-cache' );
697 $this->mTables = $wgMemc->get( $this->mCacheKey );
698 wfProfileOut( __METHOD__.'-cache' );
699 }
700 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
701 wfProfileIn( __METHOD__.'-recache' );
702 // not in cache, or we need a fresh reload.
703 // we will first load the default tables
704 // then update them using things in MediaWiki:Zhconversiontable/*
705 $this->loadDefaultTables();
706 foreach( $this->mVariants as $var ) {
707 $cached = $this->parseCachedTable( $var );
708 // load group convert table, e.g. [[MediaWiki:Groupconversiontable-StarTrek]].
709 foreach( $this->mGroups as $group ) {
710 $cachedgroup = $this->parseCachedTable( $var, '', true, "Groupconversiontable-$group" );
711 $cached = array_merge( $cached, $cachedgroup );
712 }
713 $this->mTables[$var]->mergeArray( $cached );
714 }
715
716 $this->postLoadTables();
717 $this->mTables[self::CACHE_VERSION_KEY] = true;
718
719 if($this->lockCache()) {
720 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
721 $this->unlockCache();
722 }
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, $table='Conversiontable') {
762 global $wgMessageCache;
763 static $parsed = array();
764
765 if(!is_object($wgMessageCache))
766 return array();
767
768 $key = "$table/".$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( $table, true, $code );
777 } else {
778 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "$table/$code" );
779 if ( $title && $title->exists() ) {
780 $article = new Article( $title );
781 $txt = $article->getContents();
782 } else {
783 $txt = '';
784 }
785 }
786 // get all subpage links of the form
787 // [[MediaWiki:conversiontable/zh-xx/...|...]]
788 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ":$table";
789 $subs = explode('[[', $txt);
790 $sublinks = array();
791 foreach( $subs as $sub ) {
792 $link = explode(']]', $sub, 2);
793 if(count($link) != 2)
794 continue;
795 $b = explode('|', $link[0]);
796 $b = explode('/', trim($b[0]), 3);
797 if(count($b)==3)
798 $sublink = $b[2];
799 else
800 $sublink = '';
801
802 if($b[0] == $linkhead && $b[1] == $code) {
803 $sublinks[] = $sublink;
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 * Callback function for magicword 'groupconvert'
903 *
904 * @param string $group: the group name called for
905 * @return blank string
906 */
907 function groupConvert( $group ) {
908 $this->mGroups[] = $group;
909 return '';
910 }
911 }
912
913 /**
914 * parser for rules of language conversion , parse rules in -{ }- tag
915 * @ingroup Language
916 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
917 */
918 class ConverterRule {
919 var $mText; // original text in -{text}-
920 var $mConverter; // LanguageConverter object
921 var $mManualCodeError='<strong class="error">code error!</strong>';
922 var $mRuleDisplay = '',$mRuleTitle=false;
923 var $mRules = '';// string : the text of the rules
924 var $mRulesAction = 'none';
925 var $mFlags = array();
926 var $mConvTable = array();
927 var $mBidtable = array();// array of the translation in each variant
928 var $mUnidtable = array();// array of the translation in each variant
929
930 /**
931 * Constructor
932 *
933 * @param string $text the text between -{ and }-
934 * @param object $converter a LanguageConverter object
935 * @access public
936 */
937 function __construct($text,$converter){
938 $this->mText = $text;
939 $this->mConverter=$converter;
940 foreach($converter->mVariants as $v){
941 $this->mConvTable[$v]=array();
942 }
943 }
944
945 /**
946 * check if variants array in convert array
947 *
948 * @param string $variant Variant language code
949 * @return string Translated text
950 * @public
951 */
952 function getTextInBidtable($variants){
953 if(is_string($variants)){ $variants=array($variants); }
954 if(!is_array($variants)) return false;
955 foreach ($variants as $variant){
956 if(array_key_exists($variant, $this->mBidtable)){
957 return $this->mBidtable[$variant];
958 }
959 }
960 return false;
961 }
962
963 /**
964 * Parse flags with syntax -{FLAG| ... }-
965 * @private
966 */
967 function parseFlags(){
968 $text = $this->mText;
969 if(strlen($text) < 2 ) {
970 $this->mFlags = array( 'R' );
971 $this->mRules = $text;
972 return;
973 }
974
975 $flags = array();
976 $markup = $this->mConverter->mMarkup;
977 $validFlags = $this->mConverter->mFlags;
978 $variants = $this->mConverter->mVariants;
979
980 $tt = explode($markup['flagsep'], $text, 2);
981 if(count($tt) == 2) {
982 $f = explode($markup['varsep'], $tt[0]);
983 foreach($f as $ff) {
984 $ff = trim($ff);
985 if(array_key_exists($ff, $validFlags) &&
986 !in_array($validFlags[$ff], $flags))
987 $flags[] = $validFlags[$ff];
988 }
989 $rules = $tt[1];
990 } else {
991 $rules = $text;
992 }
993
994 //check flags
995 if( in_array('R',$flags) ){
996 $flags = array('R');// remove other flags
997 } elseif ( in_array('N',$flags) ){
998 $flags = array('N');// remove other flags
999 } elseif ( in_array('-',$flags) ){
1000 $flags = array('-');// remove other flags
1001 } elseif (count($flags)==1 && $flags[0]=='T'){
1002 $flags[]='H';
1003 } elseif ( in_array('H',$flags) ){
1004 // replace A flag, and remove other flags except T
1005 $temp=array('+','H');
1006 if(in_array('T',$flags)) $temp[] = 'T';
1007 if(in_array('D',$flags)) $temp[] = 'D';
1008 $flags = $temp;
1009 } else {
1010 if ( in_array('A',$flags) ) {
1011 $flags[]='+';
1012 $flags[]='S';
1013 }
1014 if ( in_array('D',$flags) )
1015 $flags=array_diff($flags,array('S'));
1016 $flags_temp = array();
1017 foreach ($variants as $variant) {
1018 // try to find flags like "zh-hans", "zh-hant"
1019 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1020 if ( in_array($variant, $flags) )
1021 $flags_temp[] = $variant;
1022 }
1023 if ( count($flags_temp) !== 0 )
1024 $flags = $flags_temp;
1025 }
1026 if ( count($flags) == 0 )
1027 $flags = array('S');
1028 $this->mRules=$rules;
1029 $this->mFlags=$flags;
1030 }
1031
1032 /**
1033 * generate conversion table
1034 * @private
1035 */
1036 function parseRules() {
1037 $rules = $this->mRules;
1038 $flags = $this->mFlags;
1039 $bidtable = array();
1040 $unidtable = array();
1041 $markup = $this->mConverter->mMarkup;
1042 $variants = $this->mConverter->mVariants;
1043
1044 // varsep_pattern for preg_split:
1045 // text should be splited by ";" only if a valid variant
1046 // name exist after the markup, for example:
1047 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1048 // we should split it as:
1049 // array(
1050 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1051 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1052 // [2] => ''
1053 // )
1054 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1055 foreach( $variants as $variant ) {
1056 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1057 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1058 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1059 }
1060 $varsep_pattern .= '\s*$)/';
1061
1062 $choice = preg_split($varsep_pattern, $rules);
1063
1064 foreach( $choice as $c ) {
1065 $v = explode($markup['codesep'], $c, 2);
1066 if( count($v) != 2 )
1067 continue;// syntax error, skip
1068 $to = trim($v[1]);
1069 $v = trim($v[0]);
1070 $u = explode($markup['unidsep'], $v);
1071 // if $to is empty, strtr() could return a wrong result
1072 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1073 $bidtable[$v] = $to;
1074 } else if(count($u) == 2){
1075 $from = trim($u[0]);
1076 $v = trim($u[1]);
1077 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1078 && $to && in_array( $v, $variants ) )
1079 $unidtable[$v] = array( $from=>$to );
1080 elseif ( $to && in_array( $v, $variants ) )
1081 $unidtable[$v][$from] = $to;
1082 }
1083 // syntax error, pass
1084 if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ){
1085 $bidtable = array();
1086 $unidtable = array();
1087 break;
1088 }
1089 }
1090 $this->mBidtable = $bidtable;
1091 $this->mUnidtable = $unidtable;
1092 }
1093
1094 /**
1095 * @private
1096 */
1097 function getRulesDesc(){
1098 $codesep = $this->mConverter->mDescCodeSep;
1099 $varsep = $this->mConverter->mDescVarSep;
1100 $text='';
1101 foreach($this->mBidtable as $k => $v)
1102 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
1103 foreach($this->mUnidtable as $k => $a)
1104 foreach($a as $from=>$to)
1105 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
1106 return $text;
1107 }
1108
1109 /**
1110 * Parse rules conversion
1111 * @private
1112 */
1113 function getRuleConvertedStr($variant,$doConvert){
1114 $bidtable = $this->mBidtable;
1115 $unidtable = $this->mUnidtable;
1116
1117 if( count($bidtable) + count($unidtable) == 0 ){
1118 return $this->mRules;
1119 } elseif ($doConvert){// the text converted
1120 // display current variant in bidirectional array
1121 $disp = $this->getTextInBidtable($variant);
1122 // or display current variant in fallbacks
1123 if(!$disp)
1124 $disp = $this->getTextInBidtable(
1125 $this->mConverter->getVariantFallbacks($variant));
1126 // or display current variant in unidirectional array
1127 if(!$disp && array_key_exists($variant,$unidtable)){
1128 $disp = array_values($unidtable[$variant]);
1129 $disp = $disp[0];
1130 }
1131 // or display frist text under disable manual convert
1132 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
1133 if(count($bidtable)>0){
1134 $disp = array_values($bidtable);
1135 $disp = $disp[0];
1136 } else {
1137 $disp = array_values($unidtable);
1138 $disp = array_values($disp[0]);
1139 $disp = $disp[0];
1140 }
1141 }
1142 return $disp;
1143 } else {// no convert
1144 return $this->mRules;
1145 }
1146 }
1147
1148 /**
1149 * generate conversion table for all text
1150 * @private
1151 */
1152 function generateConvTable(){
1153 $flags = $this->mFlags;
1154 $bidtable = $this->mBidtable;
1155 $unidtable = $this->mUnidtable;
1156 $manLevel = $this->mConverter->mManualLevel;
1157
1158 $vmarked=array();
1159 foreach($this->mConverter->mVariants as $v) {
1160 /* for bidirectional array
1161 fill in the missing variants, if any,
1162 with fallbacks */
1163 if(!array_key_exists($v, $bidtable)) {
1164 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
1165 $vf = $this->getTextInBidtable($variantFallbacks);
1166 if($vf) $bidtable[$v] = $vf;
1167 }
1168
1169 if(array_key_exists($v,$bidtable)){
1170 foreach($vmarked as $vo){
1171 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1172 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1173 // to introduce a custom mapping between
1174 // words WordZh and WordTw in the whole text
1175 if($manLevel[$v]=='bidirectional'){
1176 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1177 }
1178 if($manLevel[$vo]=='bidirectional'){
1179 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1180 }
1181 }
1182 $vmarked[]=$v;
1183 }
1184 /*for unidirectional array
1185 fill to convert tables */
1186 $allow_unid = $manLevel[$v]=='bidirectional'
1187 || $manLevel[$v]=='unidirectional';
1188 if($allow_unid && array_key_exists($v,$unidtable)){
1189 $ct=$this->mConvTable[$v];
1190 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1191 }
1192 }
1193 }
1194
1195 /**
1196 * Parse rules and flags
1197 * @public
1198 */
1199 function parse($variant){
1200 if(!$variant)
1201 $variant = $this->mConverter->getPreferredVariant();
1202
1203 $variants = $this->mConverter->mVariants;
1204 $this->parseFlags();
1205 $flags = $this->mFlags;
1206
1207 // convert to specified variant
1208 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1209 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1210 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1211 // then convert <text to convert> to current language
1212 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variant );
1213 else { // if current variant no in flags,
1214 // then we check its fallback variants.
1215 $variantFallbacks = $this->mConverter->getVariantFallbacks($variant);
1216 foreach ( $variantFallbacks as $variantFallback ) {
1217 // if current variant's fallback exist in flags
1218 if ( in_array( $variantFallback, $flags ) ) {
1219 // then convert <text to convert> to fallback language
1220 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variantFallback );
1221 break;
1222 }
1223 }
1224 }
1225 $this->mFlags = $flags = array('R');
1226 }
1227
1228 if( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
1229 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1230 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1231
1232 $this->parseRules();
1233 }
1234 $rules = $this->mRules;
1235
1236 if( count( $this->mBidtable ) == 0 && count( $this->mUnidtable ) == 0 ){
1237 if(in_array('+',$flags) || in_array('-',$flags))
1238 // fill all variants if text in -{A/H/-|text} without rules
1239 foreach($this->mConverter->mVariants as $v)
1240 $this->mBidtable[$v] = $rules;
1241 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1242 $this->mFlags = $flags = array('R');
1243 }
1244
1245 if( in_array('R',$flags) ) {
1246 // if we don't do content convert, still strip the -{}- tags
1247 $this->mRuleDisplay = $rules;
1248 } elseif ( in_array('N',$flags) ){
1249 // proces N flag: output current variant name
1250 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1251 } elseif ( in_array('D',$flags) ){
1252 // proces D flag: output rules description
1253 $this->mRuleDisplay = $this->getRulesDesc();
1254 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1255 // proces H,- flag or T only: output nothing
1256 $this->mRuleDisplay = '';
1257 } elseif ( in_array('S',$flags) ){
1258 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1259 $this->mConverter->mDoContentConvert);
1260 } else {
1261 $this->mRuleDisplay= $this->mManualCodeError;
1262 }
1263 // proces T flag
1264 if ( in_array('T',$flags) ) {
1265 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1266 $this->mConverter->mDoTitleConvert);
1267 }
1268
1269 if (in_array('-', $flags))
1270 $this->mRulesAction='remove';
1271 if (in_array('+', $flags))
1272 $this->mRulesAction='add';
1273
1274 $this->generateConvTable();
1275 }
1276
1277 /**
1278 * @public
1279 */
1280 function hasRules(){
1281 // TODO:
1282 }
1283
1284 /**
1285 * get display text on markup -{...}-
1286 * @public
1287 */
1288 function getDisplay(){
1289 return $this->mRuleDisplay;
1290 }
1291 /**
1292 * get converted title
1293 * @public
1294 */
1295 function getTitle(){
1296 return $this->mRuleTitle;
1297 }
1298
1299 /**
1300 * return how deal with conversion rules
1301 * @public
1302 */
1303 function getRulesAction(){
1304 return $this->mRulesAction;
1305 }
1306
1307 /**
1308 * get conversion table ( bidirectional and unidirectional conversion table )
1309 * @public
1310 */
1311 function getConvTable(){
1312 return $this->mConvTable;
1313 }
1314
1315 /**
1316 * get conversion rules string
1317 * @public
1318 */
1319 function getRules(){
1320 return $this->mRules;
1321 }
1322
1323 /**
1324 * get conversion flags
1325 * @public
1326 */
1327 function getFlags(){
1328 return $this->mFlags;
1329 }
1330 }