4 * Contains the LanguageConverter class and ConverterRule class
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
12 * base class for language convert
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter
{
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mNamespaceTables;
25 var $mTitleDisplay='';
26 var $mDoTitleConvert=true, $mDoContentConvert=true;
27 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
28 var $mTitleFromFlag = false;
33 var $mDescCodeSep = ':',$mDescVarSep = ';';
34 var $mUcfirst = false;
36 const CACHE_VERSION_KEY
= 'VERSION 6';
41 * @param string $maincode the main language code of this language
42 * @param array $variants the supported variants of this language
43 * @param array $variantfallback the fallback language of each variant
44 * @param array $markup array defining the markup used for manual conversion
45 * @param array $flags array defining the custom strings that maps to the flags
46 * @param array $manualLevel limit for supported variants
49 function __construct( $langobj, $maincode,
51 $variantfallbacks=array(),
54 $manualLevel = array() ) {
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
58 global $wgDisabledVariants;
59 $this->mVariants
= array();
60 foreach( $variants as $variant ) {
61 if( !in_array( $variant, $wgDisabledVariants ) )
62 $this->mVariants
[] = $variant;
64 $this->mVariantFallbacks
= $variantfallbacks;
65 global $wgLanguageNames;
66 $this->mVariantNames
= $wgLanguageNames;
67 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
71 'unidsep'=>'=>', //for unidirectional conversion
76 $this->mMarkup
= array_merge($m, $markup);
78 // 'S' show converted text
79 // '+' add rules for alltext
80 // 'E' the gave flags is error
81 // these flags above are reserved for program
82 'A'=>'A', // add rule for convert code (all text convert)
83 'T'=>'T', // title convert
84 'R'=>'R', // raw content
85 'D'=>'D', // convert description (subclass implement)
86 '-'=>'-', // remove convert (not implement)
87 'H'=>'H', // add rule for convert code (but no display in placed code )
88 'N'=>'N' // current variant name
90 $this->mFlags
= array_merge($f, $flags);
91 foreach( $this->mVariants
as $v) {
92 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
95 $this->mNamespaceTables
[$v] = array();
96 $this->mFlags
[$v] = $v;
103 function getVariants() {
104 return $this->mVariants
;
108 * in case some variant is not defined in the markup, we need
109 * to have some fallback. for example, in zh, normally people
110 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
111 * when zh-sg is preferred but not defined, we will pick zh-hans
112 * in this case. right now this is only used by zh.
114 * @param string $v the language code of the variant
115 * @return string array the code of the fallback language or false if there is no fallback
118 function getVariantFallbacks($v) {
119 if( isset( $this->mVariantFallbacks
[$v] ) ) {
120 return $this->mVariantFallbacks
[$v];
122 return $this->mMainLanguageCode
;
126 * get preferred language variants.
127 * @param boolean $fromUser Get it from $wgUser's preferences
128 * @return string the preferred language code
131 function getPreferredVariant( $fromUser = true ) {
132 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
134 if($this->mPreferredVariant
)
135 return $this->mPreferredVariant
;
137 // figure out user lang without constructing wgLang to avoid infinite recursion
139 $defaultUserLang = $wgUser->getOption( 'language' );
141 $defaultUserLang = $this->mMainLanguageCode
;
142 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
143 // see if interface language is same as content, if not, prevent conversion
144 if( ! in_array( $userLang, $this->mVariants
) ){
145 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
146 return $this->mPreferredVariant
;
149 // see if the preference is set in the request
150 $req = $wgRequest->getText( 'variant' );
151 if( in_array( $req, $this->mVariants
) ) {
152 $this->mPreferredVariant
= $req;
156 // check the syntax /code/ArticleTitle
157 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
158 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
159 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
160 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
161 if(in_array($scriptBase,$this->mVariants
)){
162 $this->mPreferredVariant
= $scriptBase;
163 return $this->mPreferredVariant
;
167 // get language variant preference from logged in users
168 // Don't call this on stub objects because that causes infinite
169 // recursion during initialisation
170 if( $fromUser && $wgUser->isLoggedIn() ) {
171 $this->mPreferredVariant
= $wgUser->getOption('variant');
172 return $this->mPreferredVariant
;
175 // see if default variant is globaly set
176 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
177 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
178 return $this->mPreferredVariant
;
181 if( !$this->mPreferredVariant
) {
182 // see if some supported language variant is set in the
183 // http header, but we don't set the mPreferredVariant
184 // variable in case this is called before the user's
185 // preference is loaded
186 if( array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
187 $acceptLanguage = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
190 $result = explode(',', $acceptLanguage);
192 $languages = array();
194 foreach( $result as $elem ) {
195 // if $elem likes 'zh-cn;q=0.9'
196 if(($posi = strpos( $elem, ';' )) !== false ) {
197 // get the real language code likes 'zh-cn'
198 $languages[] = substr( $elem, 0, $posi );
201 $languages[] = $elem;
205 $fallback_languages = array();
206 foreach( $languages as $language ) {
208 $language = trim( $language );
209 if( in_array( $language, $this->mVariants
) ) {
213 // To see if there are fallbacks of current language.
214 // We record these fallback variants, and process
216 $fallbacks = $this->getVariantFallbacks( $language );
217 if( is_string( $fallbacks ) )
218 $fallback_languages[] = $fallbacks;
219 elseif( is_array( $fallbacks ) )
220 $fallback_languages = array_merge( $fallback_languages, $fallbacks );
224 // process fallback languages now
225 $fallback_languages = array_unique( $fallback_languages );
226 foreach( $fallback_languages as $language ) {
227 if( in_array( $language, $this->mVariants
) ) {
234 return $this->mMainLanguageCode
;
238 * caption convert, base on preg_replace_callback
240 * to convert text in "title" or "alt", like '<img alt="text" ... '
241 * or '<span title="text" ... '
243 * @return string like ' alt="yyyy"' or ' title="yyyy"'
246 function captionConvert( $matches ) {
247 $toVariant = $this->getPreferredVariant();
248 $title = $matches[1];
250 // we convert captions except URL
251 if( !strpos( $text, '://' ) )
252 $text = $this->translate($text, $toVariant);
253 return " $title=\"$text\"";
257 * dictionary-based conversion
259 * @param string $text the text to be converted
260 * @param string $toVariant the target language code
261 * @return string the converted text
264 function autoConvert($text, $toVariant=false) {
265 $fname="LanguageConverter::autoConvert";
267 wfProfileIn( $fname );
269 if(!$this->mTablesLoaded
)
273 $toVariant = $this->getPreferredVariant();
274 if(!in_array($toVariant, $this->mVariants
))
277 /* we convert everything except:
278 1. html markups (anything between < and >)
280 3. place holders created by the parser
283 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
284 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
288 // this one is needed when the text is inside an html markup
289 $htmlfix = '|<[^>]+$|^[^<>]*>';
291 // disable convert to variants between <code></code> tags
292 $codefix = '<code>.+?<\/code>|';
293 // disable convertsion of <script type="text/javascript"> ... </script>
294 $scriptfix = '<script.*?>.*?<\/script>|';
295 // disable conversion of <pre xxxx> ... </pre>
296 $prefix = '<pre.*?>.*?<\/pre>|';
298 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
300 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
302 $m = array_shift($matches);
304 $ret = $this->translate($m[0], $toVariant);
305 $mstart = $m[1]+
strlen($m[0]);
307 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
308 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
309 foreach($matches as $m) {
310 $mark = substr($text, $mstart, $m[1]-$mstart);
311 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
313 $ret .= $this->translate($m[0], $toVariant);
314 $mstart = $m[1] +
strlen($m[0]);
316 wfProfileOut( $fname );
321 * Translate a string to a variant
322 * Doesn't process markup or do any of that other stuff, for that use convert()
324 * @param string $text Text to convert
325 * @param string $variant Variant language code
326 * @return string Translated text
329 function translate( $text, $variant ) {
330 wfProfileIn( __METHOD__
);
331 if( !$this->mTablesLoaded
)
333 $text = $this->mTables
[$variant]->replace( $text );
334 wfProfileOut( __METHOD__
);
339 * convert text to all supported variants
341 * @param string $text the text to be converted
342 * @return array of string
345 function autoConvertToAllVariants($text) {
346 $fname="LanguageConverter::autoConvertToAllVariants";
347 wfProfileIn( $fname );
348 if( !$this->mTablesLoaded
)
352 foreach($this->mVariants
as $variant) {
353 $ret[$variant] = $this->translate($text, $variant);
356 wfProfileOut( $fname );
361 * convert link text to all supported variants
363 * @param string $text the text to be converted
364 * @return array of string
367 function convertLinkToAllVariants($text) {
368 if( !$this->mTablesLoaded
)
372 $tarray = explode($this->mMarkup
['begin'], $text);
373 $tfirst = array_shift($tarray);
375 foreach($this->mVariants
as $variant)
376 $ret[$variant] = $this->translate($tfirst,$variant);
378 foreach($tarray as $txt) {
379 $marked = explode($this->mMarkup
['end'], $txt, 2);
381 foreach($this->mVariants
as $variant){
382 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
383 if(array_key_exists(1, $marked))
384 $ret[$variant] .= $this->translate($marked[1],$variant);
393 * prepare manual conversion table
396 function applyManualConv( $convRule ){
397 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
398 $title = $convRule->getTitle();
400 $this->mTitleFromFlag
= true;
401 $this->mTitleDisplay
= $title;
404 //apply manual conversion table to global table
405 $convTable = $convRule->getConvTable();
406 $action = $convRule->getRulesAction();
407 foreach( $convTable as $variant => $pair ) {
408 if( !in_array( $variant, $this->mVariants
) )continue;
409 if( $action=="add" ) {
410 foreach( $pair as $from => $to ) {
411 // to ensure that $from and $to not be left blank
412 // so $this->translate() could always return a string
414 // more efficient than array_merge(), about 2.5 times.
415 $this->mTables
[$variant]->setPair( $from, $to );
418 elseif ( $action == "remove" ) {
419 $this->mTables
[$variant]->removeArray( $pair );
425 * Convert text using a parser object for context
428 function parserConvert( $text, &$parser ) {
429 global $wgDisableLangConversion;
430 /* don't do anything if this is the conversion table */
431 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
432 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
437 if ( $wgDisableLangConversion )
440 $text = $this->convert( $text );
442 if ( $this->mTitleFromFlag
)
443 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
449 * @param string $title the title included namespace
450 * @return array of string
453 function convertNamespace( $title, $variant ) {
454 $splittitle = explode( ':', $title );
455 if (count($splittitle) < 2)
457 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
458 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
459 $ret = implode(':', $splittitle );
467 function convertTitle( $text, $variant ){
468 global $wgDisableTitleConversion, $wgUser;
470 // check for global param and __NOTC__ tag
471 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
472 $this->mTitleDisplay
= $text;
476 // use the title from the T flag if any
477 if( $this->mTitleFromFlag
){
478 $this->mTitleFromFlag
= false;
479 return $this->mTitleDisplay
;
483 $isredir = $wgRequest->getText( 'redirect', 'yes' );
484 $action = $wgRequest->getText( 'action' );
485 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
486 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
489 $text = $this->convertNamespace( $text, $variant );
490 $this->mTitleDisplay
= $this->convert( $text );
491 return $this->mTitleDisplay
;
496 * convert text to different variants of a language. the automatic
497 * conversion is done in autoConvert(). here we parse the text
498 * marked with -{}-, which specifies special conversions of the
499 * text that can not be accomplished in autoConvert()
501 * syntax of the markup:
502 * -{code1:text1;code2:text2;...}- or
503 * -{flags|code1:text1;code2:text2;...}- or
504 * -{text}- in which case no conversion should take place for text
506 * @param string $text text to be converted
507 * @param bool $isTitle whether this conversion is for the article title
508 * @return string converted text
511 function convert( $text, $isTitle = false ) {
513 $mw =& MagicWord
::get( 'notitleconvert' );
514 if( $mw->matchAndRemove( $text ) )
515 $this->mDoTitleConvert
= false;
516 $mw =& MagicWord
::get( 'nocontentconvert' );
517 if( $mw->matchAndRemove( $text ) ) {
518 $this->mDoContentConvert
= false;
521 // no conversion if redirecting
522 $mw =& MagicWord
::get( 'redirect' );
523 if( $mw->matchStart( $text ) )
526 $plang = $this->getPreferredVariant();
528 // for title convertion
529 if ( $isTitle ) return $this->convertTitle( $text, $plang );
531 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
534 foreach ( $tarray as $txt ) {
536 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
538 if( $this->mDoContentConvert
)
539 // Bug 19620: should convert a string immediately after a new rule added.
540 $text .= $this->autoConvert( $marked[0], $plang );
544 if ( array_key_exists( 1, $marked ) ) {
545 $crule = new ConverterRule($marked[1], $this);
546 $crule->parse( $plang );
547 $text .= $crule->getDisplay();
548 $this->applyManualConv( $crule );
551 $text .= $this->mMarkup
['end'];
555 // Remove the last delimiter (wasn't real)
556 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
561 * if a language supports multiple variants, it is
562 * possible that non-existing link in one variant
563 * actually exists in another variant. this function
564 * tries to find it. See e.g. LanguageZh.php
566 * @param string $link the name of the link
567 * @param mixed $nt the title object of the link
568 * @param boolean $ignoreOtherCond: to disable other conditions when
569 * we need to transclude a template or update a category's link
570 * @return null the input parameters may be modified upon return
573 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
574 # If the article has already existed, there is no need to
575 # check it again, otherwise it may cause a fault.
576 if ( is_object( $nt ) && $nt->exists() )
579 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
580 $isredir = $wgRequest->getText( 'redirect', 'yes' );
581 $action = $wgRequest->getText( 'action' );
582 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
583 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
584 $linkBatch = new LinkBatch();
588 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
589 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
592 if ( is_object( $nt ) )
593 $ns = $nt->getNamespace();
595 $variants = $this->autoConvertToAllVariants($link);
596 if($variants == false) //give up
601 foreach( $variants as $v ) {
603 $varnt = Title
::newFromText( $v, $ns );
604 if(!is_null($varnt)){
605 $linkBatch->addObj($varnt);
611 // fetch all variants in single query
612 $linkBatch->execute();
614 foreach( $titles as $varnt ) {
615 if( $varnt->getArticleID() > 0 ) {
617 $link = $varnt->getText();
624 * returns language specific hash options
628 function getExtraHashOptions() {
629 $variant = $this->getPreferredVariant();
630 return '!' . $variant ;
634 * get title text as defined in the body of the article text
638 function getParsedTitle() {
639 return $this->mTitleDisplay
;
643 * a write lock to the cache
647 function lockCache() {
650 for($i=0; $i<30; $i++
) {
651 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
663 function unlockCache() {
665 $wgMemc->delete($this->mCacheKey
. "lock");
670 * Load default conversion tables
671 * This method must be implemented in derived class
675 function loadDefaultTables() {
676 $name = get_class($this);
677 wfDie("Must implement loadDefaultTables() method in class $name");
681 * load conversion tables either from the cache or the disk
684 function loadTables($fromcache=true) {
686 if( $this->mTablesLoaded
)
688 wfProfileIn( __METHOD__
);
689 $this->mTablesLoaded
= true;
690 $this->mTables
= false;
692 wfProfileIn( __METHOD__
.'-cache' );
693 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
694 wfProfileOut( __METHOD__
.'-cache' );
696 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
697 wfProfileIn( __METHOD__
.'-recache' );
698 // not in cache, or we need a fresh reload.
699 // we will first load the default tables
700 // then update them using things in MediaWiki:Zhconversiontable/*
701 $this->loadDefaultTables();
702 foreach($this->mVariants
as $var) {
703 $cached = $this->parseCachedTable($var);
704 $this->mTables
[$var]->mergeArray($cached);
707 $this->postLoadTables();
708 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
710 if($this->lockCache()) {
711 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
712 $this->unlockCache();
714 wfProfileOut( __METHOD__
.'-recache' );
716 wfProfileOut( __METHOD__
);
720 * Hook for post processig after conversion tables are loaded
723 function postLoadTables() {}
726 * Reload the conversion tables
730 function reloadTables() {
732 unset($this->mTables
);
733 $this->mTablesLoaded
= false;
734 $this->loadTables(false);
739 * parse the conversion table stored in the cache
741 * the tables should be in blocks of the following form:
748 * to make the tables more manageable, subpages are allowed
749 * and will be parsed recursively if $recursive=true
752 function parseCachedTable($code, $subpage='', $recursive=true) {
753 global $wgMessageCache;
754 static $parsed = array();
756 if(!is_object($wgMessageCache))
759 $key = 'Conversiontable/'.$code;
761 $key .= '/' . $subpage;
763 if(array_key_exists($key, $parsed))
766 if ( strpos( $code, '/' ) === false ) {
767 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
769 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
770 if ( $title && $title->exists() ) {
771 $article = new Article( $title );
772 $txt = $article->getContents();
778 // get all subpage links of the form
779 // [[MediaWiki:conversiontable/zh-xx/...|...]]
780 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
781 $subs = explode('[[', $txt);
783 foreach( $subs as $sub ) {
784 $link = explode(']]', $sub, 2);
785 if(count($link) != 2)
787 $b = explode('|', $link[0]);
788 $b = explode('/', trim($b[0]), 3);
794 if($b[0] == $linkhead && $b[1] == $code) {
795 $sublinks[] = $sublink;
800 // parse the mappings in this page
801 $blocks = explode($this->mMarkup
['begin'], $txt);
802 array_shift($blocks);
804 foreach($blocks as $block) {
805 $mappings = explode($this->mMarkup
['end'], $block, 2);
806 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
807 $table = explode( ';', $stripped );
808 foreach( $table as $t ) {
809 $m = explode( '=>', $t );
810 if( count( $m ) != 2)
812 // trim any trailling comments starting with '//'
813 $tt = explode('//', $m[1], 2);
814 $ret[trim($m[0])] = trim($tt[0]);
817 $parsed[$key] = true;
820 // recursively parse the subpages
822 foreach($sublinks as $link) {
823 $s = $this->parseCachedTable($code, $link, $recursive);
824 $ret = array_merge($ret, $s);
828 if ($this->mUcfirst
) {
829 foreach ($ret as $k => $v) {
830 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
837 * Enclose a string with the "no conversion" tag. This is used by
838 * various functions in the Parser
840 * @param string $text text to be tagged for no conversion
841 * @return string the tagged text
844 function markNoConversion($text, $noParse=false) {
845 # don't mark if already marked
846 if(strpos($text, $this->mMarkup
['begin']) ||
847 strpos($text, $this->mMarkup
['end']))
850 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
855 * convert the sorting key for category links. this should make different
856 * keys that are variants of each other map to the same key
858 function convertCategoryKey( $key ) {
862 * hook to refresh the cache of conversion tables when
863 * MediaWiki:conversiontable* is updated
866 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
867 $titleobj = $article->getTitle();
868 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
869 $title = $titleobj->getDBkey();
870 $t = explode('/', $title, 3);
872 if( $c > 1 && $t[0] == 'Conversiontable' ) {
873 if(in_array($t[1], $this->mVariants
)) {
874 $this->reloadTables();
882 * Armour rendered math against conversion
883 * Wrap math into rawoutput -{R| math }- syntax
886 function armourMath($text){
887 // we need to convert '-{' and '}-' to '-{' and '}-'
888 // to avoid a unwanted '}-' appeared after the math-image.
889 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
890 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
896 * parser for rules of language conversion , parse rules in -{ }- tag
898 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
900 class ConverterRule
{
901 var $mText; // original text in -{text}-
902 var $mConverter; // LanguageConverter object
903 var $mManualCodeError='<strong class="error">code error!</strong>';
904 var $mRuleDisplay = '',$mRuleTitle=false;
905 var $mRules = '';// string : the text of the rules
906 var $mRulesAction = 'none';
907 var $mFlags = array();
908 var $mConvTable = array();
909 var $mBidtable = array();// array of the translation in each variant
910 var $mUnidtable = array();// array of the translation in each variant
915 * @param string $text the text between -{ and }-
916 * @param object $converter a LanguageConverter object
919 function __construct($text,$converter){
920 $this->mText
= $text;
921 $this->mConverter
=$converter;
922 foreach($converter->mVariants
as $v){
923 $this->mConvTable
[$v]=array();
928 * check if variants array in convert array
930 * @param string $variant Variant language code
931 * @return string Translated text
934 function getTextInBidtable($variants){
935 if(is_string($variants)){ $variants=array($variants); }
936 if(!is_array($variants)) return false;
937 foreach ($variants as $variant){
938 if(array_key_exists($variant, $this->mBidtable
)){
939 return $this->mBidtable
[$variant];
946 * Parse flags with syntax -{FLAG| ... }-
949 function parseFlags(){
950 $text = $this->mText
;
951 if(strlen($text) < 2 ) {
952 $this->mFlags
= array( 'R' );
953 $this->mRules
= $text;
958 $markup = $this->mConverter
->mMarkup
;
959 $validFlags = $this->mConverter
->mFlags
;
960 $variants = $this->mConverter
->mVariants
;
962 $tt = explode($markup['flagsep'], $text, 2);
963 if(count($tt) == 2) {
964 $f = explode($markup['varsep'], $tt[0]);
967 if(array_key_exists($ff, $validFlags) &&
968 !in_array($validFlags[$ff], $flags))
969 $flags[] = $validFlags[$ff];
977 if( in_array('R',$flags) ){
978 $flags = array('R');// remove other flags
979 } elseif ( in_array('N',$flags) ){
980 $flags = array('N');// remove other flags
981 } elseif ( in_array('-',$flags) ){
982 $flags = array('-');// remove other flags
983 } elseif (count($flags)==1 && $flags[0]=='T'){
985 } elseif ( in_array('H',$flags) ){
986 // replace A flag, and remove other flags except T
987 $temp=array('+','H');
988 if(in_array('T',$flags)) $temp[] = 'T';
989 if(in_array('D',$flags)) $temp[] = 'D';
992 if ( in_array('A',$flags) ) {
996 if ( in_array('D',$flags) )
997 $flags=array_diff($flags,array('S'));
998 $flags_temp = array();
999 foreach ($variants as $variant) {
1000 // try to find flags like "zh-hans", "zh-hant"
1001 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1002 if ( in_array($variant, $flags) )
1003 $flags_temp[] = $variant;
1005 if ( count($flags_temp) !== 0 )
1006 $flags = $flags_temp;
1008 if ( count($flags) == 0 )
1009 $flags = array('S');
1010 $this->mRules
=$rules;
1011 $this->mFlags
=$flags;
1015 * generate conversion table
1018 function parseRules() {
1019 $rules = $this->mRules
;
1020 $flags = $this->mFlags
;
1021 $bidtable = array();
1022 $unidtable = array();
1023 $markup = $this->mConverter
->mMarkup
;
1024 $variants = $this->mConverter
->mVariants
;
1026 // varsep_pattern for preg_split:
1027 // text should be splited by ";" only if a valid variant
1028 // name exist after the markup, for example:
1029 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1030 // we should split it as:
1032 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1033 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1036 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1037 foreach( $variants as $variant ) {
1038 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1039 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1040 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1042 $varsep_pattern .= '\s*$)/';
1044 $choice = preg_split($varsep_pattern, $rules);
1046 foreach( $choice as $c ) {
1047 $v = explode($markup['codesep'], $c, 2);
1048 if( count($v) != 2 )
1049 continue;// syntax error, skip
1052 $u = explode($markup['unidsep'], $v);
1053 // if $to is empty, strtr() could return a wrong result
1054 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1055 $bidtable[$v] = $to;
1056 } else if(count($u) == 2){
1057 $from = trim($u[0]);
1059 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1060 && $to && in_array( $v, $variants ) )
1061 $unidtable[$v] = array( $from=>$to );
1062 elseif ( $to && in_array( $v, $variants ) )
1063 $unidtable[$v][$from] = $to;
1065 // syntax error, pass
1066 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1067 $bidtable = array();
1068 $unidtable = array();
1072 $this->mBidtable
= $bidtable;
1073 $this->mUnidtable
= $unidtable;
1079 function getRulesDesc(){
1080 $codesep = $this->mConverter
->mDescCodeSep
;
1081 $varsep = $this->mConverter
->mDescVarSep
;
1083 foreach($this->mBidtable
as $k => $v)
1084 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1085 foreach($this->mUnidtable
as $k => $a)
1086 foreach($a as $from=>$to)
1087 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1092 * Parse rules conversion
1095 function getRuleConvertedStr($variant,$doConvert){
1096 $bidtable = $this->mBidtable
;
1097 $unidtable = $this->mUnidtable
;
1099 if( count($bidtable) +
count($unidtable) == 0 ){
1100 return $this->mRules
;
1101 } elseif ($doConvert){// the text converted
1102 // display current variant in bidirectional array
1103 $disp = $this->getTextInBidtable($variant);
1104 // or display current variant in fallbacks
1106 $disp = $this->getTextInBidtable(
1107 $this->mConverter
->getVariantFallbacks($variant));
1108 // or display current variant in unidirectional array
1109 if(!$disp && array_key_exists($variant,$unidtable)){
1110 $disp = array_values($unidtable[$variant]);
1113 // or display frist text under disable manual convert
1114 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1115 if(count($bidtable)>0){
1116 $disp = array_values($bidtable);
1119 $disp = array_values($unidtable);
1120 $disp = array_values($disp[0]);
1125 } else {// no convert
1126 return $this->mRules
;
1131 * generate conversion table for all text
1134 function generateConvTable(){
1135 $flags = $this->mFlags
;
1136 $bidtable = $this->mBidtable
;
1137 $unidtable = $this->mUnidtable
;
1138 $manLevel = $this->mConverter
->mManualLevel
;
1141 foreach($this->mConverter
->mVariants
as $v) {
1142 /* for bidirectional array
1143 fill in the missing variants, if any,
1145 if(!array_key_exists($v, $bidtable)) {
1146 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1147 $vf = $this->getTextInBidtable($variantFallbacks);
1148 if($vf) $bidtable[$v] = $vf;
1151 if(array_key_exists($v,$bidtable)){
1152 foreach($vmarked as $vo){
1153 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1154 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1155 // to introduce a custom mapping between
1156 // words WordZh and WordTw in the whole text
1157 if($manLevel[$v]=='bidirectional'){
1158 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1160 if($manLevel[$vo]=='bidirectional'){
1161 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1166 /*for unidirectional array
1167 fill to convert tables */
1168 $allow_unid = $manLevel[$v]=='bidirectional'
1169 ||
$manLevel[$v]=='unidirectional';
1170 if($allow_unid && array_key_exists($v,$unidtable)){
1171 $ct=$this->mConvTable
[$v];
1172 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1178 * Parse rules and flags
1181 function parse($variant){
1183 $variant = $this->mConverter
->getPreferredVariant();
1185 $variants = $this->mConverter
->mVariants
;
1186 $this->parseFlags();
1187 $flags = $this->mFlags
;
1189 // convert to specified variant
1190 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1191 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1192 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1193 // then convert <text to convert> to current language
1194 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1195 else { // if current variant no in flags,
1196 // then we check its fallback variants.
1197 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1198 foreach ( $variantFallbacks as $variantFallback ) {
1199 // if current variant's fallback exist in flags
1200 if ( in_array( $variantFallback, $flags ) ) {
1201 // then convert <text to convert> to fallback language
1202 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1207 $this->mFlags
= $flags = array('R');
1210 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1211 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1212 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1214 $this->parseRules();
1216 $rules = $this->mRules
;
1218 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1219 if(in_array('+',$flags) ||
in_array('-',$flags))
1220 // fill all variants if text in -{A/H/-|text} without rules
1221 foreach($this->mConverter
->mVariants
as $v)
1222 $this->mBidtable
[$v] = $rules;
1223 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1224 $this->mFlags
= $flags = array('R');
1227 if( in_array('R',$flags) ) {
1228 // if we don't do content convert, still strip the -{}- tags
1229 $this->mRuleDisplay
= $rules;
1230 } elseif ( in_array('N',$flags) ){
1231 // proces N flag: output current variant name
1232 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1233 } elseif ( in_array('D',$flags) ){
1234 // proces D flag: output rules description
1235 $this->mRuleDisplay
= $this->getRulesDesc();
1236 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1237 // proces H,- flag or T only: output nothing
1238 $this->mRuleDisplay
= '';
1239 } elseif ( in_array('S',$flags) ){
1240 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1241 $this->mConverter
->mDoContentConvert
);
1243 $this->mRuleDisplay
= $this->mManualCodeError
;
1246 if ( in_array('T',$flags) ) {
1247 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1248 $this->mConverter
->mDoTitleConvert
);
1251 if (in_array('-', $flags))
1252 $this->mRulesAction
='remove';
1253 if (in_array('+', $flags))
1254 $this->mRulesAction
='add';
1256 $this->generateConvTable();
1262 function hasRules(){
1267 * get display text on markup -{...}-
1270 function getDisplay(){
1271 return $this->mRuleDisplay
;
1274 * get converted title
1277 function getTitle(){
1278 return $this->mRuleTitle
;
1282 * return how deal with conversion rules
1285 function getRulesAction(){
1286 return $this->mRulesAction
;
1290 * get conversion table ( bidirectional and unidirectional conversion table )
1293 function getConvTable(){
1294 return $this->mConvTable
;
1298 * get conversion rules string
1301 function getRules(){
1302 return $this->mRules
;
1306 * get conversion flags
1309 function getFlags(){
1310 return $this->mFlags
;