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