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