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