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