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