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