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