LanguageConverter::captionConvert(): remove HTML tags and escape HTML special chars...
[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 global $wgMessageCache;
846 static $parsed = array();
847
848 if ( !is_object( $wgMessageCache ) ) {
849 return array();
850 }
851
852 $key = 'Conversiontable/' . $code;
853 if ( $subpage ) {
854 $key .= '/' . $subpage;
855 }
856 if ( array_key_exists( $key, $parsed ) ) {
857 return array();
858 }
859
860 if ( strpos( $code, '/' ) === false ) {
861 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
862 if ( $txt === false ) {
863 # FIXME: this method doesn't seem to be expecting
864 # this possible outcome...
865 $txt = '&lt;Conversiontable&gt;';
866 }
867 } else {
868 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
869 "Conversiontable/$code" );
870 if ( $title && $title->exists() ) {
871 $article = new Article( $title );
872 $txt = $article->getContents();
873 } else {
874 $txt = '';
875 }
876 }
877
878 // get all subpage links of the form
879 // [[MediaWiki:conversiontable/zh-xx/...|...]]
880 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
881 ':Conversiontable';
882 $subs = StringUtils::explode( '[[', $txt );
883 $sublinks = array();
884 foreach ( $subs as $sub ) {
885 $link = explode( ']]', $sub, 2 );
886 if ( count( $link ) != 2 ) {
887 continue;
888 }
889 $b = explode( '|', $link[0], 2 );
890 $b = explode( '/', trim( $b[0] ), 3 );
891 if ( count( $b ) == 3 ) {
892 $sublink = $b[2];
893 } else {
894 $sublink = '';
895 }
896
897 if ( $b[0] == $linkhead && $b[1] == $code ) {
898 $sublinks[] = $sublink;
899 }
900 }
901
902 // parse the mappings in this page
903 $blocks = StringUtils::explode( '-{', $txt );
904 $ret = array();
905 $first = true;
906 foreach ( $blocks as $block ) {
907 if ( $first ) {
908 // Skip the part before the first -{
909 $first = false;
910 continue;
911 }
912 $mappings = explode( '}-', $block, 2 );
913 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
914 $mappings[0] );
915 $table = StringUtils::explode( ';', $stripped );
916 foreach ( $table as $t ) {
917 $m = explode( '=>', $t, 3 );
918 if ( count( $m ) != 2 )
919 continue;
920 // trim any trailling comments starting with '//'
921 $tt = explode( '//', $m[1], 2 );
922 $ret[trim( $m[0] )] = trim( $tt[0] );
923 }
924 }
925 $parsed[$key] = true;
926
927 // recursively parse the subpages
928 if ( $recursive ) {
929 foreach ( $sublinks as $link ) {
930 $s = $this->parseCachedTable( $code, $link, $recursive );
931 $ret = array_merge( $ret, $s );
932 }
933 }
934
935 if ( $this->mUcfirst ) {
936 foreach ( $ret as $k => $v ) {
937 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
938 }
939 }
940 return $ret;
941 }
942
943 /**
944 * Enclose a string with the "no conversion" tag. This is used by
945 * various functions in the Parser.
946 *
947 * @param $text String: text to be tagged for no conversion
948 * @param $noParse Unused (?)
949 * @return String: the tagged text
950 */
951 public function markNoConversion( $text, $noParse = false ) {
952 # don't mark if already marked
953 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
954 return $text;
955 }
956
957 $ret = "-{R|$text}-";
958 return $ret;
959 }
960
961 /**
962 * Convert the sorting key for category links. This should make different
963 * keys that are variants of each other map to the same key.
964 */
965 function convertCategoryKey( $key ) {
966 return $key;
967 }
968
969 /**
970 * Hook to refresh the cache of conversion tables when
971 * MediaWiki:conversiontable* is updated.
972 * @private
973 */
974 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
975 $iswatch, $section, $flags, $revision ) {
976 $titleobj = $article->getTitle();
977 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
978 $title = $titleobj->getDBkey();
979 $t = explode( '/', $title, 3 );
980 $c = count( $t );
981 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
982 if ( $this->validateVariant( $t[1] ) ) {
983 $this->reloadTables();
984 }
985 }
986 }
987 return true;
988 }
989
990 /**
991 * Armour rendered math against conversion.
992 * Escape special chars in parsed math text.(in most cases are img elements)
993 */
994 public function armourMath( $text ) {
995 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
996 // any unwanted markup appearing in the math image tag.
997 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
998 return $text;
999 }
1000
1001 /**
1002 * Get the cached separator pattern for ConverterRule::parseRules()
1003 */
1004 function getVarSeparatorPattern() {
1005 if ( is_null( $this->mVarSeparatorPattern ) ) {
1006 // varsep_pattern for preg_split:
1007 // text should be splited by ";" only if a valid variant
1008 // name exist after the markup, for example:
1009 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1010 // <span style="font-size:120%;">yyy</span>;}-
1011 // we should split it as:
1012 // array(
1013 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1014 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1015 // [2] => ''
1016 // )
1017 $pat = '/;\s*(?=';
1018 foreach ( $this->mVariants as $variant ) {
1019 // zh-hans:xxx;zh-hant:yyy
1020 $pat .= $variant . '\s*:|';
1021 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1022 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1023 }
1024 $pat .= '\s*$)/';
1025 $this->mVarSeparatorPattern = $pat;
1026 }
1027 return $this->mVarSeparatorPattern;
1028 }
1029 }
1030
1031 /**
1032 * Parser for rules of language conversion , parse rules in -{ }- tag.
1033 * @ingroup Language
1034 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1035 */
1036 class ConverterRule {
1037 var $mText; // original text in -{text}-
1038 var $mConverter; // LanguageConverter object
1039 var $mManualCodeError = '<strong class="error">code error!</strong>';
1040 var $mRuleDisplay = '';
1041 var $mRuleTitle = false;
1042 var $mRules = '';// string : the text of the rules
1043 var $mRulesAction = 'none';
1044 var $mFlags = array();
1045 var $mVariantFlags = array();
1046 var $mConvTable = array();
1047 var $mBidtable = array();// array of the translation in each variant
1048 var $mUnidtable = array();// array of the translation in each variant
1049
1050 /**
1051 * Constructor
1052 *
1053 * @param $text String: the text between -{ and }-
1054 * @param $converter LanguageConverter object
1055 */
1056 public function __construct( $text, $converter ) {
1057 $this->mText = $text;
1058 $this->mConverter = $converter;
1059 }
1060
1061 /**
1062 * Check if variants array in convert array.
1063 *
1064 * @param $variants Array or string: variant language code
1065 * @return String: translated text
1066 */
1067 public function getTextInBidtable( $variants ) {
1068 $variants = (array)$variants;
1069 if ( !$variants ) {
1070 return false;
1071 }
1072 foreach ( $variants as $variant ) {
1073 if ( isset( $this->mBidtable[$variant] ) ) {
1074 return $this->mBidtable[$variant];
1075 }
1076 }
1077 return false;
1078 }
1079
1080 /**
1081 * Parse flags with syntax -{FLAG| ... }-
1082 * @private
1083 */
1084 function parseFlags() {
1085 $text = $this->mText;
1086 $flags = array();
1087 $variantFlags = array();
1088
1089 $sepPos = strpos( $text, '|' );
1090 if ( $sepPos !== false ) {
1091 $validFlags = $this->mConverter->mFlags;
1092 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1093 foreach ( $f as $ff ) {
1094 $ff = trim( $ff );
1095 if ( isset( $validFlags[$ff] ) ) {
1096 $flags[$validFlags[$ff]] = true;
1097 }
1098 }
1099 $text = strval( substr( $text, $sepPos + 1 ) );
1100 }
1101
1102 if ( !$flags ) {
1103 $flags['S'] = true;
1104 } elseif ( isset( $flags['R'] ) ) {
1105 $flags = array( 'R' => true );// remove other flags
1106 } elseif ( isset( $flags['N'] ) ) {
1107 $flags = array( 'N' => true );// remove other flags
1108 } elseif ( isset( $flags['-'] ) ) {
1109 $flags = array( '-' => true );// remove other flags
1110 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1111 $flags['H'] = true;
1112 } elseif ( isset( $flags['H'] ) ) {
1113 // replace A flag, and remove other flags except T
1114 $temp = array( '+' => true, 'H' => true );
1115 if ( isset( $flags['T'] ) ) {
1116 $temp['T'] = true;
1117 }
1118 if ( isset( $flags['D'] ) ) {
1119 $temp['D'] = true;
1120 }
1121 $flags = $temp;
1122 } else {
1123 if ( isset( $flags['A'] ) ) {
1124 $flags['+'] = true;
1125 $flags['S'] = true;
1126 }
1127 if ( isset( $flags['D'] ) ) {
1128 unset( $flags['S'] );
1129 }
1130 // try to find flags like "zh-hans", "zh-hant"
1131 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1132 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1133 if ( $variantFlags ) {
1134 $variantFlags = array_flip( $variantFlags );
1135 $flags = array();
1136 }
1137 }
1138 $this->mVariantFlags = $variantFlags;
1139 $this->mRules = $text;
1140 $this->mFlags = $flags;
1141 }
1142
1143 /**
1144 * Generate conversion table.
1145 * @private
1146 */
1147 function parseRules() {
1148 $rules = $this->mRules;
1149 $bidtable = array();
1150 $unidtable = array();
1151 $variants = $this->mConverter->mVariants;
1152 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1153
1154 $choice = preg_split( $varsep_pattern, $rules );
1155
1156 foreach ( $choice as $c ) {
1157 $v = explode( ':', $c, 2 );
1158 if ( count( $v ) != 2 ) {
1159 // syntax error, skip
1160 continue;
1161 }
1162 $to = trim( $v[1] );
1163 $v = trim( $v[0] );
1164 $u = explode( '=>', $v, 2 );
1165 // if $to is empty, strtr() could return a wrong result
1166 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1167 $bidtable[$v] = $to;
1168 } elseif ( count( $u ) == 2 ) {
1169 $from = trim( $u[0] );
1170 $v = trim( $u[1] );
1171 if ( array_key_exists( $v, $unidtable )
1172 && !is_array( $unidtable[$v] )
1173 && $to
1174 && in_array( $v, $variants ) ) {
1175 $unidtable[$v] = array( $from => $to );
1176 } elseif ( $to && in_array( $v, $variants ) ) {
1177 $unidtable[$v][$from] = $to;
1178 }
1179 }
1180 // syntax error, pass
1181 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1182 $bidtable = array();
1183 $unidtable = array();
1184 break;
1185 }
1186 }
1187 $this->mBidtable = $bidtable;
1188 $this->mUnidtable = $unidtable;
1189 }
1190
1191 /**
1192 * @private
1193 */
1194 function getRulesDesc() {
1195 $codesep = $this->mConverter->mDescCodeSep;
1196 $varsep = $this->mConverter->mDescVarSep;
1197 $text = '';
1198 foreach ( $this->mBidtable as $k => $v ) {
1199 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1200 }
1201 foreach ( $this->mUnidtable as $k => $a ) {
1202 foreach ( $a as $from => $to ) {
1203 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1204 "$codesep$to$varsep";
1205 }
1206 }
1207 return $text;
1208 }
1209
1210 /**
1211 * Parse rules conversion.
1212 * @private
1213 */
1214 function getRuleConvertedStr( $variant ) {
1215 $bidtable = $this->mBidtable;
1216 $unidtable = $this->mUnidtable;
1217
1218 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1219 return $this->mRules;
1220 } else {
1221 // display current variant in bidirectional array
1222 $disp = $this->getTextInBidtable( $variant );
1223 // or display current variant in fallbacks
1224 if ( !$disp ) {
1225 $disp = $this->getTextInBidtable(
1226 $this->mConverter->getVariantFallbacks( $variant ) );
1227 }
1228 // or display current variant in unidirectional array
1229 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1230 $disp = array_values( $unidtable[$variant] );
1231 $disp = $disp[0];
1232 }
1233 // or display frist text under disable manual convert
1234 if ( !$disp
1235 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1236 if ( count( $bidtable ) > 0 ) {
1237 $disp = array_values( $bidtable );
1238 $disp = $disp[0];
1239 } else {
1240 $disp = array_values( $unidtable );
1241 $disp = array_values( $disp[0] );
1242 $disp = $disp[0];
1243 }
1244 }
1245 return $disp;
1246 }
1247 }
1248
1249 /**
1250 * Generate conversion table for all text.
1251 * @private
1252 */
1253 function generateConvTable() {
1254 // Special case optimisation
1255 if ( !$this->mBidtable && !$this->mUnidtable ) {
1256 $this->mConvTable = array();
1257 return;
1258 }
1259
1260 $bidtable = $this->mBidtable;
1261 $unidtable = $this->mUnidtable;
1262 $manLevel = $this->mConverter->mManualLevel;
1263
1264 $vmarked = array();
1265 foreach ( $this->mConverter->mVariants as $v ) {
1266 /* for bidirectional array
1267 fill in the missing variants, if any,
1268 with fallbacks */
1269 if ( !isset( $bidtable[$v] ) ) {
1270 $variantFallbacks =
1271 $this->mConverter->getVariantFallbacks( $v );
1272 $vf = $this->getTextInBidtable( $variantFallbacks );
1273 if ( $vf ) {
1274 $bidtable[$v] = $vf;
1275 }
1276 }
1277
1278 if ( isset( $bidtable[$v] ) ) {
1279 foreach ( $vmarked as $vo ) {
1280 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1281 // or -{H|zh:WordZh;zh-tw:WordTw}-
1282 // or -{-|zh:WordZh;zh-tw:WordTw}-
1283 // to introduce a custom mapping between
1284 // words WordZh and WordTw in the whole text
1285 if ( $manLevel[$v] == 'bidirectional' ) {
1286 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1287 }
1288 if ( $manLevel[$vo] == 'bidirectional' ) {
1289 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1290 }
1291 }
1292 $vmarked[] = $v;
1293 }
1294 /*for unidirectional array fill to convert tables */
1295 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1296 && isset( $unidtable[$v] ) )
1297 {
1298 if ( isset( $this->mConvTable[$v] ) ) {
1299 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1300 } else {
1301 $this->mConvTable[$v] = $unidtable[$v];
1302 }
1303 }
1304 }
1305 }
1306
1307 /**
1308 * Parse rules and flags.
1309 * @public
1310 */
1311 function parse( $variant = NULL ) {
1312 if ( !$variant ) {
1313 $variant = $this->mConverter->getPreferredVariant();
1314 }
1315
1316 $this->parseFlags();
1317 $flags = $this->mFlags;
1318
1319 // convert to specified variant
1320 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1321 if ( $this->mVariantFlags ) {
1322 // check if current variant in flags
1323 if ( isset( $this->mVariantFlags[$variant] ) ) {
1324 // then convert <text to convert> to current language
1325 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1326 $variant );
1327 } else { // if current variant no in flags,
1328 // then we check its fallback variants.
1329 $variantFallbacks =
1330 $this->mConverter->getVariantFallbacks( $variant );
1331 foreach ( $variantFallbacks as $variantFallback ) {
1332 // if current variant's fallback exist in flags
1333 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1334 // then convert <text to convert> to fallback language
1335 $this->mRules =
1336 $this->mConverter->autoConvert( $this->mRules,
1337 $variantFallback );
1338 break;
1339 }
1340 }
1341 }
1342 $this->mFlags = $flags = array( 'R' => true );
1343 }
1344
1345 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1346 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1347 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1348 $this->parseRules();
1349 }
1350 $rules = $this->mRules;
1351
1352 if ( !$this->mBidtable && !$this->mUnidtable ) {
1353 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1354 // fill all variants if text in -{A/H/-|text} without rules
1355 foreach ( $this->mConverter->mVariants as $v ) {
1356 $this->mBidtable[$v] = $rules;
1357 }
1358 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1359 $this->mFlags = $flags = array( 'R' => true );
1360 }
1361 }
1362
1363 $this->mRuleDisplay = false;
1364 foreach ( $flags as $flag => $unused ) {
1365 switch ( $flag ) {
1366 case 'R':
1367 // if we don't do content convert, still strip the -{}- tags
1368 $this->mRuleDisplay = $rules;
1369 break;
1370 case 'N':
1371 // process N flag: output current variant name
1372 $ruleVar = trim( $rules );
1373 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1374 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1375 } else {
1376 $this->mRuleDisplay = '';
1377 }
1378 break;
1379 case 'D':
1380 // process D flag: output rules description
1381 $this->mRuleDisplay = $this->getRulesDesc();
1382 break;
1383 case 'H':
1384 // process H,- flag or T only: output nothing
1385 $this->mRuleDisplay = '';
1386 break;
1387 case '-':
1388 $this->mRulesAction = 'remove';
1389 $this->mRuleDisplay = '';
1390 break;
1391 case '+':
1392 $this->mRulesAction = 'add';
1393 $this->mRuleDisplay = '';
1394 break;
1395 case 'S':
1396 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1397 break;
1398 case 'T':
1399 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1400 $this->mRuleDisplay = '';
1401 break;
1402 default:
1403 // ignore unknown flags (but see error case below)
1404 }
1405 }
1406 if ( $this->mRuleDisplay === false ) {
1407 $this->mRuleDisplay = $this->mManualCodeError;
1408 }
1409
1410 $this->generateConvTable();
1411 }
1412
1413 /**
1414 * @public
1415 */
1416 function hasRules() {
1417 // TODO:
1418 }
1419
1420 /**
1421 * Get display text on markup -{...}-
1422 * @public
1423 */
1424 function getDisplay() {
1425 return $this->mRuleDisplay;
1426 }
1427
1428 /**
1429 * Get converted title.
1430 * @public
1431 */
1432 function getTitle() {
1433 return $this->mRuleTitle;
1434 }
1435
1436 /**
1437 * Return how deal with conversion rules.
1438 * @public
1439 */
1440 function getRulesAction() {
1441 return $this->mRulesAction;
1442 }
1443
1444 /**
1445 * Get conversion table. ( bidirectional and unidirectional
1446 * conversion table )
1447 * @public
1448 */
1449 function getConvTable() {
1450 return $this->mConvTable;
1451 }
1452
1453 /**
1454 * Get conversion rules string.
1455 * @public
1456 */
1457 function getRules() {
1458 return $this->mRules;
1459 }
1460
1461 /**
1462 * Get conversion flags.
1463 * @public
1464 */
1465 function getFlags() {
1466 return $this->mFlags;
1467 }
1468 }