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