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