PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/languages/LanguageConverter.php

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