summaryrefslogtreecommitdiff
path: root/languages/LanguageConverter.php
blob: a949ad4e0b524d9581297ef764536834d808fa5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
<?php
/**
  * @package MediaWiki
  * @subpackage Language
  *
  * @author Zhengzhu Feng <zhengzhu@gmail.com>
  * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  */

class LanguageConverter {
	var $mPreferredVariant='';
	var $mMainLanguageCode;
	var $mVariants, $mVariantFallbacks;
	var $mTablesLoaded = false;
	var $mUseFss = false;
	var $mTables;
	var $mFssObjects;
	var $mTitleDisplay='';
	var $mDoTitleConvert=true, $mDoContentConvert=true;
	var $mCacheKey;
	var $mLangObj;
	var $mMarkup;
	var $mFlags;
	var $mUcfirst = false;
	var $mNoTitleConvert = false;
	/**
     * Constructor
	 *
     * @param string $maincode the main language code of this language
     * @param array $variants the supported variants of this language
     * @param array $variantfallback the fallback language of each variant
     * @param array $markup array defining the markup used for manual conversion
	 * @param array $flags array defining the custom strings that maps to the flags
     * @access public
     */
	function __construct($langobj, $maincode,
								$variants=array(),
								$variantfallbacks=array(),
								$markup=array(),
								$flags = array()) {
		global $wgLegalTitleChars;
		$this->mLangObj = $langobj;
		$this->mMainLanguageCode = $maincode;
		$this->mVariants = $variants;
		$this->mVariantFallbacks = $variantfallbacks;
		$this->mCacheKey = wfMemcKey( 'conversiontables' );
		$m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
				   'varsep'=>';', 'end'=>'}-');
		$this->mMarkup = array_merge($m, $markup);
		$f = array('A'=>'A', 'T'=>'T');
		$this->mFlags = array_merge($f, $flags);
		if ( function_exists( 'fss_prep_replace' ) ) {
			$this->mUseFss = true;
		}
	}

	/**
     * @access public
     */
	function getVariants() {
		return $this->mVariants;
	}

	/**
	 * in case some variant is not defined in the markup, we need
	 * to have some fallback. for example, in zh, normally people
	 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
	 * when zh-sg is preferred but not defined, we will pick zh-cn
	 * in this case. right now this is only used by zh.
	 *
	 * @param string $v the language code of the variant
	 * @return string the code of the fallback language or false if there is no fallback
     * @private
	*/
	function getVariantFallback($v) {
		return $this->mVariantFallbacks[$v];
	}


	/**
	 * get preferred language variants.
	 * @param boolean $fromUser Get it from $wgUser's preferences
     * @return string the preferred language code
     * @access public
	*/
	function getPreferredVariant( $fromUser = true ) {
		global $wgUser, $wgRequest;

		if($this->mPreferredVariant)
			return $this->mPreferredVariant;

		// see if the preference is set in the request
		$req = $wgRequest->getText( 'variant' );
		if( in_array( $req, $this->mVariants ) ) {
			$this->mPreferredVariant = $req;
			return $req;
		}

		// get language variant preference from logged in users
		// Don't call this on stub objects because that causes infinite 
		// recursion during initialisation
		if( $fromUser && $wgUser->isLoggedIn() )  {
			$this->mPreferredVariant = $wgUser->getOption('variant');
			return $this->mPreferredVariant;
		}

		# FIXME rewrite code for parsing http header. The current code
		# is written specific for detecting zh- variants
		if( !$this->mPreferredVariant ) {
			// see if some supported language variant is set in the
			// http header, but we don't set the mPreferredVariant
			// variable in case this is called before the user's
			// preference is loaded
			$pv=$this->mMainLanguageCode;
			if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
				$header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
				$zh = strstr($header, 'zh-');
				if($zh) {
					$pv = substr($zh,0,5);
				}
			}
			return $pv;
		}
	}

	/**
     * dictionary-based conversion
     *
     * @param string $text the text to be converted
     * @param string $toVariant the target language code
     * @return string the converted text
     * @private
     */
	function autoConvert($text, $toVariant=false) {
		$fname="LanguageConverter::autoConvert";

		wfProfileIn( $fname );

		if(!$this->mTablesLoaded)
			$this->loadTables();

		if(!$toVariant)
			$toVariant = $this->getPreferredVariant();
		if(!in_array($toVariant, $this->mVariants))
			return $text;

		/* we convert everything except:
		   1. html markups (anything between < and >)
		   2. html entities
		   3. place holders created by the parser
		*/
		global $wgParser;
		if (isset($wgParser))
			$marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
		else
			$marker = "";

		// this one is needed when the text is inside an html markup
		$htmlfix = '|<[^>]+$|^[^<>]*>';

		// disable convert to variants between <code></code> tags
		$codefix = '<code>.+?<\/code>|';

		$reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
	
		$matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);

		$m = array_shift($matches);

		$ret = $this->translate($m[0], $toVariant);
		$mstart = $m[1]+strlen($m[0]);
		foreach($matches as $m) {
			$ret .= substr($text, $mstart, $m[1]-$mstart);
			$ret .= $this->translate($m[0], $toVariant);
			$mstart = $m[1] + strlen($m[0]);
		}
		wfProfileOut( $fname );
		return $ret;
	}

	/**
	 * Translate a string to a variant
	 * Doesn't process markup or do any of that other stuff, for that use convert()
	 *
	 * @param string $text Text to convert
	 * @param string $variant Variant language code
	 * @return string Translated text
	 */
	function translate( $text, $variant ) {
		if( !$this->mTablesLoaded )
			$this->loadTables();
		if ( $this->mUseFss ) {
			return fss_exec_replace( $this->mFssObjects[$variant], $text );
		} else {
			return strtr( $text, $this->mTables[$variant] );
		}
	}

	/**
     * convert text to all supported variants
     *
     * @param string $text the text to be converted
     * @return array of string
     * @public
     */
	function autoConvertToAllVariants($text) {
		$fname="LanguageConverter::autoConvertToAllVariants";
		wfProfileIn( $fname );
		if( !$this->mTablesLoaded )
			$this->loadTables();

		$ret = array();
		foreach($this->mVariants as $variant) {
			$ret[$variant] = $this->translate($text, $variant);
		}

		wfProfileOut( $fname );
		return $ret;
	}

	/**
     * convert link text to all supported variants
     *
     * @param string $text the text to be converted
     * @return array of string
     * @public
     */
	function convertLinkToAllVariants($text) {
		if( !$this->mTablesLoaded )
			$this->loadTables();

		$ret = array();
		$tarray = explode($this->mMarkup['begin'], $text);
		$tfirst = array_shift($tarray);

		foreach($this->mVariants as $variant)
			$ret[$variant] = $this->translate($tfirst,$variant);

		foreach($tarray as $txt) {
			$marked = explode($this->mMarkup['end'], $txt, 2);

			foreach($this->mVariants as $variant){
				$ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
				if(array_key_exists(1, $marked))
					$ret[$variant] .= $this->translate($marked[1],$variant);
			}
			
		}

		return $ret;
	}


	/**
	 * Convert text using a parser object for context
	 */
	function parserConvert( $text, &$parser ) {
		global $wgDisableLangConversion;
		/* don't do anything if this is the conversion table */
		if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
				 strpos($parser->mTitle->getText(), "Conversiontable") !== false ) 
		{
			return $text;
		}

		if($wgDisableLangConversion)
			return $text;

		$text = $this->convert( $text );
		$parser->mOutput->setTitleText( $this->mTitleDisplay );
		return $text;
	}

	/**
	 * convert text to different variants of a language. the automatic
	 * conversion is done in autoConvert(). here we parse the text
	 * marked with -{}-, which specifies special conversions of the
	 * text that can not be accomplished in autoConvert()
	 *
	 * syntax of the markup:
	 * -{code1:text1;code2:text2;...}-  or
	 * -{text}- in which case no conversion should take place for text
     *
     * @param string $text text to be converted
     * @param bool $isTitle whether this conversion is for the article title
     * @return string converted text
     * @access public
     */
	function convert( $text , $isTitle=false) {
		$mw =& MagicWord::get( 'notitleconvert'   );
		if( $mw->matchAndRemove( $text ) )
			$this->mDoTitleConvert = false;

		$mw =& MagicWord::get( 'nocontentconvert'   );
		if( $mw->matchAndRemove( $text ) ) {
			$this->mDoContentConvert = false;
		}

		// no conversion if redirecting
		$mw =& MagicWord::get( 'redirect'   );
		if( $mw->matchStart( $text ))
			return $text;

		if( $isTitle ) {
			if($this->mNoTitleConvert){
				$this->mTitleDisplay = $text;			
				return $text;
			}

			if( !$this->mDoTitleConvert ) {
				$this->mTitleDisplay = $text;
				return $text;
			}

			global $wgRequest;
			$isredir = $wgRequest->getText( 'redirect', 'yes' );
			$action = $wgRequest->getText( 'action' );
			if ( $isredir == 'no' || $action == 'edit' ) {
				return $text;
			}
			else {
				$this->mTitleDisplay = $this->convert($text);
				return $this->mTitleDisplay;
			}
		}

		if( !$this->mDoContentConvert )
			return $text;

		$plang = $this->getPreferredVariant();
		if( isset( $this->mVariantFallbacks[$plang] ) ) {
			$fallback = $this->mVariantFallbacks[$plang];
		} else {
			// This sounds... bad?
			$fallback = '';
		}

		$tarray = explode($this->mMarkup['begin'], $text);
		$tfirst = array_shift($tarray);
		$text = $this->autoConvert($tfirst);
		foreach($tarray as $txt) {
			$marked = explode($this->mMarkup['end'], $txt, 2);
			$flags = array();
			$tt = explode($this->mMarkup['flagsep'], $marked[0], 2);

			if(sizeof($tt) == 2) {
				$f = explode($this->mMarkup['varsep'], $tt[0]);
				foreach($f as $ff) {
					$ff = trim($ff);
					if(array_key_exists($ff, $this->mFlags) &&
						!array_key_exists($this->mFlags[$ff], $flags))
						$flags[] = $this->mFlags[$ff];
				}
				$rules = $tt[1];
			}
			else
				$rules = $marked[0];

			//FIXME: may cause trouble here...
			//strip &nbsp; since it interferes with the parsing, plus,
			//all spaces should be stripped in this tag anyway.
			$rules = str_replace('&nbsp;', '', $rules);

			$carray = $this->parseManualRule($rules, $flags);
			$disp = '';
			if(array_key_exists($plang, $carray))
				$disp = $carray[$plang];
			else if(array_key_exists($fallback, $carray))
				$disp = $carray[$fallback];
			if($disp) {
				if(in_array('T',  $flags))
					$this->mTitleDisplay = $disp;
				else
					$text .= $disp;

				if(in_array('A', $flags)) {
					/* modify the conversion table for this session*/

					/* fill in the missing variants, if any,
					    with fallbacks */
					foreach($this->mVariants as $v) {
						if(!array_key_exists($v, $carray)) {
							$vf = $this->getVariantFallback($v);
							if(array_key_exists($vf, $carray))
								$carray[$v] = $carray[$vf];
						}
					}

					foreach($this->mVariants as $vfrom) {
						if(!array_key_exists($vfrom, $carray))
							continue;
						foreach($this->mVariants as $vto) {
							if($vfrom == $vto)
								continue;
							if(!array_key_exists($vto, $carray))
								continue;
							$this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];

						}
					}
					if ( $this->mUseFss ) {
						$this->generateFssObjects();
					}
				}
			}
			else {
				$text .= $marked[0];
			}
			if(array_key_exists(1, $marked))
				$text .= $this->autoConvert($marked[1]);
		}

		return $text;
	}

	/**
	 * parse the manually marked conversion rule
	 * @param string $rule the text of the rule
	 * @return array of the translation in each variant
	 * @private
	 */
	function parseManualRule($rules, $flags=array()) {

		$choice = explode($this->mMarkup['varsep'], $rules);
		$carray = array();
		if(sizeof($choice) == 1) {
			/* a single choice */
			foreach($this->mVariants as $v)
				$carray[$v] = $choice[0];
		}
		else {
			foreach($choice as $c) {
				$v = explode($this->mMarkup['codesep'], $c);
				if(sizeof($v) != 2) // syntax error, skip
					continue;
				$carray[trim($v[0])] = trim($v[1]);
			}
		}
		return $carray;
	}

	/**
	 * if a language supports multiple variants, it is
	 * possible that non-existing link in one variant
	 * actually exists in another variant. this function
	 * tries to find it. See e.g. LanguageZh.php
	 *
	 * @param string $link the name of the link
	 * @param mixed $nt the title object of the link
	 * @return null the input parameters may be modified upon return
     * @access public
	 */
	function findVariantLink( &$link, &$nt ) {
		global $wgDisableLangConversion;
		$pref = $this->getPreferredVariant();
		$ns=0;
		if(is_object($nt))
			$ns = $nt->getNamespace();

		$variants = $this->autoConvertToAllVariants($link);
		if($variants == false) //give up
			return;
		foreach( $variants as $v ) {
			$varnt = Title::newFromText( $v, $ns );
			if( $varnt && $varnt->getArticleID() > 0 ) {
				$nt = $varnt;
				if( !$wgDisableLangConversion )
					$link = $v;
				break;
			}
		}
	}

    /**
     * returns language specific hash options
     *
     * @access public
     */
	function getExtraHashOptions() {
		$variant = $this->getPreferredVariant();
		return '!' . $variant ;
	}

    /**
     * get title text as defined in the body of the article text
     *
     * @access public
     */
	function getParsedTitle() {
		return $this->mTitleDisplay;
	}

	/**
     * a write lock to the cache
     *
     * @private
     */
	function lockCache() {
		global $wgMemc;
		$success = false;
		for($i=0; $i<30; $i++) {
			if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
				break;
			sleep(1);
		}
		return $success;
	}

	/**
     * unlock cache
     *
     * @private
     */
	function unlockCache() {
		global $wgMemc;
		$wgMemc->delete($this->mCacheKey . "lock");
	}


	/**
     * Load default conversion tables
     * This method must be implemented in derived class
     *
     * @private
     */
	function loadDefaultTables() {
		$name = get_class($this);
		wfDie("Must implement loadDefaultTables() method in class $name");
	}

	/**
     * load conversion tables either from the cache or the disk
     * @private
     */
	function loadTables($fromcache=true) {
		global $wgMemc;
		if( $this->mTablesLoaded )
			return;
		$this->mTablesLoaded = true;
		if($fromcache) {
			$this->mTables = $wgMemc->get( $this->mCacheKey );
			if( !empty( $this->mTables ) ) //all done
				return;
		}
		// not in cache, or we need a fresh reload.
		// we will first load the default tables
		// then update them using things in MediaWiki:Zhconversiontable/*
		global $wgMessageCache;
		$this->loadDefaultTables();
		foreach($this->mVariants as $var) {
			$cached = $this->parseCachedTable($var);
			$this->mTables[$var] = array_merge($this->mTables[$var], $cached);
		}

		$this->postLoadTables();

		if($this->lockCache()) {
			$wgMemc->set($this->mCacheKey, $this->mTables, 43200);
			$this->unlockCache();
		}
		if ( $this->mUseFss ) {
			$this->generateFssObjects();
		}
	}

	/**
	 * Generate FSS objects. The FSS extension must be available.
	 */
	function generateFssObjects() {
		foreach ( $this->mTables as $variant => $table ) {
			$this->mFssObjects[$variant] = fss_prep_replace( $table );
		}
	}

    /**
     * Hook for post processig after conversion tables are loaded
     *
     */
	function postLoadTables() {}

    /**
     * Reload the conversion tables
     *
     * @private
     */
	function reloadTables() {
		if($this->mTables)
			unset($this->mTables);
		$this->mTablesLoaded = false;
		$this->loadTables(false);
	}


	/**
     * parse the conversion table stored in the cache
     *
     * the tables should be in blocks of the following form:

     *		-{
     *			word => word ;
     *			word => word ;
     *			...
     *		}-
     *
     *	to make the tables more manageable, subpages are allowed
     *	and will be parsed recursively if $recursive=true
     *
     * @private
	 */
	function parseCachedTable($code, $subpage='', $recursive=true) {
		global $wgMessageCache;
		static $parsed = array();

		if(!is_object($wgMessageCache))
			return array();

		$key = 'Conversiontable/'.$code;
		if($subpage)
			$key .= '/' . $subpage;

		if(array_key_exists($key, $parsed))
			return array();


		$txt = $wgMessageCache->get( $key, true, true, true );

		// get all subpage links of the form
		// [[MediaWiki:conversiontable/zh-xx/...|...]]
		$linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
		$subs = explode('[[', $txt);
		$sublinks = array();
		foreach( $subs as $sub ) {
			$link = explode(']]', $sub, 2);
			if(count($link) != 2)
				continue;
			$b = explode('|', $link[0]);
			$b = explode('/', trim($b[0]), 3);
			if(count($b)==3)
				$sublink = $b[2];
			else
				$sublink = '';

			if($b[0] == $linkhead && $b[1] == $code) {
				$sublinks[] = $sublink;
			}
		}


		// parse the mappings in this page
		$blocks = explode($this->mMarkup['begin'], $txt);
		array_shift($blocks);
		$ret = array();
		foreach($blocks as $block) {
			$mappings = explode($this->mMarkup['end'], $block, 2);
			$stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
			$table = explode( ';', $stripped );
			foreach( $table as $t ) {
				$m = explode( '=>', $t );
				if( count( $m ) != 2)
					continue;
				// trim any trailling comments starting with '//'
				$tt = explode('//', $m[1], 2);
				$ret[trim($m[0])] = trim($tt[0]);
			}
		}
		$parsed[$key] = true;


		// recursively parse the subpages
		if($recursive) {
			foreach($sublinks as $link) {
				$s = $this->parseCachedTable($code, $link, $recursive);
				$ret = array_merge($ret, $s);
			}
		}

		if ($this->mUcfirst) {
			foreach ($ret as $k => $v) {
				$ret[Language::ucfirst($k)] = Language::ucfirst($v);
			}
		}
		return $ret;
	}

	/**
	 * Enclose a string with the "no conversion" tag. This is used by
	 * various functions in the Parser
	 *
	 * @param string $text text to be tagged for no conversion
	 * @return string the tagged text
	*/
	function markNoConversion($text, $noParse=false) {
		# don't mark if already marked
		if(strpos($text, $this->mMarkup['begin']) ||
 		   strpos($text, $this->mMarkup['end']))
			return $text;

		$ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
		return $ret;
	}

	/**
	 * convert the sorting key for category links. this should make different
	 * keys that are variants of each other map to the same key
	*/
	function convertCategoryKey( $key ) {
		return $key;
	}
	/**
     * hook to refresh the cache of conversion tables when
     * MediaWiki:conversiontable* is updated
     * @private
	*/
	function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
		$titleobj = $article->getTitle();
		if($titleobj->getNamespace() == NS_MEDIAWIKI) {
            /*
			global $wgContLang; // should be an LanguageZh.
			if(get_class($wgContLang) != 'languagezh')
				return true;
            */
			$title = $titleobj->getDBkey();
			$t = explode('/', $title, 3);
			$c = count($t);
			if( $c > 1 && $t[0] == 'Conversiontable' ) {
				if(in_array($t[1], $this->mVariants)) {
					$this->reloadTables();
				}
			}
		}
		return true;
	}

	function setNoTitleConvert(){
		$this->mNoTitleConvert = true;
	}

}

?>