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