Localisation updates: Adding/updating Persian translations
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2
3 /**
4 * @ingroup Language
5 *
6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>
9 */
10
11 class LanguageConverter {
12 var $mPreferredVariant='';
13 var $mMainLanguageCode;
14 var $mVariants, $mVariantFallbacks, $mVariantNames;
15 var $mTablesLoaded = false;
16 var $mTables;
17 var $mTitleDisplay='';
18 var $mDoTitleConvert=true, $mDoContentConvert=true;
19 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
20 var $mManualCodeError='<span style="color: red;">code error!</span>';
21 var $mTitleFromFlag = false;
22 var $mCacheKey;
23 var $mLangObj;
24 var $mMarkup;
25 var $mFlags;
26 var $mUcfirst = false;
27
28 const CACHE_VERSION_KEY = 'VERSION 6';
29
30 /**
31 * Constructor
32 *
33 * @param string $maincode the main language code of this language
34 * @param array $variants the supported variants of this language
35 * @param array $variantfallback the fallback language of each variant
36 * @param array $markup array defining the markup used for manual conversion
37 * @param array $flags array defining the custom strings that maps to the flags
38 * @access public
39 */
40 function __construct($langobj, $maincode,
41 $variants=array(),
42 $variantfallbacks=array(),
43 $markup=array(),
44 $flags = array(),
45 $manualLevel = array() ) {
46 $this->mLangObj = $langobj;
47 $this->mMainLanguageCode = $maincode;
48 $this->mVariants = $variants;
49 $this->mVariantFallbacks = $variantfallbacks;
50 global $wgLanguageNames;
51 $this->mVariantNames = $wgLanguageNames;
52 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
53 $m = array(
54 'begin'=>'-{',
55 'flagsep'=>'|',
56 'unidsep'=>'=>', //for unidirectional conversion
57 'codesep'=>':',
58 'varsep'=>';',
59 'end'=>'}-'
60 );
61 $this->mMarkup = array_merge($m, $markup);
62 $f = array(
63 // 'S' show converted text
64 // '+' add rules for alltext
65 // 'E' the gave flags is error
66 // these flags above are reserved for program
67 'A'=>'A', // add rule for convert code (all text convert)
68 'T'=>'T', // title convert
69 'R'=>'R', // raw content
70 'D'=>'D', // convert description (subclass implement)
71 '-'=>'-', // remove convert (not implement)
72 'H'=>'H', // add rule for convert code (but no display in placed code )
73 'N'=>'N' // current variant name
74 );
75 $this->mFlags = array_merge($f, $flags);
76 foreach( $this->mVariants as $v)
77 $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
78 ?$manualLevel[$v]
79 :'bidirectional';
80 }
81
82 /**
83 * @access public
84 */
85 function getVariants() {
86 return $this->mVariants;
87 }
88
89 /**
90 * in case some variant is not defined in the markup, we need
91 * to have some fallback. for example, in zh, normally people
92 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
93 * when zh-sg is preferred but not defined, we will pick zh-hans
94 * in this case. right now this is only used by zh.
95 *
96 * @param string $v the language code of the variant
97 * @return string array the code of the fallback language or false if there is no fallback
98 * @private
99 */
100 function getVariantFallbacks($v) {
101 if( isset( $this->mVariantFallbacks[$v] ) ) {
102 return $this->mVariantFallbacks[$v];
103 }
104 return $this->mMainLanguageCode;
105 }
106
107 /**
108 * check if variants array in convert array
109 *
110 * @param string $variant Variant language code
111 * @param array $carray convert array
112 * @param string $text Text to convert
113 * @return string Translated text
114 * @private
115 */
116 function getTextInCArray($variants,$carray){
117 if(is_string($variants)){ $variants=array($variants); }
118 if(!is_array($variants)) return false;
119 foreach ($variants as $variant){
120 if(array_key_exists($variant, $carray)){
121 return $carray[$variant];
122 }
123 }
124 return false;
125 }
126
127 /**
128 * get preferred language variants.
129 * @param boolean $fromUser Get it from $wgUser's preferences
130 * @return string the preferred language code
131 * @access public
132 */
133 function getPreferredVariant( $fromUser = true ) {
134 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
135
136 if($this->mPreferredVariant)
137 return $this->mPreferredVariant;
138
139 // see if the preference is set in the request
140 $req = $wgRequest->getText( 'variant' );
141 if( in_array( $req, $this->mVariants ) ) {
142 $this->mPreferredVariant = $req;
143 return $req;
144 }
145
146 // check the syntax /code/ArticleTitle
147 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
148 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
149 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
150 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
151 if(in_array($scriptBase,$this->mVariants)){
152 $this->mPreferredVariant = $scriptBase;
153 return $this->mPreferredVariant;
154 }
155 }
156
157 // get language variant preference from logged in users
158 // Don't call this on stub objects because that causes infinite
159 // recursion during initialisation
160 if( $fromUser && $wgUser->isLoggedIn() ) {
161 $this->mPreferredVariant = $wgUser->getOption('variant');
162 return $this->mPreferredVariant;
163 }
164
165 // see if default variant is globaly set
166 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
167 $this->mPreferredVariant = $wgDefaultLanguageVariant;
168 return $this->mPreferredVariant;
169 }
170
171 # FIXME rewrite code for parsing http header. The current code
172 # is written specific for detecting zh- variants
173 if( !$this->mPreferredVariant ) {
174 // see if some supported language variant is set in the
175 // http header, but we don't set the mPreferredVariant
176 // variable in case this is called before the user's
177 // preference is loaded
178 $pv=$this->mMainLanguageCode;
179 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
180 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
181 $zh = strstr($header, $pv.'-');
182 if($zh) {
183 $pv = substr($zh,0,5);
184 }
185 }
186 // don't try to return bad variant
187 if(in_array( $pv, $this->mVariants ))
188 return $pv;
189 }
190
191 return $this->mMainLanguageCode;
192
193 }
194
195 /**
196 * dictionary-based conversion
197 *
198 * @param string $text the text to be converted
199 * @param string $toVariant the target language code
200 * @return string the converted text
201 * @private
202 */
203 function autoConvert($text, $toVariant=false) {
204 $fname="LanguageConverter::autoConvert";
205
206 wfProfileIn( $fname );
207
208 if(!$this->mTablesLoaded)
209 $this->loadTables();
210
211 if(!$toVariant)
212 $toVariant = $this->getPreferredVariant();
213 if(!in_array($toVariant, $this->mVariants))
214 return $text;
215
216 /* we convert everything except:
217 1. html markups (anything between < and >)
218 2. html entities
219 3. place holders created by the parser
220 */
221 global $wgParser;
222 if (isset($wgParser) && $wgParser->UniqPrefix()!='')
223 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
224 else
225 $marker = "";
226
227 // this one is needed when the text is inside an html markup
228 $htmlfix = '|<[^>]+$|^[^<>]*>';
229
230 // disable convert to variants between <code></code> tags
231 $codefix = '<code>.+?<\/code>|';
232 // disable convertsion of <script type="text/javascript"> ... </script>
233 $scriptfix = '<script.*?>.*?<\/script>|';
234
235 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
236
237 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
238
239 $m = array_shift($matches);
240
241 $ret = $this->translate($m[0], $toVariant);
242 $mstart = $m[1]+strlen($m[0]);
243 foreach($matches as $m) {
244 $ret .= substr($text, $mstart, $m[1]-$mstart);
245 $ret .= $this->translate($m[0], $toVariant);
246 $mstart = $m[1] + strlen($m[0]);
247 }
248 wfProfileOut( $fname );
249 return $ret;
250 }
251
252 /**
253 * Translate a string to a variant
254 * Doesn't process markup or do any of that other stuff, for that use convert()
255 *
256 * @param string $text Text to convert
257 * @param string $variant Variant language code
258 * @return string Translated text
259 */
260 function translate( $text, $variant ) {
261 wfProfileIn( __METHOD__ );
262 if( !$this->mTablesLoaded )
263 $this->loadTables();
264 $text = $this->mTables[$variant]->replace( $text );
265 wfProfileOut( __METHOD__ );
266 return $text;
267 }
268
269 /**
270 * convert text to all supported variants
271 *
272 * @param string $text the text to be converted
273 * @return array of string
274 * @public
275 */
276 function autoConvertToAllVariants($text) {
277 $fname="LanguageConverter::autoConvertToAllVariants";
278 wfProfileIn( $fname );
279 if( !$this->mTablesLoaded )
280 $this->loadTables();
281
282 $ret = array();
283 foreach($this->mVariants as $variant) {
284 $ret[$variant] = $this->translate($text, $variant);
285 }
286
287 wfProfileOut( $fname );
288 return $ret;
289 }
290
291 /**
292 * convert link text to all supported variants
293 *
294 * @param string $text the text to be converted
295 * @return array of string
296 * @public
297 */
298 function convertLinkToAllVariants($text) {
299 if( !$this->mTablesLoaded )
300 $this->loadTables();
301
302 $ret = array();
303 $tarray = explode($this->mMarkup['begin'], $text);
304 $tfirst = array_shift($tarray);
305
306 foreach($this->mVariants as $variant)
307 $ret[$variant] = $this->translate($tfirst,$variant);
308
309 foreach($tarray as $txt) {
310 $marked = explode($this->mMarkup['end'], $txt, 2);
311
312 foreach($this->mVariants as $variant){
313 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
314 if(array_key_exists(1, $marked))
315 $ret[$variant] .= $this->translate($marked[1],$variant);
316 }
317
318 }
319
320 return $ret;
321 }
322
323
324 /**
325 * Convert text using a parser object for context
326 */
327 function parserConvert( $text, &$parser ) {
328 global $wgDisableLangConversion;
329 /* don't do anything if this is the conversion table */
330 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
331 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
332 {
333 return $text;
334 }
335
336 if($wgDisableLangConversion)
337 return $text;
338
339 $text = $this->convert( $text );
340 $parser->mOutput->setTitleText( $this->mTitleDisplay );
341 return $text;
342 }
343
344 /**
345 * Parse flags with syntax -{FLAG| ... }-
346 *
347 */
348 function parseFlags($marked){
349 $flags = array();
350
351 // for multi-FLAGs
352 if(strlen($marked) < 2 )
353 return array($marked,array('R'));
354
355 $tt = explode($this->mMarkup['flagsep'], $marked, 2);
356
357 if(count($tt) == 2) {
358 $f = explode($this->mMarkup['varsep'], $tt[0]);
359 foreach($f as $ff) {
360 $ff = trim($ff);
361 if(array_key_exists($ff, $this->mFlags) &&
362 !in_array($this->mFlags[$ff], $flags))
363 $flags[] = $this->mFlags[$ff];
364 }
365 $rules = $tt[1];
366 } else {
367 $rules = $marked;
368 }
369
370 if( !in_array('R',$flags) ){
371 //FIXME: may cause trouble here...
372 //strip &nbsp; since it interferes with the parsing, plus,
373 //all spaces should be stripped in this tag anyway.
374 $rules = str_replace('&nbsp;', '', $rules);
375 $rules = str_replace('=&gt;','=>',$rules);
376 }
377
378 //check flags
379 if( in_array('R',$flags) ){
380 $flags = array('R');// remove other flags
381 } elseif ( in_array('N',$flags) ){
382 $flags = array('N');// remove other flags
383 } elseif ( in_array('-',$flags) ){
384 $flags = array('-');// remove other flags
385 } elseif (count($flags)==1 && $flags[0]=='T'){
386 $flags[]='H';
387 } elseif ( in_array('H',$flags) ){
388 // replace A flag, and remove other flags except T
389 $temp=array('+','H');
390 if(in_array('T',$flags)) $temp[] = 'T';
391 if(in_array('D',$flags)) $temp[] = 'D';
392 $flags = $temp;
393 } else {
394 if ( in_array('A',$flags)) {
395 $flags[]='+';
396 $flags[]='S';
397 }
398 if ( in_array('D',$flags) )
399 $flags=array_diff($flags,array('S'));
400 }
401 if ( count($flags)==0 )
402 $flags = array('S');
403
404 return array($rules,$flags);
405 }
406
407 function getRulesDesc($bidtable,$unidtable){
408 $text='';
409 foreach($bidtable as $k => $v)
410 $text .= $this->mVariantNames[$k].':'.$v.';';
411 foreach($unidtable as $k => $a)
412 foreach($a as $from=>$to)
413 $text.=$from.'⇒'.$this->mVariantNames[$k].':'.$to.';';
414 return $text;
415 }
416
417 /**
418 * parse the manually marked conversion rule
419 * @param string $rule the text of the rule
420 * @return array of the translation in each variant
421 * @private
422 */
423 function getConvTableFromRules($rules,$flags=array()) {
424 $bidtable = array();
425 $unidtable = array();
426 $choice = explode($this->mMarkup['varsep'], $rules );
427 foreach($choice as $c) {
428 $v = explode($this->mMarkup['codesep'], $c);
429 if(count($v) != 2)
430 continue;// syntax error, skip
431 $to=trim($v[1]);
432 $v=trim($v[0]);
433 $u = explode($this->mMarkup['unidsep'], $v);
434 if(count($u) == 1) {
435 $bidtable[$v] = $to;
436 } else if(count($u) == 2){
437 $from=trim($u[0]);$v=trim($u[1]);
438 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
439 $unidtable[$v]=array($from=>$to);
440 else
441 $unidtable[$v][$from]=$to;
442 }
443 // syntax error, pass
444 }
445 return array($bidtable,$unidtable);
446 }
447
448 /**
449 * get display text on markup -{...}-
450 * @param string $rules the original code
451 * @param array $flags FLAGs
452 * @param array $bidtable bidirectional convert table
453 * @param string $unidtable unidirectional convert table
454 * @param string $variant the current variant
455 * @param bool $$doConvert if do convert
456 * @private
457 */
458 function getRulesDisplay($rules,$flags,
459 $bidtable,$unidtable,
460 $variant=false,$doConvert=true){
461 if(!$variant) $variant = $this->getPreferredVariant();
462 $is_mc_disable = $this->mManualLevel[$variant]=='disable';
463
464 if( in_array('R',$flags) ) {
465 // if we don't do content convert, still strip the -{}- tags
466 $disp = $rules;
467 } elseif ( in_array('N',$flags) ){
468 // proces N flag: output current variant name
469 $disp = $this->mVariantNames[trim($rules)];
470 } elseif ( in_array('D',$flags) ){
471 // proces D flag: output rules description
472 $disp = $this->getRulesDesc($bidtable,$unidtable);
473 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
474 // proces H,- flag or T only: output nothing
475 $disp = '';
476 } elseif ( in_array('S',$flags) ){
477 // the text converted
478 if($doConvert){
479 // display current variant in bidirectional array
480 $disp = $this->getTextInCArray($variant,$bidtable);
481 // or display current variant in fallbacks
482 if(!$disp)
483 $disp = $this->getTextInCArray($this->getVariantFallbacks($variant),$bidtable);
484 // or display current variant in unidirectional array
485 if(!$disp && array_key_exists($variant,$unidtable)){
486 $disp = array_values($unidtable[$variant]);
487 $disp = $disp[0];
488 }
489 // or display frist text under disable manual convert
490 if(!$disp && $is_mc_disable) {
491 if(count($bidtable)>0){
492 $disp = array_values($bidtable);
493 $disp = $disp[0];
494 } else {
495 $disp = array_values($unidtable);
496 $disp = array_values($disp[0]);
497 $disp = $disp[0];
498 }
499 }
500 } else {// no convert
501 $disp = $rules;
502 }
503 } elseif ( in_array('T',$flags) ) {
504 // proces T flag : output nothing
505 $disp = '';
506 }
507 else
508 $disp= $this->mManualCodeError;
509
510 return $disp;
511 }
512
513 function applyManualFlag($flags,$bidtable,$unidtable,$variant=false){
514 if(!$variant) $variant = $this->getPreferredVariant();
515
516 $is_title_flag = in_array('T', $flags);
517 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
518 if($is_title_flag){
519 $this->mTitleFromFlag = true;
520 $this->mTitleDisplay = $this->getRulesDisplay($rules,array('S'),
521 $bidtable,$unidtable,
522 $variant,
523 $this->mDoTitleConvert);
524 }
525
526 if($this->mManualLevel[$variant]=='disable') return;
527
528 $is_remove_flag = !$is_title_flag && in_array('-', $flags);
529 $is_add_flag = !$is_remove_flag && in_array('+', $flags);
530 $is_bidMC = $this->mManualLevel[$variant]=='bidirectional';
531 $is_unidMC = $this->mManualLevel[$variant]=='unidirectional';
532 $vmarked=array();
533
534 foreach($this->mVariants as $v) {
535 /* for bidirectional array
536 fill in the missing variants, if any,
537 with fallbacks */
538 if($is_bidMC && !array_key_exists($v, $bidtable)) {
539 $vf = $this->getTextInCArray($this->getVariantFallbacks($v),$bidtable);
540 if($vf) $bidtable[$v] = $vf;
541 }
542 if($is_bidMC && array_key_exists($v,$bidtable)){
543 foreach($vmarked as $vo){
544 // use syntax:
545 // -{A|zh:WordZh;zh-tw:WordTw}- or -{+|zh:WordZh;zh-tw:WordTw}-
546 // to introduce a custom mapping between
547 // words WordZh and WordTw in the whole text
548 if($is_add_flag){
549 $this->mTables[$v]->setPair($bidtable[$vo], $bidtable[$v]);
550 $this->mTables[$vo]->setPair($bidtable[$v], $bidtable[$vo]);
551 }
552 // use syntax -{-|zh:WordZh;zh-tw:WordTw}- to remove a conversion
553 // words WordZh and WordTw in the whole text
554 if($is_remove_flag){
555 $this->mTables[$v]->removePair($bidtable[$vo]);
556 $this->mTables[$vo]->removePair($bidtable[$v]);
557 }
558 }
559 $vmarked[]=$v;
560 }
561 /*for unidirectional array
562 fill to convert tables */
563 if($is_unidMC && array_key_exists($v,$unidtable)){
564 if($is_add_flag)$this->mTables[$v]->mergeArray($unidtable[$v]);
565 if($is_remove_flag)$this->mTables[$v]->removeArray($unidtable[$v]);
566 }
567 }
568 }
569
570 /**
571 * Parse rules and flags
572 * @private
573 */
574 function parseRules($rules,$flags,$variant=false){
575 if(!$variant) $variant = $this->getPreferredVariant();
576
577 list($bidtable,$unidtable) = $this->getConvTableFromRules($rules, $flags);
578 if(count($bidtable)==0 && count($unidtable)==0
579 && !in_array('N',$flags) && !in_array('T',$flags) )
580 $flags = array('R');
581 $disp = $this->getRulesDisplay($rules,$flags,
582 $bidtable,$unidtable,
583 $variant,
584 $this->mDoContentConvert);
585 $this->applyManualFlag($flags,$bidtable,$unidtable);
586
587 return $disp;
588 }
589
590 function convertTitle($text){
591 // check for __NOTC__ tag
592 if( !$this->mDoTitleConvert ) {
593 $this->mTitleDisplay = $text;
594 return $text;
595 }
596
597 // use the title from the T flag if any
598 if($this->mTitleFromFlag){
599 $this->mTitleFromFlag = false;
600 return $this->mTitleDisplay;
601 }
602
603 global $wgRequest;
604 $isredir = $wgRequest->getText( 'redirect', 'yes' );
605 $action = $wgRequest->getText( 'action' );
606 if ( $isredir == 'no' || $action == 'edit' ) {
607 return $text;
608 } else {
609 $this->mTitleDisplay = $this->convert($text);
610 return $this->mTitleDisplay;
611 }
612 }
613
614 /**
615 * convert text to different variants of a language. the automatic
616 * conversion is done in autoConvert(). here we parse the text
617 * marked with -{}-, which specifies special conversions of the
618 * text that can not be accomplished in autoConvert()
619 *
620 * syntax of the markup:
621 * -{code1:text1;code2:text2;...}- or
622 * -{flags|code1:text1;code2:text2;...}- or
623 * -{text}- in which case no conversion should take place for text
624 *
625 * @param string $text text to be converted
626 * @param bool $isTitle whether this conversion is for the article title
627 * @return string converted text
628 * @access public
629 */
630 function convert( $text , $isTitle=false) {
631
632 $mw =& MagicWord::get( 'notitleconvert' );
633 if( $mw->matchAndRemove( $text ) )
634 $this->mDoTitleConvert = false;
635 $mw =& MagicWord::get( 'nocontentconvert' );
636 if( $mw->matchAndRemove( $text ) ) {
637 $this->mDoContentConvert = false;
638 }
639
640 // no conversion if redirecting
641 $mw =& MagicWord::get( 'redirect' );
642 if( $mw->matchStart( $text ))
643 return $text;
644
645 // for title convertion
646 if ($isTitle) return $this->convertTitle($text);
647
648 $plang = $this->getPreferredVariant();
649
650 $tarray = explode($this->mMarkup['begin'], $text);
651 $tfirst = array_shift($tarray);
652 if($this->mDoContentConvert)
653 $text = $this->autoConvert($tfirst,$plang);
654 else
655 $text = $tfirst;
656 foreach($tarray as $txt) {
657 $marked = explode($this->mMarkup['end'], $txt, 2);
658
659 // strip the flags from syntax like -{T| ... }-
660 list($rules,$flags) = $this->parseFlags($marked[0]);
661
662 $text .= $this->parseRules($rules,$flags,$plang);
663
664 if(array_key_exists(1, $marked)){
665 if( $this->mDoContentConvert )
666 $text .= $this->autoConvert($marked[1],$plang);
667 else
668 $text .= $marked[1];
669 }
670 }
671
672 return $text;
673 }
674
675 /**
676 * if a language supports multiple variants, it is
677 * possible that non-existing link in one variant
678 * actually exists in another variant. this function
679 * tries to find it. See e.g. LanguageZh.php
680 *
681 * @param string $link the name of the link
682 * @param mixed $nt the title object of the link
683 * @return null the input parameters may be modified upon return
684 * @access public
685 */
686 function findVariantLink( &$link, &$nt ) {
687 global $wgDisableLangConversion;
688 $linkBatch = new LinkBatch();
689
690 $ns=NS_MAIN;
691
692 if(is_object($nt))
693 $ns = $nt->getNamespace();
694
695 $variants = $this->autoConvertToAllVariants($link);
696 if($variants == false) //give up
697 return;
698
699 $titles = array();
700
701 foreach( $variants as $v ) {
702 if($v != $link){
703 $varnt = Title::newFromText( $v, $ns );
704 if(!is_null($varnt)){
705 $linkBatch->addObj($varnt);
706 $titles[]=$varnt;
707 }
708 }
709 }
710
711 // fetch all variants in single query
712 $linkBatch->execute();
713
714 foreach( $titles as $varnt ) {
715 if( $varnt->getArticleID() > 0 ) {
716 $nt = $varnt;
717 if( !$wgDisableLangConversion )
718 $link = $v;
719 break;
720 }
721 }
722 }
723
724 /**
725 * returns language specific hash options
726 *
727 * @access public
728 */
729 function getExtraHashOptions() {
730 $variant = $this->getPreferredVariant();
731 return '!' . $variant ;
732 }
733
734 /**
735 * get title text as defined in the body of the article text
736 *
737 * @access public
738 */
739 function getParsedTitle() {
740 return $this->mTitleDisplay;
741 }
742
743 /**
744 * a write lock to the cache
745 *
746 * @private
747 */
748 function lockCache() {
749 global $wgMemc;
750 $success = false;
751 for($i=0; $i<30; $i++) {
752 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
753 break;
754 sleep(1);
755 }
756 return $success;
757 }
758
759 /**
760 * unlock cache
761 *
762 * @private
763 */
764 function unlockCache() {
765 global $wgMemc;
766 $wgMemc->delete($this->mCacheKey . "lock");
767 }
768
769
770 /**
771 * Load default conversion tables
772 * This method must be implemented in derived class
773 *
774 * @private
775 */
776 function loadDefaultTables() {
777 $name = get_class($this);
778 wfDie("Must implement loadDefaultTables() method in class $name");
779 }
780
781 /**
782 * load conversion tables either from the cache or the disk
783 * @private
784 */
785 function loadTables($fromcache=true) {
786 global $wgMemc;
787 if( $this->mTablesLoaded )
788 return;
789 wfProfileIn( __METHOD__ );
790 $this->mTablesLoaded = true;
791 $this->mTables = false;
792 if($fromcache) {
793 wfProfileIn( __METHOD__.'-cache' );
794 $this->mTables = $wgMemc->get( $this->mCacheKey );
795 wfProfileOut( __METHOD__.'-cache' );
796 }
797 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
798 wfProfileIn( __METHOD__.'-recache' );
799 // not in cache, or we need a fresh reload.
800 // we will first load the default tables
801 // then update them using things in MediaWiki:Zhconversiontable/*
802 $this->loadDefaultTables();
803 foreach($this->mVariants as $var) {
804 $cached = $this->parseCachedTable($var);
805 $this->mTables[$var]->mergeArray($cached);
806 }
807
808 $this->postLoadTables();
809 $this->mTables[self::CACHE_VERSION_KEY] = true;
810
811 if($this->lockCache()) {
812 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
813 $this->unlockCache();
814 }
815 wfProfileOut( __METHOD__.'-recache' );
816 }
817 wfProfileOut( __METHOD__ );
818 }
819
820 /**
821 * Hook for post processig after conversion tables are loaded
822 *
823 */
824 function postLoadTables() {}
825
826 /**
827 * Reload the conversion tables
828 *
829 * @private
830 */
831 function reloadTables() {
832 if($this->mTables)
833 unset($this->mTables);
834 $this->mTablesLoaded = false;
835 $this->loadTables(false);
836 }
837
838
839 /**
840 * parse the conversion table stored in the cache
841 *
842 * the tables should be in blocks of the following form:
843 * -{
844 * word => word ;
845 * word => word ;
846 * ...
847 * }-
848 *
849 * to make the tables more manageable, subpages are allowed
850 * and will be parsed recursively if $recursive=true
851 *
852 */
853 function parseCachedTable($code, $subpage='', $recursive=true) {
854 global $wgMessageCache;
855 static $parsed = array();
856
857 if(!is_object($wgMessageCache))
858 return array();
859
860 $key = 'Conversiontable/'.$code;
861 if($subpage)
862 $key .= '/' . $subpage;
863
864 if(array_key_exists($key, $parsed))
865 return array();
866
867
868 $txt = $wgMessageCache->get( $key, true, true, true );
869
870 // get all subpage links of the form
871 // [[MediaWiki:conversiontable/zh-xx/...|...]]
872 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
873 $subs = explode('[[', $txt);
874 $sublinks = array();
875 foreach( $subs as $sub ) {
876 $link = explode(']]', $sub, 2);
877 if(count($link) != 2)
878 continue;
879 $b = explode('|', $link[0]);
880 $b = explode('/', trim($b[0]), 3);
881 if(count($b)==3)
882 $sublink = $b[2];
883 else
884 $sublink = '';
885
886 if($b[0] == $linkhead && $b[1] == $code) {
887 $sublinks[] = $sublink;
888 }
889 }
890
891
892 // parse the mappings in this page
893 $blocks = explode($this->mMarkup['begin'], $txt);
894 array_shift($blocks);
895 $ret = array();
896 foreach($blocks as $block) {
897 $mappings = explode($this->mMarkup['end'], $block, 2);
898 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
899 $table = explode( ';', $stripped );
900 foreach( $table as $t ) {
901 $m = explode( '=>', $t );
902 if( count( $m ) != 2)
903 continue;
904 // trim any trailling comments starting with '//'
905 $tt = explode('//', $m[1], 2);
906 $ret[trim($m[0])] = trim($tt[0]);
907 }
908 }
909 $parsed[$key] = true;
910
911
912 // recursively parse the subpages
913 if($recursive) {
914 foreach($sublinks as $link) {
915 $s = $this->parseCachedTable($code, $link, $recursive);
916 $ret = array_merge($ret, $s);
917 }
918 }
919
920 if ($this->mUcfirst) {
921 foreach ($ret as $k => $v) {
922 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
923 }
924 }
925 return $ret;
926 }
927
928 /**
929 * Enclose a string with the "no conversion" tag. This is used by
930 * various functions in the Parser
931 *
932 * @param string $text text to be tagged for no conversion
933 * @return string the tagged text
934 */
935 function markNoConversion($text, $noParse=false) {
936 # don't mark if already marked
937 if(strpos($text, $this->mMarkup['begin']) ||
938 strpos($text, $this->mMarkup['end']))
939 return $text;
940
941 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
942 return $ret;
943 }
944
945 /**
946 * convert the sorting key for category links. this should make different
947 * keys that are variants of each other map to the same key
948 */
949 function convertCategoryKey( $key ) {
950 return $key;
951 }
952 /**
953 * hook to refresh the cache of conversion tables when
954 * MediaWiki:conversiontable* is updated
955 * @private
956 */
957 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
958 $titleobj = $article->getTitle();
959 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
960 $title = $titleobj->getDBkey();
961 $t = explode('/', $title, 3);
962 $c = count($t);
963 if( $c > 1 && $t[0] == 'Conversiontable' ) {
964 if(in_array($t[1], $this->mVariants)) {
965 $this->reloadTables();
966 }
967 }
968 }
969 return true;
970 }
971
972 /**
973 * Armour rendered math against conversion
974 * Wrap math into rawoutput -{R| math }- syntax
975 */
976 function armourMath($text){
977 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
978 return $ret;
979 }
980 }