LanguageConverter.php 33 KB

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