To find an available category name during update table 'categorylinks'. Just act...
[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 $mTitleDisplay='';
27 var $mDoTitleConvert=true, $mDoContentConvert=true;
28 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
29 var $mTitleFromFlag = false;
30 var $mCacheKey;
31 var $mLangObj;
32 var $mMarkup;
33 var $mFlags;
34 var $mDescCodeSep = ':',$mDescVarSep = ';';
35 var $mUcfirst = false;
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 $this->mVariants = $variants;
59 $this->mVariantFallbacks = $variantfallbacks;
60 global $wgLanguageNames;
61 $this->mVariantNames = $wgLanguageNames;
62 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
63 $m = array(
64 'begin'=>'-{',
65 'flagsep'=>'|',
66 'unidsep'=>'=>', //for unidirectional conversion
67 'codesep'=>':',
68 'varsep'=>';',
69 'end'=>'}-'
70 );
71 $this->mMarkup = array_merge($m, $markup);
72 $f = array(
73 // 'S' show converted text
74 // '+' add rules for alltext
75 // 'E' the gave flags is error
76 // these flags above are reserved for program
77 'A'=>'A', // add rule for convert code (all text convert)
78 'T'=>'T', // title convert
79 'R'=>'R', // raw content
80 'D'=>'D', // convert description (subclass implement)
81 '-'=>'-', // remove convert (not implement)
82 'H'=>'H', // add rule for convert code (but no display in placed code )
83 'N'=>'N' // current variant name
84 );
85 $this->mFlags = array_merge($f, $flags);
86 foreach( $this->mVariants as $v) {
87 $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
88 ?$manualLevel[$v]
89 :'bidirectional';
90 $this->mManualAddTables[$v] = array();
91 $this->mManualRemoveTables[$v] = array();
92 }
93 }
94
95 /**
96 * @public
97 */
98 function getVariants() {
99 return $this->mVariants;
100 }
101
102 /**
103 * in case some variant is not defined in the markup, we need
104 * to have some fallback. for example, in zh, normally people
105 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
106 * when zh-sg is preferred but not defined, we will pick zh-hans
107 * in this case. right now this is only used by zh.
108 *
109 * @param string $v the language code of the variant
110 * @return string array the code of the fallback language or false if there is no fallback
111 * @public
112 */
113 function getVariantFallbacks($v) {
114 if( isset( $this->mVariantFallbacks[$v] ) ) {
115 return $this->mVariantFallbacks[$v];
116 }
117 return $this->mMainLanguageCode;
118 }
119
120 /**
121 * get preferred language variants.
122 * @param boolean $fromUser Get it from $wgUser's preferences
123 * @return string the preferred language code
124 * @public
125 */
126 function getPreferredVariant( $fromUser = true ) {
127 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
128
129 if($this->mPreferredVariant)
130 return $this->mPreferredVariant;
131
132 // figure out user lang without constructing wgLang to avoid infinite recursion
133 if( $fromUser )
134 $defaultUserLang = $wgUser->getOption( 'language' );
135 else
136 $defaultUserLang = $this->mMainLanguageCode;
137 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
138 // see if interface language is same as content, if not, prevent conversion
139 if( ! in_array( $userLang, $this->mVariants ) ){
140 $this->mPreferredVariant = $this->mMainLanguageCode; // no conversion
141 return $this->mPreferredVariant;
142 }
143
144 // see if the preference is set in the request
145 $req = $wgRequest->getText( 'variant' );
146 if( in_array( $req, $this->mVariants ) ) {
147 $this->mPreferredVariant = $req;
148 return $req;
149 }
150
151 // check the syntax /code/ArticleTitle
152 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
153 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
154 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
155 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
156 if(in_array($scriptBase,$this->mVariants)){
157 $this->mPreferredVariant = $scriptBase;
158 return $this->mPreferredVariant;
159 }
160 }
161
162 // get language variant preference from logged in users
163 // Don't call this on stub objects because that causes infinite
164 // recursion during initialisation
165 if( $fromUser && $wgUser->isLoggedIn() ) {
166 $this->mPreferredVariant = $wgUser->getOption('variant');
167 return $this->mPreferredVariant;
168 }
169
170 // see if default variant is globaly set
171 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
172 $this->mPreferredVariant = $wgDefaultLanguageVariant;
173 return $this->mPreferredVariant;
174 }
175
176 # FIXME rewrite code for parsing http header. The current code
177 # is written specific for detecting zh- variants
178 if( !$this->mPreferredVariant ) {
179 // see if some supported language variant is set in the
180 // http header, but we don't set the mPreferredVariant
181 // variable in case this is called before the user's
182 // preference is loaded
183 $pv=$this->mMainLanguageCode;
184 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
185 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
186 $zh = strstr($header, $pv.'-');
187 if($zh) {
188 $ary = split("[,;]",$zh);
189 $pv = $ary[0];
190 }
191 }
192 // don't try to return bad variant
193 if(in_array( $pv, $this->mVariants ))
194 return $pv;
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(), "Conversiontable") !== false )
415 {
416 return $text;
417 }
418
419 if($wgDisableLangConversion)
420 return $text;
421
422 $text = $this->convert( $text );
423 $parser->mOutput->setTitleText( $this->mTitleDisplay );
424 return $text;
425 }
426
427 /**
428 * convert title
429 * @private
430 */
431 function convertTitle($text){
432 global $wgDisableTitleConversion, $wgUser;
433
434 // check for global param and __NOTC__ tag
435 if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
436 $this->mTitleDisplay = $text;
437 return $text;
438 }
439
440 // use the title from the T flag if any
441 if($this->mTitleFromFlag){
442 $this->mTitleFromFlag = false;
443 return $this->mTitleDisplay;
444 }
445
446 global $wgRequest;
447 $isredir = $wgRequest->getText( 'redirect', 'yes' );
448 $action = $wgRequest->getText( 'action' );
449 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
450 if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
451 return $text;
452 } else {
453 $this->mTitleDisplay = $this->convert($text);
454 return $this->mTitleDisplay;
455 }
456 }
457
458 /**
459 * convert text to different variants of a language. the automatic
460 * conversion is done in autoConvert(). here we parse the text
461 * marked with -{}-, which specifies special conversions of the
462 * text that can not be accomplished in autoConvert()
463 *
464 * syntax of the markup:
465 * -{code1:text1;code2:text2;...}- or
466 * -{flags|code1:text1;code2:text2;...}- or
467 * -{text}- in which case no conversion should take place for text
468 *
469 * @param string $text text to be converted
470 * @param bool $isTitle whether this conversion is for the article title
471 * @return string converted text
472 * @public
473 */
474 function convert( $text , $isTitle=false) {
475
476 $mw =& MagicWord::get( 'notitleconvert' );
477 if( $mw->matchAndRemove( $text ) )
478 $this->mDoTitleConvert = false;
479 $mw =& MagicWord::get( 'nocontentconvert' );
480 if( $mw->matchAndRemove( $text ) ) {
481 $this->mDoContentConvert = false;
482 }
483
484 // no conversion if redirecting
485 $mw =& MagicWord::get( 'redirect' );
486 if( $mw->matchStart( $text ))
487 return $text;
488
489 // for title convertion
490 if ($isTitle) return $this->convertTitle($text);
491
492 $plang = $this->getPreferredVariant();
493 $tarray = StringUtils::explode($this->mMarkup['end'], $text);
494 $text = '';
495
496 $marks = array();
497 foreach($tarray as $txt) {
498 $marked = explode($this->mMarkup['begin'], $txt, 2);
499 if (array_key_exists(1, $marked)) {
500 $crule = new ConverterRule($marked[1], $this);
501 $crule->parse($plang);
502 $marked[1] = $crule->getDisplay();
503 $this->prepareManualConv($crule);
504 }
505 else
506 $marked[0] .= $this->mMarkup['end'];
507 array_push($marks, $marked);
508 }
509 $this->applyManualConv();
510 foreach ($marks as $marked) {
511 if( $this->mDoContentConvert )
512 $text .= $this->autoConvert($marked[0],$plang);
513 else
514 $text .= $marked[0];
515 if( array_key_exists(1, $marked) )
516 $text .= $marked[1];
517 }
518 // Remove the last delimiter (wasn't real)
519 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
520
521 return $text;
522 }
523
524 /**
525 * if a language supports multiple variants, it is
526 * possible that non-existing link in one variant
527 * actually exists in another variant. this function
528 * tries to find it. See e.g. LanguageZh.php
529 *
530 * @param string $link the name of the link
531 * @param mixed $nt the title object of the link
532 * @param boolean $ignoreSubmitCond: to disable the submit condition if
533 * we need to find a category's variant link when database update.
534 * @return null the input parameters may be modified upon return
535 * @public
536 */
537 function findVariantLink( &$link, &$nt, $forTemplate = false, $ignoreSubmitCond = false ) {
538 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
539 $isredir = $wgRequest->getText( 'redirect', 'yes' );
540 $action = $wgRequest->getText( 'action' );
541 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
542 $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
543 $linkBatch = new LinkBatch();
544
545 $ns=NS_MAIN;
546
547 if ( $disableLinkConversion || ( !$forTemplate && ( $isredir == 'no' || $action == 'edit'
548 || (!$ignoreSubmitCond && $action == 'submit') || $linkconvert == 'no'
549 || $wgUser->getOption('noconvertlink') == 1 ) ) ) { return; }
550
551 if(is_object($nt))
552 $ns = $nt->getNamespace();
553
554 $variants = $this->autoConvertToAllVariants($link);
555 if($variants == false) //give up
556 return;
557
558 $titles = array();
559
560 foreach( $variants as $v ) {
561 if($v != $link){
562 $varnt = Title::newFromText( $v, $ns );
563 if(!is_null($varnt)){
564 $linkBatch->addObj($varnt);
565 $titles[]=$varnt;
566 }
567 }
568 }
569
570 // fetch all variants in single query
571 $linkBatch->execute();
572
573 foreach( $titles as $varnt ) {
574 if( $varnt->getArticleID() > 0 ) {
575 $nt = $varnt;
576 $link = $varnt->getText();
577 break;
578 }
579 }
580 }
581
582 /**
583 * returns language specific hash options
584 *
585 * @public
586 */
587 function getExtraHashOptions() {
588 $variant = $this->getPreferredVariant();
589 return '!' . $variant ;
590 }
591
592 /**
593 * get title text as defined in the body of the article text
594 *
595 * @public
596 */
597 function getParsedTitle() {
598 return $this->mTitleDisplay;
599 }
600
601 /**
602 * a write lock to the cache
603 *
604 * @private
605 */
606 function lockCache() {
607 global $wgMemc;
608 $success = false;
609 for($i=0; $i<30; $i++) {
610 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
611 break;
612 sleep(1);
613 }
614 return $success;
615 }
616
617 /**
618 * unlock cache
619 *
620 * @private
621 */
622 function unlockCache() {
623 global $wgMemc;
624 $wgMemc->delete($this->mCacheKey . "lock");
625 }
626
627
628 /**
629 * Load default conversion tables
630 * This method must be implemented in derived class
631 *
632 * @private
633 */
634 function loadDefaultTables() {
635 $name = get_class($this);
636 wfDie("Must implement loadDefaultTables() method in class $name");
637 }
638
639 /**
640 * load conversion tables either from the cache or the disk
641 * @private
642 */
643 function loadTables($fromcache=true) {
644 global $wgMemc;
645 if( $this->mTablesLoaded )
646 return;
647 wfProfileIn( __METHOD__ );
648 $this->mTablesLoaded = true;
649 $this->mTables = false;
650 if($fromcache) {
651 wfProfileIn( __METHOD__.'-cache' );
652 $this->mTables = $wgMemc->get( $this->mCacheKey );
653 wfProfileOut( __METHOD__.'-cache' );
654 }
655 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
656 wfProfileIn( __METHOD__.'-recache' );
657 // not in cache, or we need a fresh reload.
658 // we will first load the default tables
659 // then update them using things in MediaWiki:Zhconversiontable/*
660 $this->loadDefaultTables();
661 foreach($this->mVariants as $var) {
662 $cached = $this->parseCachedTable($var);
663 $this->mTables[$var]->mergeArray($cached);
664 }
665
666 $this->postLoadTables();
667 $this->mTables[self::CACHE_VERSION_KEY] = true;
668
669 if($this->lockCache()) {
670 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
671 $this->unlockCache();
672 }
673 wfProfileOut( __METHOD__.'-recache' );
674 }
675 wfProfileOut( __METHOD__ );
676 }
677
678 /**
679 * Hook for post processig after conversion tables are loaded
680 *
681 */
682 function postLoadTables() {}
683
684 /**
685 * Reload the conversion tables
686 *
687 * @private
688 */
689 function reloadTables() {
690 if($this->mTables)
691 unset($this->mTables);
692 $this->mTablesLoaded = false;
693 $this->loadTables(false);
694 }
695
696
697 /**
698 * parse the conversion table stored in the cache
699 *
700 * the tables should be in blocks of the following form:
701 * -{
702 * word => word ;
703 * word => word ;
704 * ...
705 * }-
706 *
707 * to make the tables more manageable, subpages are allowed
708 * and will be parsed recursively if $recursive=true
709 *
710 */
711 function parseCachedTable($code, $subpage='', $recursive=true) {
712 global $wgMessageCache;
713 static $parsed = array();
714
715 if(!is_object($wgMessageCache))
716 return array();
717
718 $key = 'Conversiontable/'.$code;
719 if($subpage)
720 $key .= '/' . $subpage;
721
722 if(array_key_exists($key, $parsed))
723 return array();
724
725 if ( strpos( $code, '/' ) === false ) {
726 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
727 } else {
728 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
729 if ( $title && $title->exists() ) {
730 $article = new Article( $title );
731 $txt = $article->getContents();
732 } else {
733 $txt = '';
734 }
735 }
736
737 // get all subpage links of the form
738 // [[MediaWiki:conversiontable/zh-xx/...|...]]
739 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
740 $subs = explode('[[', $txt);
741 $sublinks = array();
742 foreach( $subs as $sub ) {
743 $link = explode(']]', $sub, 2);
744 if(count($link) != 2)
745 continue;
746 $b = explode('|', $link[0]);
747 $b = explode('/', trim($b[0]), 3);
748 if(count($b)==3)
749 $sublink = $b[2];
750 else
751 $sublink = '';
752
753 if($b[0] == $linkhead && $b[1] == $code) {
754 $sublinks[] = $sublink;
755 }
756 }
757
758
759 // parse the mappings in this page
760 $blocks = explode($this->mMarkup['begin'], $txt);
761 array_shift($blocks);
762 $ret = array();
763 foreach($blocks as $block) {
764 $mappings = explode($this->mMarkup['end'], $block, 2);
765 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
766 $table = explode( ';', $stripped );
767 foreach( $table as $t ) {
768 $m = explode( '=>', $t );
769 if( count( $m ) != 2)
770 continue;
771 // trim any trailling comments starting with '//'
772 $tt = explode('//', $m[1], 2);
773 $ret[trim($m[0])] = trim($tt[0]);
774 }
775 }
776 $parsed[$key] = true;
777
778
779 // recursively parse the subpages
780 if($recursive) {
781 foreach($sublinks as $link) {
782 $s = $this->parseCachedTable($code, $link, $recursive);
783 $ret = array_merge($ret, $s);
784 }
785 }
786
787 if ($this->mUcfirst) {
788 foreach ($ret as $k => $v) {
789 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
790 }
791 }
792 return $ret;
793 }
794
795 /**
796 * Enclose a string with the "no conversion" tag. This is used by
797 * various functions in the Parser
798 *
799 * @param string $text text to be tagged for no conversion
800 * @return string the tagged text
801 * @public
802 */
803 function markNoConversion($text, $noParse=false) {
804 # don't mark if already marked
805 if(strpos($text, $this->mMarkup['begin']) ||
806 strpos($text, $this->mMarkup['end']))
807 return $text;
808
809 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
810 return $ret;
811 }
812
813 /**
814 * convert the sorting key for category links. this should make different
815 * keys that are variants of each other map to the same key
816 */
817 function convertCategoryKey( $key ) {
818 return $key;
819 }
820 /**
821 * hook to refresh the cache of conversion tables when
822 * MediaWiki:conversiontable* is updated
823 * @private
824 */
825 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
826 $titleobj = $article->getTitle();
827 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
828 $title = $titleobj->getDBkey();
829 $t = explode('/', $title, 3);
830 $c = count($t);
831 if( $c > 1 && $t[0] == 'Conversiontable' ) {
832 if(in_array($t[1], $this->mVariants)) {
833 $this->reloadTables();
834 }
835 }
836 }
837 return true;
838 }
839
840 /**
841 * Armour rendered math against conversion
842 * Wrap math into rawoutput -{R| math }- syntax
843 * @public
844 */
845 function armourMath($text){
846 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
847 return $ret;
848 }
849 }
850
851 /**
852 * parser for rules of language conversion , parse rules in -{ }- tag
853 * @ingroup Language
854 * @author fdcn <fdcn64@gmail.com>
855 */
856 class ConverterRule {
857 var $mText; // original text in -{text}-
858 var $mConverter; // LanguageConverter object
859 var $mManualCodeError='<strong class="error">code error!</strong>';
860 var $mRuleDisplay = '',$mRuleTitle=false;
861 var $mRules = '';// string : the text of the rules
862 var $mRulesAction = 'none';
863 var $mFlags = array();
864 var $mConvTable = array();
865 var $mBidtable = array();// array of the translation in each variant
866 var $mUnidtable = array();// array of the translation in each variant
867
868 /**
869 * Constructor
870 *
871 * @param string $text the text between -{ and }-
872 * @param object $converter a LanguageConverter object
873 * @access public
874 */
875 function __construct($text,$converter){
876 $this->mText = $text;
877 $this->mConverter=$converter;
878 foreach($converter->mVariants as $v){
879 $this->mConvTable[$v]=array();
880 }
881 }
882
883 /**
884 * check if variants array in convert array
885 *
886 * @param string $variant Variant language code
887 * @return string Translated text
888 * @public
889 */
890 function getTextInBidtable($variants){
891 if(is_string($variants)){ $variants=array($variants); }
892 if(!is_array($variants)) return false;
893 foreach ($variants as $variant){
894 if(array_key_exists($variant, $this->mBidtable)){
895 return $this->mBidtable[$variant];
896 }
897 }
898 return false;
899 }
900
901 /**
902 * Parse flags with syntax -{FLAG| ... }-
903 * @private
904 */
905 function parseFlags(){
906 $text = $this->mText;
907 if(strlen($text) < 2 ) {
908 $this->mFlags = array( 'R' );
909 $this->mRules = $text;
910 return;
911 }
912
913 $flags = array();
914 $markup = $this->mConverter->mMarkup;
915 $validFlags = $this->mConverter->mFlags;
916
917 $tt = explode($markup['flagsep'], $text, 2);
918 if(count($tt) == 2) {
919 $f = explode($markup['varsep'], $tt[0]);
920 foreach($f as $ff) {
921 $ff = trim($ff);
922 if(array_key_exists($ff, $validFlags) &&
923 !in_array($validFlags[$ff], $flags))
924 $flags[] = $validFlags[$ff];
925 }
926 $rules = $tt[1];
927 } else {
928 $rules = $text;
929 }
930
931 //check flags
932 if( in_array('R',$flags) ){
933 $flags = array('R');// remove other flags
934 } elseif ( in_array('N',$flags) ){
935 $flags = array('N');// remove other flags
936 } elseif ( in_array('-',$flags) ){
937 $flags = array('-');// remove other flags
938 } elseif (count($flags)==1 && $flags[0]=='T'){
939 $flags[]='H';
940 } elseif ( in_array('H',$flags) ){
941 // replace A flag, and remove other flags except T
942 $temp=array('+','H');
943 if(in_array('T',$flags)) $temp[] = 'T';
944 if(in_array('D',$flags)) $temp[] = 'D';
945 $flags = $temp;
946 } else {
947 if ( in_array('A',$flags)) {
948 $flags[]='+';
949 $flags[]='S';
950 }
951 if ( in_array('D',$flags) )
952 $flags=array_diff($flags,array('S'));
953 }
954 if ( count($flags)==0 )
955 $flags = array('S');
956 $this->mRules=$rules;
957 $this->mFlags=$flags;
958 }
959
960 /**
961 * generate conversion table
962 * @private
963 */
964 function parseRules() {
965 $rules = $this->mRules;
966 $flags = $this->mFlags;
967 $bidtable = array();
968 $unidtable = array();
969 $markup = $this->mConverter->mMarkup;
970
971 $choice = explode($markup['varsep'], $rules );
972 foreach($choice as $c) {
973 $v = explode($markup['codesep'], $c);
974 if(count($v) != 2)
975 continue;// syntax error, skip
976 $to=trim($v[1]);
977 $v=trim($v[0]);
978 $u = explode($markup['unidsep'], $v);
979 if(count($u) == 1) {
980 $bidtable[$v] = $to;
981 } else if(count($u) == 2){
982 $from=trim($u[0]);$v=trim($u[1]);
983 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
984 $unidtable[$v]=array($from=>$to);
985 else
986 $unidtable[$v][$from]=$to;
987 }
988 // syntax error, pass
989 if (!array_key_exists($v,$this->mConverter->mVariantNames)){
990 $bidtable = array();
991 $unidtable = array();
992 break;
993 }
994 }
995 $this->mBidtable = $bidtable;
996 $this->mUnidtable = $unidtable;
997 }
998
999 /**
1000 * @private
1001 */
1002 function getRulesDesc(){
1003 $codesep = $this->mConverter->mDescCodeSep;
1004 $varsep = $this->mConverter->mDescVarSep;
1005 $text='';
1006 foreach($this->mBidtable as $k => $v)
1007 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
1008 foreach($this->mUnidtable as $k => $a)
1009 foreach($a as $from=>$to)
1010 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
1011 return $text;
1012 }
1013
1014 /**
1015 * Parse rules conversion
1016 * @private
1017 */
1018 function getRuleConvertedStr($variant,$doConvert){
1019 $bidtable = $this->mBidtable;
1020 $unidtable = $this->mUnidtable;
1021
1022 if( count($bidtable) + count($unidtable) == 0 ){
1023 return $this->mRules;
1024 } elseif ($doConvert){// the text converted
1025 // display current variant in bidirectional array
1026 $disp = $this->getTextInBidtable($variant);
1027 // or display current variant in fallbacks
1028 if(!$disp)
1029 $disp = $this->getTextInBidtable(
1030 $this->mConverter->getVariantFallbacks($variant));
1031 // or display current variant in unidirectional array
1032 if(!$disp && array_key_exists($variant,$unidtable)){
1033 $disp = array_values($unidtable[$variant]);
1034 $disp = $disp[0];
1035 }
1036 // or display frist text under disable manual convert
1037 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
1038 if(count($bidtable)>0){
1039 $disp = array_values($bidtable);
1040 $disp = $disp[0];
1041 } else {
1042 $disp = array_values($unidtable);
1043 $disp = array_values($disp[0]);
1044 $disp = $disp[0];
1045 }
1046 }
1047 return $disp;
1048 } else {// no convert
1049 return $this->mRules;
1050 }
1051 }
1052
1053 /**
1054 * generate conversion table for all text
1055 * @private
1056 */
1057 function generateConvTable(){
1058 $flags = $this->mFlags;
1059 $bidtable = $this->mBidtable;
1060 $unidtable = $this->mUnidtable;
1061 $manLevel = $this->mConverter->mManualLevel;
1062
1063 $vmarked=array();
1064 foreach($this->mConverter->mVariants as $v) {
1065 /* for bidirectional array
1066 fill in the missing variants, if any,
1067 with fallbacks */
1068 if(!array_key_exists($v, $bidtable)) {
1069 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
1070 $vf = $this->getTextInBidtable($variantFallbacks);
1071 if($vf) $bidtable[$v] = $vf;
1072 }
1073
1074 if(array_key_exists($v,$bidtable)){
1075 foreach($vmarked as $vo){
1076 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1077 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1078 // to introduce a custom mapping between
1079 // words WordZh and WordTw in the whole text
1080 if($manLevel[$v]=='bidirectional'){
1081 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1082 }
1083 if($manLevel[$vo]=='bidirectional'){
1084 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1085 }
1086 }
1087 $vmarked[]=$v;
1088 }
1089 /*for unidirectional array
1090 fill to convert tables */
1091 $allow_unid = $manLevel[$v]=='bidirectional'
1092 || $manLevel[$v]=='unidirectional';
1093 if($allow_unid && array_key_exists($v,$unidtable)){
1094 $ct=$this->mConvTable[$v];
1095 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1096 }
1097 }
1098 }
1099
1100 /**
1101 * Parse rules and flags
1102 * @public
1103 */
1104 function parse($variant){
1105 if(!$variant) $variant = $this->mConverter->getPreferredVariant();
1106
1107 $this->parseFlags();
1108 $flags = $this->mFlags;
1109
1110 if( !in_array('R',$flags) || !in_array('N',$flags) ){
1111 //FIXME: may cause trouble here...
1112 //strip &nbsp; since it interferes with the parsing, plus,
1113 //all spaces should be stripped in this tag anyway.
1114 $this->mRules = str_replace('&nbsp;', '', $this->mRules);
1115 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1116 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1117
1118 $this->parseRules();
1119 }
1120 $rules = $this->mRules;
1121
1122 if(count($this->mBidtable)==0 && count($this->mUnidtable)==0){
1123 if(in_array('+',$flags) || in_array('-',$flags))
1124 // fill all variants if text in -{A/H/-|text} without rules
1125 foreach($this->mConverter->mVariants as $v)
1126 $this->mBidtable[$v] = $rules;
1127 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1128 $this->mFlags = $flags = array('R');
1129 }
1130
1131 if( in_array('R',$flags) ) {
1132 // if we don't do content convert, still strip the -{}- tags
1133 $this->mRuleDisplay = $rules;
1134 } elseif ( in_array('N',$flags) ){
1135 // proces N flag: output current variant name
1136 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1137 } elseif ( in_array('D',$flags) ){
1138 // proces D flag: output rules description
1139 $this->mRuleDisplay = $this->getRulesDesc();
1140 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1141 // proces H,- flag or T only: output nothing
1142 $this->mRuleDisplay = '';
1143 } elseif ( in_array('S',$flags) ){
1144 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1145 $this->mConverter->mDoContentConvert);
1146 } else {
1147 $this->mRuleDisplay= $this->mManualCodeError;
1148 }
1149 // proces T flag
1150 if ( in_array('T',$flags) ) {
1151 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1152 $this->mConverter->mDoTitleConvert);
1153 }
1154
1155 if (in_array('-', $flags))
1156 $this->mRulesAction='remove';
1157 if (in_array('+', $flags))
1158 $this->mRulesAction='add';
1159
1160 $this->generateConvTable();
1161 }
1162
1163 /**
1164 * @public
1165 */
1166 function hasRules(){
1167 // TODO:
1168 }
1169
1170 /**
1171 * get display text on markup -{...}-
1172 * @public
1173 */
1174 function getDisplay(){
1175 return $this->mRuleDisplay;
1176 }
1177 /**
1178 * get converted title
1179 * @public
1180 */
1181 function getTitle(){
1182 return $this->mRuleTitle;
1183 }
1184
1185 /**
1186 * return how deal with conversion rules
1187 * @public
1188 */
1189 function getRulesAction(){
1190 return $this->mRulesAction;
1191 }
1192
1193 /**
1194 * get conversion table ( bidirectional and unidirectional conversion table )
1195 * @public
1196 */
1197 function getConvTable(){
1198 return $this->mConvTable;
1199 }
1200
1201 /**
1202 * get conversion rules string
1203 * @public
1204 */
1205 function getRules(){
1206 return $this->mRules;
1207 }
1208
1209 /**
1210 * get conversion flags
1211 * @public
1212 */
1213 function getFlags(){
1214 return $this->mFlags;
1215 }
1216 }