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