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