Merge "Check result of preg_match_all in Parser.php"
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Language
20 */
21
22 /**
23 * Base class for language conversion.
24 * @ingroup Language
25 *
26 * @author Zhengzhu Feng <zhengzhu@gmail.com>
27 * @author fdcn <fdcn64@gmail.com>
28 * @author shinjiman <shinjiman@gmail.com>
29 * @author PhiLiP <philip.npc@gmail.com>
30 */
31 class LanguageConverter {
32 /**
33 * languages supporting variants
34 * @since 1.20
35 * @var array
36 */
37 static public $languagesWithVariants = array(
38 'gan',
39 'iu',
40 'kk',
41 'ku',
42 'shi',
43 'sr',
44 'tg',
45 'uz',
46 'zh',
47 );
48
49 public $mMainLanguageCode;
50 public $mVariants, $mVariantFallbacks, $mVariantNames;
51 public $mTablesLoaded = false;
52 public $mTables;
53 // 'bidirectional' 'unidirectional' 'disable' for each variant
54 public $mManualLevel;
55
56 /**
57 * @var string Memcached key name
58 */
59 public $mCacheKey;
60
61 public $mLangObj;
62 public $mFlags;
63 public $mDescCodeSep = ':', $mDescVarSep = ';';
64 public $mUcfirst = false;
65 public $mConvRuleTitle = false;
66 public $mURLVariant;
67 public $mUserVariant;
68 public $mHeaderVariant;
69 public $mMaxDepth = 10;
70 public $mVarSeparatorPattern;
71
72 const CACHE_VERSION_KEY = 'VERSION 7';
73
74 /**
75 * Constructor
76 *
77 * @param Language $langobj
78 * @param string $maincode The main language code of this language
79 * @param array $variants The supported variants of this language
80 * @param array $variantfallbacks The fallback language of each variant
81 * @param array $flags Defining the custom strings that maps to the flags
82 * @param array $manualLevel Limit for supported variants
83 */
84 public function __construct( $langobj, $maincode, $variants = array(),
85 $variantfallbacks = array(), $flags = array(),
86 $manualLevel = array() ) {
87 global $wgDisabledVariants;
88 $this->mLangObj = $langobj;
89 $this->mMainLanguageCode = $maincode;
90 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
91 $this->mVariantFallbacks = $variantfallbacks;
92 $this->mVariantNames = Language::fetchLanguageNames();
93 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
94 $defaultflags = array(
95 // 'S' show converted text
96 // '+' add rules for alltext
97 // 'E' the gave flags is error
98 // these flags above are reserved for program
99 'A' => 'A', // add rule for convert code (all text convert)
100 'T' => 'T', // title convert
101 'R' => 'R', // raw content
102 'D' => 'D', // convert description (subclass implement)
103 '-' => '-', // remove convert (not implement)
104 'H' => 'H', // add rule for convert code (but no display in placed code)
105 'N' => 'N' // current variant name
106 );
107 $this->mFlags = array_merge( $defaultflags, $flags );
108 foreach ( $this->mVariants as $v ) {
109 if ( array_key_exists( $v, $manualLevel ) ) {
110 $this->mManualLevel[$v] = $manualLevel[$v];
111 } else {
112 $this->mManualLevel[$v] = 'bidirectional';
113 }
114 $this->mFlags[$v] = $v;
115 }
116 }
117
118 /**
119 * Get all valid variants.
120 * Call this instead of using $this->mVariants directly.
121 *
122 * @return array Contains all valid variants
123 */
124 public function getVariants() {
125 return $this->mVariants;
126 }
127
128 /**
129 * In case some variant is not defined in the markup, we need
130 * to have some fallback. For example, in zh, normally people
131 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
132 * when zh-sg is preferred but not defined, we will pick zh-hans
133 * in this case. Right now this is only used by zh.
134 *
135 * @param string $variant The language code of the variant
136 * @return string|array The code of the fallback language or the
137 * main code if there is no fallback
138 */
139 public function getVariantFallbacks( $variant ) {
140 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
141 return $this->mVariantFallbacks[$variant];
142 }
143 return $this->mMainLanguageCode;
144 }
145
146 /**
147 * Get the title produced by the conversion rule.
148 * @return string The converted title text
149 */
150 public function getConvRuleTitle() {
151 return $this->mConvRuleTitle;
152 }
153
154 /**
155 * Get preferred language variant.
156 * @return string The preferred language code
157 */
158 public function getPreferredVariant() {
159 global $wgDefaultLanguageVariant, $wgUser;
160
161 $req = $this->getURLVariant();
162
163 if ( $wgUser->isLoggedIn() && !$req ) {
164 $req = $this->getUserVariant();
165 } elseif ( !$req ) {
166 $req = $this->getHeaderVariant();
167 }
168
169 if ( $wgDefaultLanguageVariant && !$req ) {
170 $req = $this->validateVariant( $wgDefaultLanguageVariant );
171 }
172
173 // This function, unlike the other get*Variant functions, is
174 // not memoized (i.e. there return value is not cached) since
175 // new information might appear during processing after this
176 // is first called.
177 if ( $this->validateVariant( $req ) ) {
178 return $req;
179 }
180 return $this->mMainLanguageCode;
181 }
182
183 /**
184 * Get default variant.
185 * This function would not be affected by user's settings
186 * @return string The default variant code
187 */
188 public function getDefaultVariant() {
189 global $wgDefaultLanguageVariant;
190
191 $req = $this->getURLVariant();
192
193 if ( !$req ) {
194 $req = $this->getHeaderVariant();
195 }
196
197 if ( $wgDefaultLanguageVariant && !$req ) {
198 $req = $this->validateVariant( $wgDefaultLanguageVariant );
199 }
200
201 if ( $req ) {
202 return $req;
203 }
204 return $this->mMainLanguageCode;
205 }
206
207 /**
208 * Validate the variant
209 * @param string $variant The variant to validate
210 * @return mixed Returns the variant if it is valid, null otherwise
211 */
212 public function validateVariant( $variant = null ) {
213 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
214 return $variant;
215 }
216 return null;
217 }
218
219 /**
220 * Get the variant specified in the URL
221 *
222 * @return mixed Variant if one found, false otherwise.
223 */
224 public function getURLVariant() {
225 global $wgRequest;
226
227 if ( $this->mURLVariant ) {
228 return $this->mURLVariant;
229 }
230
231 // see if the preference is set in the request
232 $ret = $wgRequest->getText( 'variant' );
233
234 if ( !$ret ) {
235 $ret = $wgRequest->getVal( 'uselang' );
236 }
237
238 $this->mURLVariant = $this->validateVariant( $ret );
239 return $this->mURLVariant;
240 }
241
242 /**
243 * Determine if the user has a variant set.
244 *
245 * @return mixed Variant if one found, false otherwise.
246 */
247 protected function getUserVariant() {
248 global $wgUser, $wgContLang;
249
250 // memoizing this function wreaks havoc on parserTest.php
251 /*
252 if ( $this->mUserVariant ) {
253 return $this->mUserVariant;
254 }
255 */
256
257 // Get language variant preference from logged in users
258 // Don't call this on stub objects because that causes infinite
259 // recursion during initialisation
260 if ( $wgUser->isLoggedIn() ) {
261 if ( $this->mMainLanguageCode == $wgContLang->getCode() ) {
262 $ret = $wgUser->getOption( 'variant' );
263 } else {
264 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode );
265 }
266 } else {
267 // figure out user lang without constructing wgLang to avoid
268 // infinite recursion
269 $ret = $wgUser->getOption( 'language' );
270 }
271
272 $this->mUserVariant = $this->validateVariant( $ret );
273 return $this->mUserVariant;
274 }
275
276 /**
277 * Determine the language variant from the Accept-Language header.
278 *
279 * @return mixed Variant if one found, false otherwise.
280 */
281 protected function getHeaderVariant() {
282 global $wgRequest;
283
284 if ( $this->mHeaderVariant ) {
285 return $this->mHeaderVariant;
286 }
287
288 // see if some supported language variant is set in the
289 // HTTP header.
290 $languages = array_keys( $wgRequest->getAcceptLang() );
291 if ( empty( $languages ) ) {
292 return null;
293 }
294
295 $fallbackLanguages = array();
296 foreach ( $languages as $language ) {
297 $this->mHeaderVariant = $this->validateVariant( $language );
298 if ( $this->mHeaderVariant ) {
299 break;
300 }
301
302 // To see if there are fallbacks of current language.
303 // We record these fallback variants, and process
304 // them later.
305 $fallbacks = $this->getVariantFallbacks( $language );
306 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
307 $fallbackLanguages[] = $fallbacks;
308 } elseif ( is_array( $fallbacks ) ) {
309 $fallbackLanguages =
310 array_merge( $fallbackLanguages, $fallbacks );
311 }
312 }
313
314 if ( !$this->mHeaderVariant ) {
315 // process fallback languages now
316 $fallback_languages = array_unique( $fallbackLanguages );
317 foreach ( $fallback_languages as $language ) {
318 $this->mHeaderVariant = $this->validateVariant( $language );
319 if ( $this->mHeaderVariant ) {
320 break;
321 }
322 }
323 }
324
325 return $this->mHeaderVariant;
326 }
327
328 /**
329 * Dictionary-based conversion.
330 * This function would not parse the conversion rules.
331 * If you want to parse rules, try to use convert() or
332 * convertTo().
333 *
334 * @param string $text The text to be converted
335 * @param bool|string $toVariant The target language code
336 * @return string The converted text
337 */
338 public function autoConvert( $text, $toVariant = false ) {
339
340 $this->loadTables();
341
342 if ( !$toVariant ) {
343 $toVariant = $this->getPreferredVariant();
344 if ( !$toVariant ) {
345 return $text;
346 }
347 }
348
349 if ( $this->guessVariant( $text, $toVariant ) ) {
350 return $text;
351 }
352
353 /* we convert everything except:
354 1. HTML markups (anything between < and >)
355 2. HTML entities
356 3. placeholders created by the parser
357 */
358 $marker = '|' . Parser::MARKER_PREFIX . '[\-a-zA-Z0-9]+';
359
360 // this one is needed when the text is inside an HTML markup
361 $htmlfix = '|<[^>]+$|^[^<>]*>';
362
363 // disable convert to variants between <code> tags
364 $codefix = '<code>.+?<\/code>|';
365 // disable conversion of <script> tags
366 $scriptfix = '<script.*?>.*?<\/script>|';
367 // disable conversion of <pre> tags
368 $prefix = '<pre.*?>.*?<\/pre>|';
369
370 $reg = '/' . $codefix . $scriptfix . $prefix .
371 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
372 $startPos = 0;
373 $sourceBlob = '';
374 $literalBlob = '';
375
376 // Guard against delimiter nulls in the input
377 $text = str_replace( "\000", '', $text );
378
379 $markupMatches = null;
380 $elementMatches = null;
381 while ( $startPos < strlen( $text ) ) {
382 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
383 $elementPos = $markupMatches[0][1];
384 $element = $markupMatches[0][0];
385 } else {
386 $elementPos = strlen( $text );
387 $element = '';
388 }
389
390 // Queue the part before the markup for translation in a batch
391 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
392
393 // Advance to the next position
394 $startPos = $elementPos + strlen( $element );
395
396 // Translate any alt or title attributes inside the matched element
397 if ( $element !== ''
398 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
399 ) {
400 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
401 $changed = false;
402 foreach ( array( 'title', 'alt' ) as $attrName ) {
403 if ( !isset( $attrs[$attrName] ) ) {
404 continue;
405 }
406 $attr = $attrs[$attrName];
407 // Don't convert URLs
408 if ( !strpos( $attr, '://' ) ) {
409 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
410 }
411
412 // Remove HTML tags to avoid disrupting the layout
413 $attr = preg_replace( '/<[^>]+>/', '', $attr );
414 if ( $attr !== $attrs[$attrName] ) {
415 $attrs[$attrName] = $attr;
416 $changed = true;
417 }
418 }
419 if ( $changed ) {
420 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
421 $elementMatches[3];
422 }
423 }
424 $literalBlob .= $element . "\000";
425 }
426
427 // Do the main translation batch
428 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
429
430 // Put the output back together
431 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
432 $literalIter = StringUtils::explode( "\000", $literalBlob );
433 $output = '';
434 while ( $translatedIter->valid() && $literalIter->valid() ) {
435 $output .= $translatedIter->current();
436 $output .= $literalIter->current();
437 $translatedIter->next();
438 $literalIter->next();
439 }
440
441 return $output;
442 }
443
444 /**
445 * Translate a string to a variant.
446 * Doesn't parse rules or do any of that other stuff, for that use
447 * convert() or convertTo().
448 *
449 * @param string $text Text to convert
450 * @param string $variant Variant language code
451 * @return string Translated text
452 */
453 public function translate( $text, $variant ) {
454 // If $text is empty or only includes spaces, do nothing
455 // Otherwise translate it
456 if ( trim( $text ) ) {
457 $this->loadTables();
458 $text = $this->mTables[$variant]->replace( $text );
459 }
460 return $text;
461 }
462
463 /**
464 * Call translate() to convert text to all valid variants.
465 *
466 * @param string $text The text to be converted
467 * @return array Variant => converted text
468 */
469 public function autoConvertToAllVariants( $text ) {
470 $this->loadTables();
471
472 $ret = array();
473 foreach ( $this->mVariants as $variant ) {
474 $ret[$variant] = $this->translate( $text, $variant );
475 }
476
477 return $ret;
478 }
479
480 /**
481 * Apply manual conversion rules.
482 *
483 * @param ConverterRule $convRule
484 */
485 protected function applyManualConv( $convRule ) {
486 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
487 // title conversion.
488 // Bug 24072: $mConvRuleTitle was overwritten by other manual
489 // rule(s) not for title, this breaks the title conversion.
490 $newConvRuleTitle = $convRule->getTitle();
491 if ( $newConvRuleTitle ) {
492 // So I add an empty check for getTitle()
493 $this->mConvRuleTitle = $newConvRuleTitle;
494 }
495
496 // merge/remove manual conversion rules to/from global table
497 $convTable = $convRule->getConvTable();
498 $action = $convRule->getRulesAction();
499 foreach ( $convTable as $variant => $pair ) {
500 if ( !$this->validateVariant( $variant ) ) {
501 continue;
502 }
503
504 if ( $action == 'add' ) {
505 foreach ( $pair as $from => $to ) {
506 // to ensure that $from and $to not be left blank
507 // so $this->translate() could always return a string
508 if ( $from || $to ) {
509 // more efficient than array_merge(), about 2.5 times.
510 $this->mTables[$variant]->setPair( $from, $to );
511 }
512 }
513 } elseif ( $action == 'remove' ) {
514 $this->mTables[$variant]->removeArray( $pair );
515 }
516 }
517 }
518
519 /**
520 * Auto convert a Title object to a readable string in the
521 * preferred variant.
522 *
523 * @param Title $title A object of Title
524 * @return string Converted title text
525 */
526 public function convertTitle( $title ) {
527 $variant = $this->getPreferredVariant();
528 $index = $title->getNamespace();
529 if ( $index !== NS_MAIN ) {
530 $text = $this->convertNamespace( $index, $variant ) . ':';
531 } else {
532 $text = '';
533 }
534 $text .= $this->translate( $title->getText(), $variant );
535 return $text;
536 }
537
538 /**
539 * Get the namespace display name in the preferred variant.
540 *
541 * @param int $index Namespace id
542 * @param string|null $variant Variant code or null for preferred variant
543 * @return string Namespace name for display
544 */
545 public function convertNamespace( $index, $variant = null ) {
546 if ( $variant === null ) {
547 $variant = $this->getPreferredVariant();
548 }
549 if ( $index === NS_MAIN ) {
550 return '';
551 } else {
552 // First check if a message gives a converted name in the target variant.
553 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
554 if ( $nsConvMsg->exists() ) {
555 return $nsConvMsg->plain();
556 }
557 // Then check if a message gives a converted name in content language
558 // which needs extra translation to the target variant.
559 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
560 if ( $nsConvMsg->exists() ) {
561 return $this->translate( $nsConvMsg->plain(), $variant );
562 }
563 // No message exists, retrieve it from the target variant's namespace names.
564 $langObj = $this->mLangObj->factory( $variant );
565 return $langObj->getFormattedNsText( $index );
566 }
567 }
568
569 /**
570 * Convert text to different variants of a language. The automatic
571 * conversion is done in autoConvert(). Here we parse the text
572 * marked with -{}-, which specifies special conversions of the
573 * text that can not be accomplished in autoConvert().
574 *
575 * Syntax of the markup:
576 * -{code1:text1;code2:text2;...}- or
577 * -{flags|code1:text1;code2:text2;...}- or
578 * -{text}- in which case no conversion should take place for text
579 *
580 * @param string $text Text to be converted
581 * @return string Converted text
582 */
583 public function convert( $text ) {
584 $variant = $this->getPreferredVariant();
585 return $this->convertTo( $text, $variant );
586 }
587
588 /**
589 * Same as convert() except a extra parameter to custom variant.
590 *
591 * @param string $text Text to be converted
592 * @param string $variant The target variant code
593 * @return string Converted text
594 */
595 public function convertTo( $text, $variant ) {
596 global $wgDisableLangConversion;
597 if ( $wgDisableLangConversion ) {
598 return $text;
599 }
600 // Reset converter state for a new converter run.
601 $this->mConvRuleTitle = false;
602 return $this->recursiveConvertTopLevel( $text, $variant );
603 }
604
605 /**
606 * Recursively convert text on the outside. Allow to use nested
607 * markups to custom rules.
608 *
609 * @param string $text Text to be converted
610 * @param string $variant The target variant code
611 * @param int $depth Depth of recursion
612 * @return string Converted text
613 */
614 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
615 $startPos = 0;
616 $out = '';
617 $length = strlen( $text );
618 $shouldConvert = !$this->guessVariant( $text, $variant );
619
620 while ( $startPos < $length ) {
621 $pos = strpos( $text, '-{', $startPos );
622
623 if ( $pos === false ) {
624 // No more markup, append final segment
625 $fragment = substr( $text, $startPos );
626 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
627 return $out;
628 }
629
630 // Markup found
631 // Append initial segment
632 $fragment = substr( $text, $startPos, $pos - $startPos );
633 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
634
635 // Advance position
636 $startPos = $pos;
637
638 // Do recursive conversion
639 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
640 }
641
642 return $out;
643 }
644
645 /**
646 * Recursively convert text on the inside.
647 *
648 * @param string $text Text to be converted
649 * @param string $variant The target variant code
650 * @param int $startPos
651 * @param int $depth Depth of recursion
652 *
653 * @throws MWException
654 * @return string Converted text
655 */
656 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
657 // Quick sanity check (no function calls)
658 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
659 throw new MWException( __METHOD__ . ': invalid input string' );
660 }
661
662 $startPos += 2;
663 $inner = '';
664 $warningDone = false;
665 $length = strlen( $text );
666
667 while ( $startPos < $length ) {
668 $m = false;
669 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
670 if ( !$m ) {
671 // Unclosed rule
672 break;
673 }
674
675 $token = $m[0][0];
676 $pos = $m[0][1];
677
678 // Markup found
679 // Append initial segment
680 $inner .= substr( $text, $startPos, $pos - $startPos );
681
682 // Advance position
683 $startPos = $pos;
684
685 switch ( $token ) {
686 case '-{':
687 // Check max depth
688 if ( $depth >= $this->mMaxDepth ) {
689 $inner .= '-{';
690 if ( !$warningDone ) {
691 $inner .= '<span class="error">' .
692 wfMessage( 'language-converter-depth-warning' )
693 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
694 '</span>';
695 $warningDone = true;
696 }
697 $startPos += 2;
698 continue;
699 }
700 // Recursively parse another rule
701 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
702 break;
703 case '}-':
704 // Apply the rule
705 $startPos += 2;
706 $rule = new ConverterRule( $inner, $this );
707 $rule->parse( $variant );
708 $this->applyManualConv( $rule );
709 return $rule->getDisplay();
710 default:
711 throw new MWException( __METHOD__ . ': invalid regex match' );
712 }
713 }
714
715 // Unclosed rule
716 if ( $startPos < $length ) {
717 $inner .= substr( $text, $startPos );
718 }
719 $startPos = $length;
720 return '-{' . $this->autoConvert( $inner, $variant );
721 }
722
723 /**
724 * If a language supports multiple variants, it is possible that
725 * non-existing link in one variant actually exists in another variant.
726 * This function tries to find it. See e.g. LanguageZh.php
727 * The input parameters may be modified upon return
728 *
729 * @param string &$link The name of the link
730 * @param Title &$nt The title object of the link
731 * @param bool $ignoreOtherCond To disable other conditions when
732 * we need to transclude a template or update a category's link
733 */
734 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
735 # If the article has already existed, there is no need to
736 # check it again, otherwise it may cause a fault.
737 if ( is_object( $nt ) && $nt->exists() ) {
738 return;
739 }
740
741 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
742 $isredir = $wgRequest->getText( 'redirect', 'yes' );
743 $action = $wgRequest->getText( 'action' );
744 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
745 $action = 'view';
746 }
747 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
748 $disableLinkConversion = $wgDisableLangConversion
749 || $wgDisableTitleConversion;
750 $linkBatch = new LinkBatch();
751
752 $ns = NS_MAIN;
753
754 if ( $disableLinkConversion ||
755 ( !$ignoreOtherCond &&
756 ( $isredir == 'no'
757 || $action == 'edit'
758 || $action == 'submit'
759 || $linkconvert == 'no' ) ) ) {
760 return;
761 }
762
763 if ( is_object( $nt ) ) {
764 $ns = $nt->getNamespace();
765 }
766
767 $variants = $this->autoConvertToAllVariants( $link );
768 if ( !$variants ) { // give up
769 return;
770 }
771
772 $titles = array();
773
774 foreach ( $variants as $v ) {
775 if ( $v != $link ) {
776 $varnt = Title::newFromText( $v, $ns );
777 if ( !is_null( $varnt ) ) {
778 $linkBatch->addObj( $varnt );
779 $titles[] = $varnt;
780 }
781 }
782 }
783
784 // fetch all variants in single query
785 $linkBatch->execute();
786
787 foreach ( $titles as $varnt ) {
788 if ( $varnt->getArticleID() > 0 ) {
789 $nt = $varnt;
790 $link = $varnt->getText();
791 break;
792 }
793 }
794 }
795
796 /**
797 * Returns language specific hash options.
798 *
799 * @return string
800 */
801 public function getExtraHashOptions() {
802 $variant = $this->getPreferredVariant();
803
804 return '!' . $variant;
805 }
806
807 /**
808 * Guess if a text is written in a variant. This should be implemented in subclasses.
809 *
810 * @param string $text The text to be checked
811 * @param string $variant Language code of the variant to be checked for
812 * @return bool True if $text appears to be written in $variant, false if not
813 *
814 * @author Nikola Smolenski <smolensk@eunet.rs>
815 * @since 1.19
816 */
817 public function guessVariant( $text, $variant ) {
818 return false;
819 }
820
821 /**
822 * Load default conversion tables.
823 * This method must be implemented in derived class.
824 *
825 * @private
826 * @throws MWException
827 */
828 function loadDefaultTables() {
829 $name = get_class( $this );
830
831 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
832 }
833
834 /**
835 * Load conversion tables either from the cache or the disk.
836 * @private
837 * @param bool $fromCache Load from memcached? Defaults to true.
838 */
839 function loadTables( $fromCache = true ) {
840 global $wgLanguageConverterCacheType;
841
842 if ( $this->mTablesLoaded ) {
843 return;
844 }
845
846 $this->mTablesLoaded = true;
847 $this->mTables = false;
848 $cache = ObjectCache::getInstance( $wgLanguageConverterCacheType );
849 if ( $fromCache ) {
850 wfProfileIn( __METHOD__ . '-cache' );
851 $this->mTables = $cache->get( $this->mCacheKey );
852 wfProfileOut( __METHOD__ . '-cache' );
853 }
854 if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
855 wfProfileIn( __METHOD__ . '-recache' );
856 // not in cache, or we need a fresh reload.
857 // We will first load the default tables
858 // then update them using things in MediaWiki:Conversiontable/*
859 $this->loadDefaultTables();
860 foreach ( $this->mVariants as $var ) {
861 $cached = $this->parseCachedTable( $var );
862 $this->mTables[$var]->mergeArray( $cached );
863 }
864
865 $this->postLoadTables();
866 $this->mTables[self::CACHE_VERSION_KEY] = true;
867
868 $cache->set( $this->mCacheKey, $this->mTables, 43200 );
869 wfProfileOut( __METHOD__ . '-recache' );
870 }
871 }
872
873 /**
874 * Hook for post processing after conversion tables are loaded.
875 */
876 function postLoadTables() {
877 }
878
879 /**
880 * Reload the conversion tables.
881 *
882 * @private
883 */
884 function reloadTables() {
885 if ( $this->mTables ) {
886 unset( $this->mTables );
887 }
888
889 $this->mTablesLoaded = false;
890 $this->loadTables( false );
891 }
892
893 /**
894 * Parse the conversion table stored in the cache.
895 *
896 * The tables should be in blocks of the following form:
897 * -{
898 * word => word ;
899 * word => word ;
900 * ...
901 * }-
902 *
903 * To make the tables more manageable, subpages are allowed
904 * and will be parsed recursively if $recursive == true.
905 *
906 * @param string $code Language code
907 * @param string $subpage Subpage name
908 * @param bool $recursive Parse subpages recursively? Defaults to true.
909 *
910 * @return array
911 */
912 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
913 static $parsed = array();
914
915 $key = 'Conversiontable/' . $code;
916 if ( $subpage ) {
917 $key .= '/' . $subpage;
918 }
919 if ( array_key_exists( $key, $parsed ) ) {
920 return array();
921 }
922
923 $parsed[$key] = true;
924
925 if ( $subpage === '' ) {
926 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
927 } else {
928 $txt = false;
929 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
930 if ( $title && $title->exists() ) {
931 $revision = Revision::newFromTitle( $title );
932 if ( $revision ) {
933 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
934 $txt = $revision->getContent( Revision::RAW )->getNativeData();
935 }
936
937 // @todo in the future, use a specialized content model, perhaps based on json!
938 }
939 }
940 }
941
942 # Nothing to parse if there's no text
943 if ( $txt === false || $txt === null || $txt === '' ) {
944 return array();
945 }
946
947 // get all subpage links of the form
948 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
949 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
950 ':Conversiontable';
951 $subs = StringUtils::explode( '[[', $txt );
952 $sublinks = array();
953 foreach ( $subs as $sub ) {
954 $link = explode( ']]', $sub, 2 );
955 if ( count( $link ) != 2 ) {
956 continue;
957 }
958 $b = explode( '|', $link[0], 2 );
959 $b = explode( '/', trim( $b[0] ), 3 );
960 if ( count( $b ) == 3 ) {
961 $sublink = $b[2];
962 } else {
963 $sublink = '';
964 }
965
966 if ( $b[0] == $linkhead && $b[1] == $code ) {
967 $sublinks[] = $sublink;
968 }
969 }
970
971 // parse the mappings in this page
972 $blocks = StringUtils::explode( '-{', $txt );
973 $ret = array();
974 $first = true;
975 foreach ( $blocks as $block ) {
976 if ( $first ) {
977 // Skip the part before the first -{
978 $first = false;
979 continue;
980 }
981 $mappings = explode( '}-', $block, 2 );
982 $stripped = str_replace( array( "'", '"', '*', '#' ), '', $mappings[0] );
983 $table = StringUtils::explode( ';', $stripped );
984 foreach ( $table as $t ) {
985 $m = explode( '=>', $t, 3 );
986 if ( count( $m ) != 2 ) {
987 continue;
988 }
989 // trim any trailling comments starting with '//'
990 $tt = explode( '//', $m[1], 2 );
991 $ret[trim( $m[0] )] = trim( $tt[0] );
992 }
993 }
994
995 // recursively parse the subpages
996 if ( $recursive ) {
997 foreach ( $sublinks as $link ) {
998 $s = $this->parseCachedTable( $code, $link, $recursive );
999 $ret = array_merge( $ret, $s );
1000 }
1001 }
1002
1003 if ( $this->mUcfirst ) {
1004 foreach ( $ret as $k => $v ) {
1005 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1006 }
1007 }
1008 return $ret;
1009 }
1010
1011 /**
1012 * Enclose a string with the "no conversion" tag. This is used by
1013 * various functions in the Parser.
1014 *
1015 * @param string $text Text to be tagged for no conversion
1016 * @param bool $noParse Unused
1017 * @return string The tagged text
1018 */
1019 public function markNoConversion( $text, $noParse = false ) {
1020 # don't mark if already marked
1021 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1022 return $text;
1023 }
1024
1025 $ret = "-{R|$text}-";
1026 return $ret;
1027 }
1028
1029 /**
1030 * Convert the sorting key for category links. This should make different
1031 * keys that are variants of each other map to the same key.
1032 *
1033 * @param string $key
1034 *
1035 * @return string
1036 */
1037 function convertCategoryKey( $key ) {
1038 return $key;
1039 }
1040
1041 /**
1042 * Hook to refresh the cache of conversion tables when
1043 * MediaWiki:Conversiontable* is updated.
1044 * @private
1045 *
1046 * @param WikiPage $page
1047 * @param User $user User object for the current user
1048 * @param Content $content New page content
1049 * @param string $summary Edit summary of the edit
1050 * @param bool $isMinor Was the edit marked as minor?
1051 * @param null $isWatch Unused.
1052 * @param null $section Unused.
1053 * @param int $flags Bitfield
1054 * @param Revision|null $revision New Revision object or null
1055 * @return bool True
1056 */
1057 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1058 $isWatch, $section, $flags, $revision ) {
1059 $titleobj = $page->getTitle();
1060 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1061 $title = $titleobj->getDBkey();
1062 $t = explode( '/', $title, 3 );
1063 $c = count( $t );
1064 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1065 if ( $this->validateVariant( $t[1] ) ) {
1066 $this->reloadTables();
1067 }
1068 }
1069 }
1070 return true;
1071 }
1072
1073 /**
1074 * Armour rendered math against conversion.
1075 * Escape special chars in parsed math text. (in most cases are img elements)
1076 *
1077 * @param string $text Text to armour against conversion
1078 * @return string Armoured text where { and } have been converted to
1079 * &#123; and &#125;
1080 * @deprecated since 1.22 is no longer used
1081 */
1082 public function armourMath( $text ) {
1083 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
1084 // any unwanted markup appearing in the math image tag.
1085 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
1086 return $text;
1087 }
1088
1089 /**
1090 * Get the cached separator pattern for ConverterRule::parseRules()
1091 * @return string
1092 */
1093 function getVarSeparatorPattern() {
1094 if ( is_null( $this->mVarSeparatorPattern ) ) {
1095 // varsep_pattern for preg_split:
1096 // text should be splited by ";" only if a valid variant
1097 // name exist after the markup, for example:
1098 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1099 // <span style="font-size:120%;">yyy</span>;}-
1100 // we should split it as:
1101 // array(
1102 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1103 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1104 // [2] => ''
1105 // )
1106 $pat = '/;\s*(?=';
1107 foreach ( $this->mVariants as $variant ) {
1108 // zh-hans:xxx;zh-hant:yyy
1109 $pat .= $variant . '\s*:|';
1110 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1111 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1112 }
1113 $pat .= '\s*$)/';
1114 $this->mVarSeparatorPattern = $pat;
1115 }
1116 return $this->mVarSeparatorPattern;
1117 }
1118 }