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