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