LanguageConverter.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. <?php
  2. /**
  3. * Contains the LanguageConverter class and ConverterRule class
  4. * @ingroup Language
  5. *
  6. * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  7. * @file
  8. */
  9. /**
  10. * base class for language convert
  11. * @ingroup Language
  12. *
  13. * @author Zhengzhu Feng <zhengzhu@gmail.com>
  14. * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
  15. */
  16. class LanguageConverter {
  17. var $mPreferredVariant='';
  18. var $mMainLanguageCode;
  19. var $mVariants, $mVariantFallbacks, $mVariantNames;
  20. var $mTablesLoaded = false;
  21. var $mTables;
  22. var $mManualAddTables;
  23. var $mManualRemoveTables;
  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;
  29. var $mCacheKey;
  30. var $mLangObj;
  31. var $mMarkup;
  32. var $mFlags;
  33. var $mDescCodeSep = ':',$mDescVarSep = ';';
  34. var $mUcfirst = false;
  35. const CACHE_VERSION_KEY = 'VERSION 6';
  36. /**
  37. * Constructor
  38. *
  39. * @param string $maincode the main language code of this language
  40. * @param array $variants the supported variants of this language
  41. * @param array $variantfallback the fallback language of each variant
  42. * @param array $markup array defining the markup used for manual conversion
  43. * @param array $flags array defining the custom strings that maps to the flags
  44. * @param array $manualLevel limit for supported variants
  45. * @public
  46. */
  47. function __construct($langobj, $maincode,
  48. $variants=array(),
  49. $variantfallbacks=array(),
  50. $markup=array(),
  51. $flags = array(),
  52. $manualLevel = array() ) {
  53. $this->mLangObj = $langobj;
  54. $this->mMainLanguageCode = $maincode;
  55. $this->mVariants = $variants;
  56. $this->mVariantFallbacks = $variantfallbacks;
  57. global $wgLanguageNames;
  58. $this->mVariantNames = $wgLanguageNames;
  59. $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
  60. $m = array(
  61. 'begin'=>'-{',
  62. 'flagsep'=>'|',
  63. 'unidsep'=>'=>', //for unidirectional conversion
  64. 'codesep'=>':',
  65. 'varsep'=>';',
  66. 'end'=>'}-'
  67. );
  68. $this->mMarkup = array_merge($m, $markup);
  69. $f = array(
  70. // 'S' show converted text
  71. // '+' add rules for alltext
  72. // 'E' the gave flags is error
  73. // these flags above are reserved for program
  74. 'A'=>'A', // add rule for convert code (all text convert)
  75. 'T'=>'T', // title convert
  76. 'R'=>'R', // raw content
  77. 'D'=>'D', // convert description (subclass implement)
  78. '-'=>'-', // remove convert (not implement)
  79. 'H'=>'H', // add rule for convert code (but no display in placed code )
  80. 'N'=>'N' // current variant name
  81. );
  82. $this->mFlags = array_merge($f, $flags);
  83. foreach( $this->mVariants as $v) {
  84. $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
  85. ?$manualLevel[$v]
  86. :'bidirectional';
  87. $this->mManualAddTables[$v] = array();
  88. $this->mManualRemoveTables[$v] = array();
  89. $this->mNamespaceTables[$v] = array();
  90. $this->mFlags[$v] = $v;
  91. }
  92. }
  93. /**
  94. * @public
  95. */
  96. function getVariants() {
  97. return $this->mVariants;
  98. }
  99. /**
  100. * in case some variant is not defined in the markup, we need
  101. * to have some fallback. for example, in zh, normally people
  102. * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
  103. * when zh-sg is preferred but not defined, we will pick zh-hans
  104. * in this case. right now this is only used by zh.
  105. *
  106. * @param string $v the language code of the variant
  107. * @return string array the code of the fallback language or false if there is no fallback
  108. * @public
  109. */
  110. function getVariantFallbacks($v) {
  111. if( isset( $this->mVariantFallbacks[$v] ) ) {
  112. return $this->mVariantFallbacks[$v];
  113. }
  114. return $this->mMainLanguageCode;
  115. }
  116. /**
  117. * get preferred language variants.
  118. * @param boolean $fromUser Get it from $wgUser's preferences
  119. * @return string the preferred language code
  120. * @public
  121. */
  122. function getPreferredVariant( $fromUser = true ) {
  123. global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
  124. if($this->mPreferredVariant)
  125. return $this->mPreferredVariant;
  126. // figure out user lang without constructing wgLang to avoid infinite recursion
  127. if( $fromUser )
  128. $defaultUserLang = $wgUser->getOption( 'language' );
  129. else
  130. $defaultUserLang = $this->mMainLanguageCode;
  131. $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
  132. // see if interface language is same as content, if not, prevent conversion
  133. if( ! in_array( $userLang, $this->mVariants ) ){
  134. $this->mPreferredVariant = $this->mMainLanguageCode; // no conversion
  135. return $this->mPreferredVariant;
  136. }
  137. // see if the preference is set in the request
  138. $req = $wgRequest->getText( 'variant' );
  139. if( in_array( $req, $this->mVariants ) ) {
  140. $this->mPreferredVariant = $req;
  141. return $req;
  142. }
  143. // check the syntax /code/ArticleTitle
  144. if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
  145. // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
  146. // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
  147. $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
  148. if(in_array($scriptBase,$this->mVariants)){
  149. $this->mPreferredVariant = $scriptBase;
  150. return $this->mPreferredVariant;
  151. }
  152. }
  153. // get language variant preference from logged in users
  154. // Don't call this on stub objects because that causes infinite
  155. // recursion during initialisation
  156. if( $fromUser && $wgUser->isLoggedIn() ) {
  157. $this->mPreferredVariant = $wgUser->getOption('variant');
  158. return $this->mPreferredVariant;
  159. }
  160. // see if default variant is globaly set
  161. if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
  162. $this->mPreferredVariant = $wgDefaultLanguageVariant;
  163. return $this->mPreferredVariant;
  164. }
  165. # FIXME rewrite code for parsing http header. The current code
  166. # is written specific for detecting zh- variants
  167. if( !$this->mPreferredVariant ) {
  168. // see if some supported language variant is set in the
  169. // http header, but we don't set the mPreferredVariant
  170. // variable in case this is called before the user's
  171. // preference is loaded
  172. $pv=$this->mMainLanguageCode;
  173. if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  174. $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
  175. $zh = strstr($header, $pv.'-');
  176. if($zh) {
  177. $ary = split("[,;]",$zh);
  178. $pv = $ary[0];
  179. }
  180. }
  181. // don't try to return bad variant
  182. if(in_array( $pv, $this->mVariants ))
  183. return $pv;
  184. }
  185. return $this->mMainLanguageCode;
  186. }
  187. /**
  188. * caption convert, base on preg_replace_callback
  189. *
  190. * to convert text in "title" or "alt", like '<img alt="text" ... '
  191. * or '<span title="text" ... '
  192. *
  193. * @return string like ' alt="yyyy"' or ' title="yyyy"'
  194. * @private
  195. */
  196. function captionConvert( $matches ) {
  197. $toVariant = $this->getPreferredVariant();
  198. $title = $matches[1];
  199. $text = $matches[2];
  200. // we convert captions except URL
  201. if( !strpos( $text, '://' ) )
  202. $text = $this->translate($text, $toVariant);
  203. return " $title=\"$text\"";
  204. }
  205. /**
  206. * dictionary-based conversion
  207. *
  208. * @param string $text the text to be converted
  209. * @param string $toVariant the target language code
  210. * @return string the converted text
  211. * @private
  212. */
  213. function autoConvert($text, $toVariant=false) {
  214. $fname="LanguageConverter::autoConvert";
  215. wfProfileIn( $fname );
  216. if(!$this->mTablesLoaded)
  217. $this->loadTables();
  218. if(!$toVariant)
  219. $toVariant = $this->getPreferredVariant();
  220. if(!in_array($toVariant, $this->mVariants))
  221. return $text;
  222. /* we convert everything except:
  223. 1. html markups (anything between < and >)
  224. 2. html entities
  225. 3. place holders created by the parser
  226. */
  227. global $wgParser;
  228. if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
  229. $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
  230. } else
  231. $marker = "";
  232. // this one is needed when the text is inside an html markup
  233. $htmlfix = '|<[^>]+$|^[^<>]*>';
  234. // disable convert to variants between <code></code> tags
  235. $codefix = '<code>.+?<\/code>|';
  236. // disable convertsion of <script type="text/javascript"> ... </script>
  237. $scriptfix = '<script.*?>.*?<\/script>|';
  238. // disable conversion of <pre xxxx> ... </pre>
  239. $prefix = '<pre.*?>.*?<\/pre>|';
  240. $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
  241. $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
  242. $m = array_shift($matches);
  243. $ret = $this->translate($m[0], $toVariant);
  244. $mstart = $m[1]+strlen($m[0]);
  245. // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
  246. $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
  247. foreach($matches as $m) {
  248. $mark = substr($text, $mstart, $m[1]-$mstart);
  249. $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
  250. $ret .= $mark;
  251. $ret .= $this->translate($m[0], $toVariant);
  252. $mstart = $m[1] + strlen($m[0]);
  253. }
  254. wfProfileOut( $fname );
  255. return $ret;
  256. }
  257. /**
  258. * Translate a string to a variant
  259. * Doesn't process markup or do any of that other stuff, for that use convert()
  260. *
  261. * @param string $text Text to convert
  262. * @param string $variant Variant language code
  263. * @return string Translated text
  264. * @private
  265. */
  266. function translate( $text, $variant ) {
  267. wfProfileIn( __METHOD__ );
  268. if( !$this->mTablesLoaded )
  269. $this->loadTables();
  270. $text = $this->mTables[$variant]->replace( $text );
  271. wfProfileOut( __METHOD__ );
  272. return $text;
  273. }
  274. /**
  275. * convert text to all supported variants
  276. *
  277. * @param string $text the text to be converted
  278. * @return array of string
  279. * @public
  280. */
  281. function autoConvertToAllVariants($text) {
  282. $fname="LanguageConverter::autoConvertToAllVariants";
  283. wfProfileIn( $fname );
  284. if( !$this->mTablesLoaded )
  285. $this->loadTables();
  286. $ret = array();
  287. foreach($this->mVariants as $variant) {
  288. $ret[$variant] = $this->translate($text, $variant);
  289. }
  290. wfProfileOut( $fname );
  291. return $ret;
  292. }
  293. /**
  294. * convert link text to all supported variants
  295. *
  296. * @param string $text the text to be converted
  297. * @return array of string
  298. * @public
  299. */
  300. function convertLinkToAllVariants($text) {
  301. if( !$this->mTablesLoaded )
  302. $this->loadTables();
  303. $ret = array();
  304. $tarray = explode($this->mMarkup['begin'], $text);
  305. $tfirst = array_shift($tarray);
  306. foreach($this->mVariants as $variant)
  307. $ret[$variant] = $this->translate($tfirst,$variant);
  308. foreach($tarray as $txt) {
  309. $marked = explode($this->mMarkup['end'], $txt, 2);
  310. foreach($this->mVariants as $variant){
  311. $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
  312. if(array_key_exists(1, $marked))
  313. $ret[$variant] .= $this->translate($marked[1],$variant);
  314. }
  315. }
  316. return $ret;
  317. }
  318. /**
  319. * prepare manual conversion table
  320. * @private
  321. */
  322. function prepareManualConv( $convRule ){
  323. // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
  324. $title = $convRule->getTitle();
  325. if( $title ){
  326. $this->mTitleFromFlag = true;
  327. $this->mTitleDisplay = $title;
  328. }
  329. //apply manual conversion table to global table
  330. $convTable = $convRule->getConvTable();
  331. $action = $convRule->getRulesAction();
  332. foreach( $convTable as $v => $t ) {
  333. if( !in_array( $v, $this->mVariants ) )continue;
  334. if( $action=="add" ) {
  335. foreach( $t as $from => $to ) {
  336. // to ensure that $from and $to not be left blank
  337. // so $this->translate() could always return a string
  338. if ( $from || $to )
  339. // more efficient than array_merge(), about 2.5 times.
  340. $this->mManualAddTables[$v][$from] = $to;
  341. }
  342. }
  343. elseif ( $action == "remove" ) {
  344. foreach ( $t as $from=>$to ) {
  345. if ( $from || $to )
  346. $this->mManualRemoveTables[$v][$from] = $to;
  347. }
  348. }
  349. }
  350. }
  351. /**
  352. * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
  353. * @private
  354. */
  355. function applyManualConv(){
  356. //apply manual conversion table to global table
  357. foreach($this->mVariants as $v) {
  358. if (count($this->mManualAddTables[$v]) > 0) {
  359. $this->mTables[$v]->mergeArray($this->mManualAddTables[$v]);
  360. }
  361. if (count($this->mManualRemoveTables[$v]) > 0)
  362. $this->mTables[$v]->removeArray($this->mManualRemoveTables[$v]);
  363. }
  364. }
  365. /**
  366. * Convert text using a parser object for context
  367. * @public
  368. */
  369. function parserConvert( $text, &$parser ) {
  370. global $wgDisableLangConversion;
  371. /* don't do anything if this is the conversion table */
  372. if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
  373. strpos($parser->mTitle->getText(), "Conversiontable") !== false )
  374. {
  375. return $text;
  376. }
  377. if ( $wgDisableLangConversion )
  378. return $text;
  379. $text = $this->convert( $text );
  380. if ( $this->mTitleFromFlag )
  381. $parser->mOutput->setTitleText( $this->mTitleDisplay );
  382. return $text;
  383. }
  384. /**
  385. * convert namespace
  386. * @param string $title the title included namespace
  387. * @return array of string
  388. * @private
  389. */
  390. function convertNamespace( $title, $variant ) {
  391. $splittitle = explode( ':', $title );
  392. if (count($splittitle) < 2)
  393. return $title;
  394. if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) )
  395. $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
  396. $ret = implode(':', $splittitle );
  397. return $ret;
  398. }
  399. /**
  400. * convert title
  401. * @private
  402. */
  403. function convertTitle( $text, $variant ){
  404. global $wgDisableTitleConversion, $wgUser;
  405. // check for global param and __NOTC__ tag
  406. if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
  407. $this->mTitleDisplay = $text;
  408. return $text;
  409. }
  410. // use the title from the T flag if any
  411. if( $this->mTitleFromFlag ){
  412. $this->mTitleFromFlag = false;
  413. return $this->mTitleDisplay;
  414. }
  415. global $wgRequest;
  416. $isredir = $wgRequest->getText( 'redirect', 'yes' );
  417. $action = $wgRequest->getText( 'action' );
  418. $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
  419. if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
  420. return $text;
  421. } else {
  422. $text = $this->convertNamespace( $text, $variant );
  423. $this->mTitleDisplay = $this->convert( $text );
  424. return $this->mTitleDisplay;
  425. }
  426. }
  427. /**
  428. * convert text to different variants of a language. the automatic
  429. * conversion is done in autoConvert(). here we parse the text
  430. * marked with -{}-, which specifies special conversions of the
  431. * text that can not be accomplished in autoConvert()
  432. *
  433. * syntax of the markup:
  434. * -{code1:text1;code2:text2;...}- or
  435. * -{flags|code1:text1;code2:text2;...}- or
  436. * -{text}- in which case no conversion should take place for text
  437. *
  438. * @param string $text text to be converted
  439. * @param bool $isTitle whether this conversion is for the article title
  440. * @return string converted text
  441. * @public
  442. */
  443. function convert( $text, $isTitle = false ) {
  444. $mw =& MagicWord::get( 'notitleconvert' );
  445. if( $mw->matchAndRemove( $text ) )
  446. $this->mDoTitleConvert = false;
  447. $mw =& MagicWord::get( 'nocontentconvert' );
  448. if( $mw->matchAndRemove( $text ) ) {
  449. $this->mDoContentConvert = false;
  450. }
  451. // no conversion if redirecting
  452. $mw =& MagicWord::get( 'redirect' );
  453. if( $mw->matchStart( $text ) )
  454. return $text;
  455. $plang = $this->getPreferredVariant();
  456. // for title convertion
  457. if ( $isTitle ) return $this->convertTitle( $text, $plang );
  458. $tarray = StringUtils::explode( $this->mMarkup['end'], $text );
  459. $text = '';
  460. $marks = array();
  461. foreach ( $tarray as $txt ) {
  462. $marked = explode( $this->mMarkup['begin'], $txt, 2 );
  463. if ( array_key_exists( 1, $marked ) ) {
  464. $crule = new ConverterRule($marked[1], $this);
  465. $crule->parse( $plang );
  466. $marked[1] = $crule->getDisplay();
  467. $this->prepareManualConv( $crule );
  468. }
  469. else
  470. $marked[0] .= $this->mMarkup['end'];
  471. array_push( $marks, $marked );
  472. }
  473. $this->applyManualConv();
  474. foreach ( $marks as $marked ) {
  475. if( $this->mDoContentConvert )
  476. $text .= $this->autoConvert( $marked[0], $plang );
  477. else
  478. $text .= $marked[0];
  479. if( array_key_exists( 1, $marked ) )
  480. $text .= $marked[1];
  481. }
  482. // Remove the last delimiter (wasn't real)
  483. $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
  484. return $text;
  485. }
  486. /**
  487. * if a language supports multiple variants, it is
  488. * possible that non-existing link in one variant
  489. * actually exists in another variant. this function
  490. * tries to find it. See e.g. LanguageZh.php
  491. *
  492. * @param string $link the name of the link
  493. * @param mixed $nt the title object of the link
  494. * @param boolean $ignoreOtherCond: to disable other conditions when
  495. * we need to transclude a template or update a category's link
  496. * @return null the input parameters may be modified upon return
  497. * @public
  498. */
  499. function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
  500. global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
  501. $isredir = $wgRequest->getText( 'redirect', 'yes' );
  502. $action = $wgRequest->getText( 'action' );
  503. $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
  504. $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
  505. $linkBatch = new LinkBatch();
  506. $ns=NS_MAIN;
  507. if ( $disableLinkConversion || ( !$ignoreOtherCond && ( $isredir == 'no' || $action == 'edit'
  508. || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) )
  509. return;
  510. if(is_object($nt))
  511. $ns = $nt->getNamespace();
  512. $variants = $this->autoConvertToAllVariants($link);
  513. if($variants == false) //give up
  514. return;
  515. $titles = array();
  516. foreach( $variants as $v ) {
  517. if($v != $link){
  518. $varnt = Title::newFromText( $v, $ns );
  519. if(!is_null($varnt)){
  520. $linkBatch->addObj($varnt);
  521. $titles[]=$varnt;
  522. }
  523. }
  524. }
  525. // fetch all variants in single query
  526. $linkBatch->execute();
  527. foreach( $titles as $varnt ) {
  528. if( $varnt->getArticleID() > 0 ) {
  529. $nt = $varnt;
  530. $link = $varnt->getText();
  531. break;
  532. }
  533. }
  534. }
  535. /**
  536. * returns language specific hash options
  537. *
  538. * @public
  539. */
  540. function getExtraHashOptions() {
  541. $variant = $this->getPreferredVariant();
  542. return '!' . $variant ;
  543. }
  544. /**
  545. * get title text as defined in the body of the article text
  546. *
  547. * @public
  548. */
  549. function getParsedTitle() {
  550. return $this->mTitleDisplay;
  551. }
  552. /**
  553. * a write lock to the cache
  554. *
  555. * @private
  556. */
  557. function lockCache() {
  558. global $wgMemc;
  559. $success = false;
  560. for($i=0; $i<30; $i++) {
  561. if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
  562. break;
  563. sleep(1);
  564. }
  565. return $success;
  566. }
  567. /**
  568. * unlock cache
  569. *
  570. * @private
  571. */
  572. function unlockCache() {
  573. global $wgMemc;
  574. $wgMemc->delete($this->mCacheKey . "lock");
  575. }
  576. /**
  577. * Load default conversion tables
  578. * This method must be implemented in derived class
  579. *
  580. * @private
  581. */
  582. function loadDefaultTables() {
  583. $name = get_class($this);
  584. wfDie("Must implement loadDefaultTables() method in class $name");
  585. }
  586. /**
  587. * load conversion tables either from the cache or the disk
  588. * @private
  589. */
  590. function loadTables($fromcache=true) {
  591. global $wgMemc;
  592. if( $this->mTablesLoaded )
  593. return;
  594. wfProfileIn( __METHOD__ );
  595. $this->mTablesLoaded = true;
  596. $this->mTables = false;
  597. if($fromcache) {
  598. wfProfileIn( __METHOD__.'-cache' );
  599. $this->mTables = $wgMemc->get( $this->mCacheKey );
  600. wfProfileOut( __METHOD__.'-cache' );
  601. }
  602. if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
  603. wfProfileIn( __METHOD__.'-recache' );
  604. // not in cache, or we need a fresh reload.
  605. // we will first load the default tables
  606. // then update them using things in MediaWiki:Zhconversiontable/*
  607. $this->loadDefaultTables();
  608. foreach($this->mVariants as $var) {
  609. $cached = $this->parseCachedTable($var);
  610. $this->mTables[$var]->mergeArray($cached);
  611. }
  612. $this->postLoadTables();
  613. $this->mTables[self::CACHE_VERSION_KEY] = true;
  614. if($this->lockCache()) {
  615. $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
  616. $this->unlockCache();
  617. }
  618. wfProfileOut( __METHOD__.'-recache' );
  619. }
  620. wfProfileOut( __METHOD__ );
  621. }
  622. /**
  623. * Hook for post processig after conversion tables are loaded
  624. *
  625. */
  626. function postLoadTables() {}
  627. /**
  628. * Reload the conversion tables
  629. *
  630. * @private
  631. */
  632. function reloadTables() {
  633. if($this->mTables)
  634. unset($this->mTables);
  635. $this->mTablesLoaded = false;
  636. $this->loadTables(false);
  637. }
  638. /**
  639. * parse the conversion table stored in the cache
  640. *
  641. * the tables should be in blocks of the following form:
  642. * -{
  643. * word => word ;
  644. * word => word ;
  645. * ...
  646. * }-
  647. *
  648. * to make the tables more manageable, subpages are allowed
  649. * and will be parsed recursively if $recursive=true
  650. *
  651. */
  652. function parseCachedTable($code, $subpage='', $recursive=true) {
  653. global $wgMessageCache;
  654. static $parsed = array();
  655. if(!is_object($wgMessageCache))
  656. return array();
  657. $key = 'Conversiontable/'.$code;
  658. if($subpage)
  659. $key .= '/' . $subpage;
  660. if(array_key_exists($key, $parsed))
  661. return array();
  662. if ( strpos( $code, '/' ) === false ) {
  663. $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
  664. } else {
  665. $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
  666. if ( $title && $title->exists() ) {
  667. $article = new Article( $title );
  668. $txt = $article->getContents();
  669. } else {
  670. $txt = '';
  671. }
  672. }
  673. // get all subpage links of the form
  674. // [[MediaWiki:conversiontable/zh-xx/...|...]]
  675. $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
  676. $subs = explode('[[', $txt);
  677. $sublinks = array();
  678. foreach( $subs as $sub ) {
  679. $link = explode(']]', $sub, 2);
  680. if(count($link) != 2)
  681. continue;
  682. $b = explode('|', $link[0]);
  683. $b = explode('/', trim($b[0]), 3);
  684. if(count($b)==3)
  685. $sublink = $b[2];
  686. else
  687. $sublink = '';
  688. if($b[0] == $linkhead && $b[1] == $code) {
  689. $sublinks[] = $sublink;
  690. }
  691. }
  692. // parse the mappings in this page
  693. $blocks = explode($this->mMarkup['begin'], $txt);
  694. array_shift($blocks);
  695. $ret = array();
  696. foreach($blocks as $block) {
  697. $mappings = explode($this->mMarkup['end'], $block, 2);
  698. $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
  699. $table = explode( ';', $stripped );
  700. foreach( $table as $t ) {
  701. $m = explode( '=>', $t );
  702. if( count( $m ) != 2)
  703. continue;
  704. // trim any trailling comments starting with '//'
  705. $tt = explode('//', $m[1], 2);
  706. $ret[trim($m[0])] = trim($tt[0]);
  707. }
  708. }
  709. $parsed[$key] = true;
  710. // recursively parse the subpages
  711. if($recursive) {
  712. foreach($sublinks as $link) {
  713. $s = $this->parseCachedTable($code, $link, $recursive);
  714. $ret = array_merge($ret, $s);
  715. }
  716. }
  717. if ($this->mUcfirst) {
  718. foreach ($ret as $k => $v) {
  719. $ret[Language::ucfirst($k)] = Language::ucfirst($v);
  720. }
  721. }
  722. return $ret;
  723. }
  724. /**
  725. * Enclose a string with the "no conversion" tag. This is used by
  726. * various functions in the Parser
  727. *
  728. * @param string $text text to be tagged for no conversion
  729. * @return string the tagged text
  730. * @public
  731. */
  732. function markNoConversion($text, $noParse=false) {
  733. # don't mark if already marked
  734. if(strpos($text, $this->mMarkup['begin']) ||
  735. strpos($text, $this->mMarkup['end']))
  736. return $text;
  737. $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
  738. return $ret;
  739. }
  740. /**
  741. * convert the sorting key for category links. this should make different
  742. * keys that are variants of each other map to the same key
  743. */
  744. function convertCategoryKey( $key ) {
  745. return $key;
  746. }
  747. /**
  748. * hook to refresh the cache of conversion tables when
  749. * MediaWiki:conversiontable* is updated
  750. * @private
  751. */
  752. function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
  753. $titleobj = $article->getTitle();
  754. if($titleobj->getNamespace() == NS_MEDIAWIKI) {
  755. $title = $titleobj->getDBkey();
  756. $t = explode('/', $title, 3);
  757. $c = count($t);
  758. if( $c > 1 && $t[0] == 'Conversiontable' ) {
  759. if(in_array($t[1], $this->mVariants)) {
  760. $this->reloadTables();
  761. }
  762. }
  763. }
  764. return true;
  765. }
  766. /**
  767. * Armour rendered math against conversion
  768. * Wrap math into rawoutput -{R| math }- syntax
  769. * @public
  770. */
  771. function armourMath($text){
  772. $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
  773. return $ret;
  774. }
  775. }
  776. /**
  777. * parser for rules of language conversion , parse rules in -{ }- tag
  778. * @ingroup Language
  779. * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
  780. */
  781. class ConverterRule {
  782. var $mText; // original text in -{text}-
  783. var $mConverter; // LanguageConverter object
  784. var $mManualCodeError='<strong class="error">code error!</strong>';
  785. var $mRuleDisplay = '',$mRuleTitle=false;
  786. var $mRules = '';// string : the text of the rules
  787. var $mRulesAction = 'none';
  788. var $mFlags = array();
  789. var $mConvTable = array();
  790. var $mBidtable = array();// array of the translation in each variant
  791. var $mUnidtable = array();// array of the translation in each variant
  792. /**
  793. * Constructor
  794. *
  795. * @param string $text the text between -{ and }-
  796. * @param object $converter a LanguageConverter object
  797. * @access public
  798. */
  799. function __construct($text,$converter){
  800. $this->mText = $text;
  801. $this->mConverter=$converter;
  802. foreach($converter->mVariants as $v){
  803. $this->mConvTable[$v]=array();
  804. }
  805. }
  806. /**
  807. * check if variants array in convert array
  808. *
  809. * @param string $variant Variant language code
  810. * @return string Translated text
  811. * @public
  812. */
  813. function getTextInBidtable($variants){
  814. if(is_string($variants)){ $variants=array($variants); }
  815. if(!is_array($variants)) return false;
  816. foreach ($variants as $variant){
  817. if(array_key_exists($variant, $this->mBidtable)){
  818. return $this->mBidtable[$variant];
  819. }
  820. }
  821. return false;
  822. }
  823. /**
  824. * Parse flags with syntax -{FLAG| ... }-
  825. * @private
  826. */
  827. function parseFlags(){
  828. $text = $this->mText;
  829. if(strlen($text) < 2 ) {
  830. $this->mFlags = array( 'R' );
  831. $this->mRules = $text;
  832. return;
  833. }
  834. $flags = array();
  835. $markup = $this->mConverter->mMarkup;
  836. $validFlags = $this->mConverter->mFlags;
  837. $variants = $this->mConverter->mVariants;
  838. $tt = explode($markup['flagsep'], $text, 2);
  839. if(count($tt) == 2) {
  840. $f = explode($markup['varsep'], $tt[0]);
  841. foreach($f as $ff) {
  842. $ff = trim($ff);
  843. if(array_key_exists($ff, $validFlags) &&
  844. !in_array($validFlags[$ff], $flags))
  845. $flags[] = $validFlags[$ff];
  846. }
  847. $rules = $tt[1];
  848. } else {
  849. $rules = $text;
  850. }
  851. //check flags
  852. if( in_array('R',$flags) ){
  853. $flags = array('R');// remove other flags
  854. } elseif ( in_array('N',$flags) ){
  855. $flags = array('N');// remove other flags
  856. } elseif ( in_array('-',$flags) ){
  857. $flags = array('-');// remove other flags
  858. } elseif (count($flags)==1 && $flags[0]=='T'){
  859. $flags[]='H';
  860. } elseif ( in_array('H',$flags) ){
  861. // replace A flag, and remove other flags except T
  862. $temp=array('+','H');
  863. if(in_array('T',$flags)) $temp[] = 'T';
  864. if(in_array('D',$flags)) $temp[] = 'D';
  865. $flags = $temp;
  866. } else {
  867. if ( in_array('A',$flags) ) {
  868. $flags[]='+';
  869. $flags[]='S';
  870. }
  871. if ( in_array('D',$flags) )
  872. $flags=array_diff($flags,array('S'));
  873. $flags_temp = array();
  874. foreach ($variants as $variant) {
  875. // try to find flags like "zh-hans", "zh-hant"
  876. // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
  877. if ( in_array($variant, $flags) )
  878. $flags_temp[] = $variant;
  879. }
  880. if ( count($flags_temp) !== 0 )
  881. $flags = $flags_temp;
  882. }
  883. if ( count($flags) == 0 )
  884. $flags = array('S');
  885. $this->mRules=$rules;
  886. $this->mFlags=$flags;
  887. }
  888. /**
  889. * generate conversion table
  890. * @private
  891. */
  892. function parseRules() {
  893. $rules = $this->mRules;
  894. $flags = $this->mFlags;
  895. $bidtable = array();
  896. $unidtable = array();
  897. $markup = $this->mConverter->mMarkup;
  898. $variants = $this->mConverter->mVariants;
  899. // varsep_pattern for preg_split:
  900. // text should be splited by ";" only if a valid variant
  901. // name exist after the markup, for example:
  902. // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
  903. // we should split it as:
  904. // array(
  905. // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
  906. // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
  907. // [2] => ''
  908. // )
  909. $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
  910. foreach( $variants as $variant ) {
  911. $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
  912. $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
  913. . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
  914. }
  915. $varsep_pattern .= '\s*$)/';
  916. $choice = preg_split($varsep_pattern, $rules);
  917. foreach( $choice as $c ) {
  918. $v = explode($markup['codesep'], $c, 2);
  919. if( count($v) != 2 )
  920. continue;// syntax error, skip
  921. $to = trim($v[1]);
  922. $v = trim($v[0]);
  923. $u = explode($markup['unidsep'], $v);
  924. // if $to is empty, strtr() could return a wrong result
  925. if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
  926. $bidtable[$v] = $to;
  927. } else if(count($u) == 2){
  928. $from = trim($u[0]);
  929. $v = trim($u[1]);
  930. if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
  931. && $to && in_array( $v, $variants ) )
  932. $unidtable[$v] = array( $from=>$to );
  933. elseif ( $to && in_array( $v, $variants ) )
  934. $unidtable[$v][$from] = $to;
  935. }
  936. // syntax error, pass
  937. if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ){
  938. $bidtable = array();
  939. $unidtable = array();
  940. break;
  941. }
  942. }
  943. $this->mBidtable = $bidtable;
  944. $this->mUnidtable = $unidtable;
  945. }
  946. /**
  947. * @private
  948. */
  949. function getRulesDesc(){
  950. $codesep = $this->mConverter->mDescCodeSep;
  951. $varsep = $this->mConverter->mDescVarSep;
  952. $text='';
  953. foreach($this->mBidtable as $k => $v)
  954. $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
  955. foreach($this->mUnidtable as $k => $a)
  956. foreach($a as $from=>$to)
  957. $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
  958. return $text;
  959. }
  960. /**
  961. * Parse rules conversion
  962. * @private
  963. */
  964. function getRuleConvertedStr($variant,$doConvert){
  965. $bidtable = $this->mBidtable;
  966. $unidtable = $this->mUnidtable;
  967. if( count($bidtable) + count($unidtable) == 0 ){
  968. return $this->mRules;
  969. } elseif ($doConvert){// the text converted
  970. // display current variant in bidirectional array
  971. $disp = $this->getTextInBidtable($variant);
  972. // or display current variant in fallbacks
  973. if(!$disp)
  974. $disp = $this->getTextInBidtable(
  975. $this->mConverter->getVariantFallbacks($variant));
  976. // or display current variant in unidirectional array
  977. if(!$disp && array_key_exists($variant,$unidtable)){
  978. $disp = array_values($unidtable[$variant]);
  979. $disp = $disp[0];
  980. }
  981. // or display frist text under disable manual convert
  982. if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
  983. if(count($bidtable)>0){
  984. $disp = array_values($bidtable);
  985. $disp = $disp[0];
  986. } else {
  987. $disp = array_values($unidtable);
  988. $disp = array_values($disp[0]);
  989. $disp = $disp[0];
  990. }
  991. }
  992. return $disp;
  993. } else {// no convert
  994. return $this->mRules;
  995. }
  996. }
  997. /**
  998. * generate conversion table for all text
  999. * @private
  1000. */
  1001. function generateConvTable(){
  1002. $flags = $this->mFlags;
  1003. $bidtable = $this->mBidtable;
  1004. $unidtable = $this->mUnidtable;
  1005. $manLevel = $this->mConverter->mManualLevel;
  1006. $vmarked=array();
  1007. foreach($this->mConverter->mVariants as $v) {
  1008. /* for bidirectional array
  1009. fill in the missing variants, if any,
  1010. with fallbacks */
  1011. if(!array_key_exists($v, $bidtable)) {
  1012. $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
  1013. $vf = $this->getTextInBidtable($variantFallbacks);
  1014. if($vf) $bidtable[$v] = $vf;
  1015. }
  1016. if(array_key_exists($v,$bidtable)){
  1017. foreach($vmarked as $vo){
  1018. // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
  1019. // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
  1020. // to introduce a custom mapping between
  1021. // words WordZh and WordTw in the whole text
  1022. if($manLevel[$v]=='bidirectional'){
  1023. $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
  1024. }
  1025. if($manLevel[$vo]=='bidirectional'){
  1026. $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
  1027. }
  1028. }
  1029. $vmarked[]=$v;
  1030. }
  1031. /*for unidirectional array
  1032. fill to convert tables */
  1033. $allow_unid = $manLevel[$v]=='bidirectional'
  1034. || $manLevel[$v]=='unidirectional';
  1035. if($allow_unid && array_key_exists($v,$unidtable)){
  1036. $ct=$this->mConvTable[$v];
  1037. $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
  1038. }
  1039. }
  1040. }
  1041. /**
  1042. * Parse rules and flags
  1043. * @public
  1044. */
  1045. function parse($variant){
  1046. if(!$variant)
  1047. $variant = $this->mConverter->getPreferredVariant();
  1048. $variants = $this->mConverter->mVariants;
  1049. $this->parseFlags();
  1050. $flags = $this->mFlags;
  1051. // convert to specified variant
  1052. // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
  1053. if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
  1054. if ( in_array( $variant, $flags ) ) // check if current variant in flags
  1055. // then convert <text to convert> to current language
  1056. $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variant );
  1057. else { // if current variant no in flags,
  1058. // then we check its fallback variants.
  1059. $variantFallbacks = $this->mConverter->getVariantFallbacks($variant);
  1060. foreach ( $variantFallbacks as $variantFallback ) {
  1061. // if current variant's fallback exist in flags
  1062. if ( in_array( $variantFallback, $flags ) ) {
  1063. // then convert <text to convert> to fallback language
  1064. $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variantFallback );
  1065. break;
  1066. }
  1067. }
  1068. }
  1069. $this->mFlags = $flags = array('R');
  1070. }
  1071. if( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
  1072. // decode => HTML entities modified by Sanitizer::removeHTMLtags
  1073. $this->mRules = str_replace('=&gt;','=>',$this->mRules);
  1074. $this->parseRules();
  1075. }
  1076. $rules = $this->mRules;
  1077. if( count( $this->mBidtable ) == 0 && count( $this->mUnidtable ) == 0 ){
  1078. if(in_array('+',$flags) || in_array('-',$flags))
  1079. // fill all variants if text in -{A/H/-|text} without rules
  1080. foreach($this->mConverter->mVariants as $v)
  1081. $this->mBidtable[$v] = $rules;
  1082. elseif (!in_array('N',$flags) && !in_array('T',$flags) )
  1083. $this->mFlags = $flags = array('R');
  1084. }
  1085. if( in_array('R',$flags) ) {
  1086. // if we don't do content convert, still strip the -{}- tags
  1087. $this->mRuleDisplay = $rules;
  1088. } elseif ( in_array('N',$flags) ){
  1089. // proces N flag: output current variant name
  1090. $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
  1091. } elseif ( in_array('D',$flags) ){
  1092. // proces D flag: output rules description
  1093. $this->mRuleDisplay = $this->getRulesDesc();
  1094. } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
  1095. // proces H,- flag or T only: output nothing
  1096. $this->mRuleDisplay = '';
  1097. } elseif ( in_array('S',$flags) ){
  1098. $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
  1099. $this->mConverter->mDoContentConvert);
  1100. } else {
  1101. $this->mRuleDisplay= $this->mManualCodeError;
  1102. }
  1103. // proces T flag
  1104. if ( in_array('T',$flags) ) {
  1105. $this->mRuleTitle = $this->getRuleConvertedStr($variant,
  1106. $this->mConverter->mDoTitleConvert);
  1107. }
  1108. if (in_array('-', $flags))
  1109. $this->mRulesAction='remove';
  1110. if (in_array('+', $flags))
  1111. $this->mRulesAction='add';
  1112. $this->generateConvTable();
  1113. }
  1114. /**
  1115. * @public
  1116. */
  1117. function hasRules(){
  1118. // TODO:
  1119. }
  1120. /**
  1121. * get display text on markup -{...}-
  1122. * @public
  1123. */
  1124. function getDisplay(){
  1125. return $this->mRuleDisplay;
  1126. }
  1127. /**
  1128. * get converted title
  1129. * @public
  1130. */
  1131. function getTitle(){
  1132. return $this->mRuleTitle;
  1133. }
  1134. /**
  1135. * return how deal with conversion rules
  1136. * @public
  1137. */
  1138. function getRulesAction(){
  1139. return $this->mRulesAction;
  1140. }
  1141. /**
  1142. * get conversion table ( bidirectional and unidirectional conversion table )
  1143. * @public
  1144. */
  1145. function getConvTable(){
  1146. return $this->mConvTable;
  1147. }
  1148. /**
  1149. * get conversion rules string
  1150. * @public
  1151. */
  1152. function getRules(){
  1153. return $this->mRules;
  1154. }
  1155. /**
  1156. * get conversion flags
  1157. * @public
  1158. */
  1159. function getFlags(){
  1160. return $this->mFlags;
  1161. }
  1162. }