From c1f9b1f7b1b77776192048005dcc66dcf3df2bfb Mon Sep 17 00:00:00 2001 From: Pierre Schmitz Date: Sat, 27 Dec 2014 15:41:37 +0100 Subject: Update to MediaWiki 1.24.1 --- includes/cache/LocalisationCache.php | 571 ++++++++++++++++++++--------------- 1 file changed, 330 insertions(+), 241 deletions(-) (limited to 'includes/cache/LocalisationCache.php') diff --git a/includes/cache/LocalisationCache.php b/includes/cache/LocalisationCache.php index 25a1e196..ae27fba3 100644 --- a/includes/cache/LocalisationCache.php +++ b/includes/cache/LocalisationCache.php @@ -20,8 +20,6 @@ * @file */ -define( 'MW_LC_VERSION', 2 ); - /** * Class for caching the contents of localisation files, Messages*.php * and *.i18n.php. @@ -35,20 +33,22 @@ define( 'MW_LC_VERSION', 2 ); * as grammatical transformation, is done by the caller. */ class LocalisationCache { + const VERSION = 2; + /** Configuration associative array */ - var $conf; + private $conf; /** * True if recaching should only be done on an explicit call to recache(). * Setting this reduces the overhead of cache freshness checking, which * requires doing a stat() for every extension i18n file. */ - var $manualRecache = false; + private $manualRecache = false; /** * True to treat all files as expired until they are regenerated by this object. */ - var $forceRecache = false; + private $forceRecache = false; /** * The cache data. 3-d array, where the first key is the language code, @@ -56,14 +56,14 @@ class LocalisationCache { * an item specific subkey index. Some items are not arrays and so for those * items, there are no subkeys. */ - var $data = array(); + protected $data = array(); /** * The persistent store object. An instance of LCStore. * * @var LCStore */ - var $store; + private $store; /** * A 2-d associative array, code/key, where presence indicates that the item @@ -72,32 +72,32 @@ class LocalisationCache { * For split items, if set, this indicates that all of the subitems have been * loaded. */ - var $loadedItems = array(); + private $loadedItems = array(); /** * A 3-d associative array, code/key/subkey, where presence indicates that * the subitem is loaded. Only used for the split items, i.e. messages. */ - var $loadedSubitems = array(); + private $loadedSubitems = array(); /** * An array where presence of a key indicates that that language has been * initialised. Initialisation includes checking for cache expiry and doing * any necessary updates. */ - var $initialisedLangs = array(); + private $initialisedLangs = array(); /** * An array mapping non-existent pseudo-languages to fallback languages. This * is filled by initShallowFallback() when data is requested from a language * that lacks a Messages*.php file. */ - var $shallowFallbacks = array(); + private $shallowFallbacks = array(); /** * An array where the keys are codes that have been recached by this instance. */ - var $recachedLangs = array(); + private $recachedLangs = array(); /** * All item keys @@ -106,7 +106,7 @@ class LocalisationCache { 'fallback', 'namespaceNames', 'bookstoreList', 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable', 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension', - 'linkTrail', 'namespaceAliases', + 'linkTrail', 'linkPrefixCharset', 'namespaceAliases', 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap', 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases', 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases', @@ -158,7 +158,7 @@ class LocalisationCache { * Associative array of cached plural rules. The key is the language code, * the value is an array of plural rules for that language. */ - var $pluralRules = null; + private $pluralRules = null; /** * Associative array of cached plural rule types. The key is the language @@ -172,16 +172,16 @@ class LocalisationCache { * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}. */ - var $pluralRuleTypes = null; + private $pluralRuleTypes = null; - var $mergeableKeys = null; + private $mergeableKeys = null; /** * Constructor. * For constructor parameters, see the documentation in DefaultSettings.php * for $wgLocalisationCacheConf. * - * @param $conf Array + * @param array $conf * @throws MWException */ function __construct( $conf ) { @@ -195,16 +195,13 @@ class LocalisationCache { switch ( $conf['store'] ) { case 'files': case 'file': - $storeClass = 'LCStore_CDB'; + $storeClass = 'LCStoreCDB'; break; case 'db': - $storeClass = 'LCStore_DB'; - break; - case 'accel': - $storeClass = 'LCStore_Accel'; + $storeClass = 'LCStoreDB'; break; case 'detect': - $storeClass = $wgCacheDirectory ? 'LCStore_CDB' : 'LCStore_DB'; + $storeClass = $wgCacheDirectory ? 'LCStoreCDB' : 'LCStoreDB'; break; default: throw new MWException( @@ -212,7 +209,7 @@ class LocalisationCache { } } - wfDebug( get_class( $this ) . ": using store $storeClass\n" ); + wfDebugLog( 'caches', get_class( $this ) . ": using store $storeClass" ); if ( !empty( $conf['storeDirectory'] ) ) { $storeConf['directory'] = $conf['storeDirectory']; } @@ -228,7 +225,7 @@ class LocalisationCache { /** * Returns true if the given key is mergeable, that is, if it is an associative * array which can be merged through a fallback sequence. - * @param $key + * @param string $key * @return bool */ public function isMergeableKey( $key ) { @@ -241,6 +238,7 @@ class LocalisationCache { self::$magicWordKeys ) ); } + return isset( $this->mergeableKeys[$key] ); } @@ -249,8 +247,8 @@ class LocalisationCache { * * Warning: this may be slow for split items (messages), since it will * need to fetch all of the subitems from the cache individually. - * @param $code - * @param $key + * @param string $code + * @param string $key * @return mixed */ public function getItem( $code, $key ) { @@ -269,14 +267,15 @@ class LocalisationCache { /** * Get a subitem, for instance a single message for a given language. - * @param $code - * @param $key - * @param $subkey - * @return null + * @param string $code + * @param string $key + * @param string $subkey + * @return mixed|null */ public function getSubitem( $code, $key, $subkey ) { if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) && - !isset( $this->loadedItems[$code][$key] ) ) { + !isset( $this->loadedItems[$code][$key] ) + ) { wfProfileIn( __METHOD__ . '-load' ); $this->loadSubitem( $code, $key, $subkey ); wfProfileOut( __METHOD__ . '-load' ); @@ -297,8 +296,8 @@ class LocalisationCache { * * Will return null if the item is not found, or false if the item is not an * array. - * @param $code - * @param $key + * @param string $code + * @param string $key * @return bool|null|string */ public function getSubitemList( $code, $key ) { @@ -316,8 +315,8 @@ class LocalisationCache { /** * Load an item into the cache. - * @param $code - * @param $key + * @param string $code + * @param string $key */ protected function loadItem( $code, $key ) { if ( !isset( $this->initialisedLangs[$code] ) ) { @@ -331,6 +330,7 @@ class LocalisationCache { if ( isset( $this->shallowFallbacks[$code] ) ) { $this->loadItem( $this->shallowFallbacks[$code], $key ); + return; } @@ -351,13 +351,14 @@ class LocalisationCache { /** * Load a subitem into the cache - * @param $code - * @param $key - * @param $subkey + * @param string $code + * @param string $key + * @param string $subkey */ protected function loadSubitem( $code, $key, $subkey ) { if ( !in_array( $key, self::$splitKeys ) ) { $this->loadItem( $code, $key ); + return; } @@ -367,12 +368,14 @@ class LocalisationCache { // Check to see if initLanguage() loaded it for us if ( isset( $this->loadedItems[$code][$key] ) || - isset( $this->loadedSubitems[$code][$key][$subkey] ) ) { + isset( $this->loadedSubitems[$code][$key][$subkey] ) + ) { return; } if ( isset( $this->shallowFallbacks[$code] ) ) { $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey ); + return; } @@ -391,15 +394,17 @@ class LocalisationCache { public function isExpired( $code ) { if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) { wfDebug( __METHOD__ . "($code): forced reload\n" ); + return true; } $deps = $this->store->get( $code, 'deps' ); $keys = $this->store->get( $code, 'list' ); $preload = $this->store->get( $code, 'preload' ); - // Different keys may expire separately, at least in LCStore_Accel + // Different keys may expire separately for some stores if ( $deps === null || $keys === null || $preload === null ) { wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" ); + return true; } @@ -411,6 +416,7 @@ class LocalisationCache { if ( !$dep instanceof CacheDependency || $dep->isExpired() ) { wfDebug( __METHOD__ . "($code): cache for $code expired due to " . get_class( $dep ) . "\n" ); + return true; } } @@ -420,7 +426,7 @@ class LocalisationCache { /** * Initialise a language in this object. Rebuild the cache if necessary. - * @param $code + * @param string $code * @throws MWException */ protected function initLanguage( $code ) { @@ -433,18 +439,20 @@ class LocalisationCache { # If the code is of the wrong form for a Messages*.php file, do a shallow fallback if ( !Language::isValidBuiltInCode( $code ) ) { $this->initShallowFallback( $code, 'en' ); + return; } # Recache the data if necessary if ( !$this->manualRecache && $this->isExpired( $code ) ) { - if ( file_exists( Language::getMessagesFileName( $code ) ) ) { + if ( Language::isSupportedLanguage( $code ) ) { $this->recache( $code ); } elseif ( $code === 'en' ) { throw new MWException( 'MessagesEn.php is missing.' ); } else { $this->initShallowFallback( $code, 'en' ); } + return; } @@ -458,6 +466,7 @@ class LocalisationCache { 'Please run maintenance/rebuildLocalisationCache.php.' ); } $this->initShallowFallback( $code, 'en' ); + return; } else { throw new MWException( 'Invalid or missing localisation cache.' ); @@ -478,8 +487,8 @@ class LocalisationCache { /** * Create a fallback from one language to another, without creating a * complete persistent cache. - * @param $primaryCode - * @param $fallbackCode + * @param string $primaryCode + * @param string $fallbackCode */ public function initShallowFallback( $primaryCode, $fallbackCode ) { $this->data[$primaryCode] =& $this->data[$fallbackCode]; @@ -490,17 +499,23 @@ class LocalisationCache { /** * Read a PHP file containing localisation data. - * @param $_fileName - * @param $_fileType + * @param string $_fileName + * @param string $_fileType * @throws MWException * @return array */ protected function readPHPFile( $_fileName, $_fileType ) { wfProfileIn( __METHOD__ ); // Disable APC caching + wfSuppressWarnings(); $_apcEnabled = ini_set( 'apc.cache_by_default', '0' ); + wfRestoreWarnings(); + include $_fileName; + + wfSuppressWarnings(); ini_set( 'apc.cache_by_default', $_apcEnabled ); + wfRestoreWarnings(); if ( $_fileType == 'core' || $_fileType == 'extension' ) { $data = compact( self::$allKeys ); @@ -511,12 +526,57 @@ class LocalisationCache { throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" ); } wfProfileOut( __METHOD__ ); + return $data; } + /** + * Read a JSON file containing localisation messages. + * @param string $fileName Name of file to read + * @throws MWException If there is a syntax error in the JSON file + * @return array Array with a 'messages' key, or empty array if the file doesn't exist + */ + public function readJSONFile( $fileName ) { + wfProfileIn( __METHOD__ ); + + if ( !is_readable( $fileName ) ) { + wfProfileOut( __METHOD__ ); + + return array(); + } + + $json = file_get_contents( $fileName ); + if ( $json === false ) { + wfProfileOut( __METHOD__ ); + + return array(); + } + + $data = FormatJson::decode( $json, true ); + if ( $data === null ) { + wfProfileOut( __METHOD__ ); + + throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" ); + } + + // Remove keys starting with '@', they're reserved for metadata and non-message data + foreach ( $data as $key => $unused ) { + if ( $key === '' || $key[0] === '@' ) { + unset( $data[$key] ); + } + } + + wfProfileOut( __METHOD__ ); + + // The JSON format only supports messages, none of the other variables, so wrap the data + return array( 'messages' => $data ); + } + /** * Get the compiled plural rules for a given language from the XML files. * @since 1.20 + * @param string $code + * @return array|null */ public function getCompiledPluralRules( $code ) { $rules = $this->getPluralRules( $code ); @@ -526,9 +586,11 @@ class LocalisationCache { try { $compiledRules = CLDRPluralRuleEvaluator::compile( $rules ); } catch ( CLDRPluralRuleError $e ) { - wfDebugLog( 'l10n', $e->getMessage() . "\n" ); + wfDebugLog( 'l10n', $e->getMessage() ); + return array(); } + return $compiledRules; } @@ -536,6 +598,8 @@ class LocalisationCache { * Get the plural rules for a given language from the XML files. * Cached. * @since 1.20 + * @param string $code + * @return array|null */ public function getPluralRules( $code ) { if ( $this->pluralRules === null ) { @@ -552,6 +616,8 @@ class LocalisationCache { * Get the plural rule types for a given language from the XML files. * Cached. * @since 1.22 + * @param string $code + * @return array|null */ public function getPluralRuleTypes( $code ) { if ( $this->pluralRuleTypes === null ) { @@ -582,6 +648,8 @@ class LocalisationCache { /** * Load a plural XML file with the given filename, compile the relevant * rules, and save the compiled rules in a process-local cache. + * + * @param string $fileName */ protected function loadPluralFile( $fileName ) { $doc = new DOMDocument; @@ -612,20 +680,24 @@ class LocalisationCache { * Read the data from the source files for a given language, and register * the relevant dependencies in the $deps array. If the localisation * exists, the data array is returned, otherwise false is returned. + * + * @param string $code + * @param array $deps + * @return array */ protected function readSourceFilesAndRegisterDeps( $code, &$deps ) { global $IP; wfProfileIn( __METHOD__ ); + // This reads in the PHP i18n file with non-messages l10n data $fileName = Language::getMessagesFileName( $code ); if ( !file_exists( $fileName ) ) { - wfProfileOut( __METHOD__ ); - return false; + $data = array(); + } else { + $deps[] = new FileDependency( $fileName ); + $data = $this->readPHPFile( $fileName, 'core' ); } - $deps[] = new FileDependency( $fileName ); - $data = $this->readPHPFile( $fileName, 'core' ); - # Load CLDR plural rules for JavaScript $data['pluralRules'] = $this->getPluralRules( $code ); # And for PHP @@ -637,15 +709,16 @@ class LocalisationCache { $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" ); wfProfileOut( __METHOD__ ); + return $data; } /** * Merge two localisation values, a primary and a fallback, overwriting the * primary value in place. - * @param $key - * @param $value - * @param $fallbackValue + * @param string $key + * @param mixed $value + * @param mixed $fallbackValue */ protected function mergeItem( $key, &$value, $fallbackValue ) { if ( !is_null( $value ) ) { @@ -674,8 +747,8 @@ class LocalisationCache { } /** - * @param $value - * @param $fallbackValue + * @param mixed $value + * @param mixed $fallbackValue */ protected function mergeMagicWords( &$value, $fallbackValue ) { foreach ( $fallbackValue as $magicName => $fallbackInfo ) { @@ -698,10 +771,10 @@ class LocalisationCache { * * Returns true if any data from the extension array was used, false * otherwise. - * @param $codeSequence - * @param $key - * @param $value - * @param $fallbackValue + * @param array $codeSequence + * @param string $key + * @param mixed $value + * @param mixed $fallbackValue * @return bool */ protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) { @@ -719,11 +792,11 @@ class LocalisationCache { /** * Load localisation data for a given language for both core and extensions * and save it to the persistent cache store and the process cache - * @param $code + * @param string $code * @throws MWException */ public function recache( $code ) { - global $wgExtensionMessagesFiles; + global $wgExtensionMessagesFiles, $wgMessagesDirs; wfProfileIn( __METHOD__ ); if ( !$code ) { @@ -751,7 +824,6 @@ class LocalisationCache { foreach ( $data as $key => $value ) { $this->mergeItem( $key, $coreData[$key], $value ); } - } # Fill in the fallback if it's not there already @@ -768,43 +840,31 @@ class LocalisationCache { if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) { $coreData['fallbackSequence'][] = 'en'; } + } - # Load the fallback localisation item by item and merge it - foreach ( $coreData['fallbackSequence'] as $fbCode ) { - # Load the secondary localisation from the source file to - # avoid infinite cycles on cyclic fallbacks - $fbData = $this->readSourceFilesAndRegisterDeps( $fbCode, $deps ); - if ( $fbData === false ) { - continue; - } + $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] ); - foreach ( self::$allKeys as $key ) { - if ( !isset( $fbData[$key] ) ) { - continue; - } + wfProfileIn( __METHOD__ . '-fallbacks' ); - if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) { - $this->mergeItem( $key, $coreData[$key], $fbData[$key] ); - } - } + # Load non-JSON localisation data for extensions + $extensionData = array_combine( + $codeSequence, + array_fill( 0, count( $codeSequence ), $initialData ) ); + foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) { + if ( isset( $wgMessagesDirs[$extension] ) ) { + # This extension has JSON message data; skip the PHP shim + continue; } - } - $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] ); - - # Load the extension localisations - # This is done after the core because we know the fallback sequence now. - # But it has a higher precedence for merging so that we can support things - # like site-specific message overrides. - wfProfileIn( __METHOD__ . '-extensions' ); - $allData = $initialData; - foreach ( $wgExtensionMessagesFiles as $fileName ) { $data = $this->readPHPFile( $fileName, 'extension' ); $used = false; foreach ( $data as $key => $item ) { - if ( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) { - $used = true; + foreach ( $codeSequence as $csCode ) { + if ( isset( $item[$csCode] ) ) { + $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] ); + $used = true; + } } } @@ -813,15 +873,81 @@ class LocalisationCache { } } - # Merge core data into extension data - foreach ( $coreData as $key => $item ) { - $this->mergeItem( $key, $allData[$key], $item ); + # Load the localisation data for each fallback, then merge it into the full array + $allData = $initialData; + foreach ( $codeSequence as $csCode ) { + $csData = $initialData; + + # Load core messages and the extension localisations. + foreach ( $wgMessagesDirs as $dirs ) { + foreach ( (array)$dirs as $dir ) { + $fileName = "$dir/$csCode.json"; + $data = $this->readJSONFile( $fileName ); + + foreach ( $data as $key => $item ) { + $this->mergeItem( $key, $csData[$key], $item ); + } + + $deps[] = new FileDependency( $fileName ); + } + } + + # Merge non-JSON extension data + if ( isset( $extensionData[$csCode] ) ) { + foreach ( $extensionData[$csCode] as $key => $item ) { + $this->mergeItem( $key, $csData[$key], $item ); + } + } + + if ( $csCode === $code ) { + # Merge core data into extension data + foreach ( $coreData as $key => $item ) { + $this->mergeItem( $key, $csData[$key], $item ); + } + } else { + # Load the secondary localisation from the source file to + # avoid infinite cycles on cyclic fallbacks + $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps ); + if ( $fbData !== false ) { + # Only merge the keys that make sense to merge + foreach ( self::$allKeys as $key ) { + if ( !isset( $fbData[$key] ) ) { + continue; + } + + if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) { + $this->mergeItem( $key, $csData[$key], $fbData[$key] ); + } + } + } + } + + # Allow extensions an opportunity to adjust the data for this + # fallback + wfRunHooks( 'LocalisationCacheRecacheFallback', array( $this, $csCode, &$csData ) ); + + # Merge the data for this fallback into the final array + if ( $csCode === $code ) { + $allData = $csData; + } else { + foreach ( self::$allKeys as $key ) { + if ( !isset( $csData[$key] ) ) { + continue; + } + + if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) { + $this->mergeItem( $key, $allData[$key], $csData[$key] ); + } + } + } } - wfProfileOut( __METHOD__ . '-extensions' ); + + wfProfileOut( __METHOD__ . '-fallbacks' ); # Add cache dependencies for any referenced globals $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' ); - $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' ); + $deps['wgMessagesDirs'] = new GlobalDependency( 'wgMessagesDirs' ); + $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' ); # Add dependencies to the cache entry $allData['deps'] = $deps; @@ -854,7 +980,8 @@ class LocalisationCache { $allData['list'][$key] = array_keys( $allData[$key] ); } # Run hooks - wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) ); + $purgeBlobs = true; + wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData, &$purgeBlobs ) ); if ( is_null( $allData['namespaceNames'] ) ) { wfProfileOut( __METHOD__ ); @@ -889,8 +1016,8 @@ class LocalisationCache { # Clear out the MessageBlobStore # HACK: If using a null (i.e. disabled) storage backend, we # can't write to the MessageBlobStore either - if ( !$this->store instanceof LCStore_Null ) { - MessageBlobStore::clear(); + if ( $purgeBlobs && !$this->store instanceof LCStoreNull ) { + MessageBlobStore::getInstance()->clear(); } wfProfileOut( __METHOD__ ); @@ -901,7 +1028,7 @@ class LocalisationCache { * * The preload item will be loaded automatically, improving performance * for the commonly-requested items it contains. - * @param $data + * @param array $data * @return array */ protected function buildPreload( $data ) { @@ -925,7 +1052,7 @@ class LocalisationCache { /** * Unload the data for a given language from the object cache. * Reduces memory usage. - * @param $code + * @param string $code */ public function unload( $code ) { unset( $this->data[$code] ); @@ -954,28 +1081,9 @@ class LocalisationCache { * Disable the storage backend */ public function disableBackend() { - $this->store = new LCStore_Null; + $this->store = new LCStoreNull; $this->manualRecache = false; } - - /** - * Return an array with initialised languages. - * - * @return array - */ - public function getInitialisedLanguages() { - return $this->initialisedLangs; - } - - /** - * Set initialised languages. - * - * @param array $languages Optional array of initialised languages. - */ - public function setInitialisedLanguages( $languages = array() ) { - $this->initialisedLangs = $languages; - } - } /** @@ -1023,69 +1131,20 @@ interface LCStore { function set( $key, $value ); } -/** - * LCStore implementation which uses PHP accelerator to store data. - * This will work if one of XCache, WinCache or APC cacher is configured. - * (See ObjectCache.php) - */ -class LCStore_Accel implements LCStore { - var $currentLang; - var $keys; - - public function __construct() { - $this->cache = wfGetCache( CACHE_ACCEL ); - } - - public function get( $code, $key ) { - $k = wfMemcKey( 'l10n', $code, 'k', $key ); - $r = $this->cache->get( $k ); - return $r === false ? null : $r; - } - - public function startWrite( $code ) { - $k = wfMemcKey( 'l10n', $code, 'l' ); - $keys = $this->cache->get( $k ); - if ( $keys ) { - foreach ( $keys as $k ) { - $this->cache->delete( $k ); - } - } - $this->currentLang = $code; - $this->keys = array(); - } - - public function finishWrite() { - if ( $this->currentLang ) { - $k = wfMemcKey( 'l10n', $this->currentLang, 'l' ); - $this->cache->set( $k, array_keys( $this->keys ) ); - } - $this->currentLang = null; - $this->keys = array(); - } - - public function set( $key, $value ) { - if ( $this->currentLang ) { - $k = wfMemcKey( 'l10n', $this->currentLang, 'k', $key ); - $this->keys[$k] = true; - $this->cache->set( $k, $value ); - } - } -} - /** * LCStore implementation which uses the standard DB functions to store data. * This will work on any MediaWiki installation. */ -class LCStore_DB implements LCStore { - var $currentLang; - var $writesDone = false; +class LCStoreDB implements LCStore { + private $currentLang; + private $writesDone = false; - /** - * @var DatabaseBase - */ - var $dbw; - var $batch; - var $readOnly = false; + /** @var DatabaseBase */ + private $dbw; + /** @var array */ + private $batch = array(); + + private $readOnly = false; public function get( $code, $key ) { if ( $this->writesDone ) { @@ -1096,7 +1155,7 @@ class LCStore_DB implements LCStore { $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ), array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ ); if ( $row ) { - return unserialize( $row->lc_value ); + return unserialize( $db->decodeBlob( $row->lc_value ) ); } else { return null; } @@ -1105,25 +1164,11 @@ class LCStore_DB implements LCStore { public function startWrite( $code ) { if ( $this->readOnly ) { return; - } - - if ( !$code ) { + } elseif ( !$code ) { throw new MWException( __METHOD__ . ": Invalid language \"$code\"" ); } $this->dbw = wfGetDB( DB_MASTER ); - try { - $this->dbw->begin( __METHOD__ ); - $this->dbw->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__ ); - } catch ( DBQueryError $e ) { - if ( $this->dbw->wasReadOnlyError() ) { - $this->readOnly = true; - $this->dbw->rollback( __METHOD__ ); - return; - } else { - throw $e; - } - } $this->currentLang = $code; $this->batch = array(); @@ -1132,37 +1177,42 @@ class LCStore_DB implements LCStore { public function finishWrite() { if ( $this->readOnly ) { return; + } elseif ( is_null( $this->currentLang ) ) { + throw new MWException( __CLASS__ . ': must call startWrite() before finishWrite()' ); } - if ( $this->batch ) { - $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ ); + $this->dbw->begin( __METHOD__ ); + try { + $this->dbw->delete( 'l10n_cache', + array( 'lc_lang' => $this->currentLang ), __METHOD__ ); + foreach ( array_chunk( $this->batch, 500 ) as $rows ) { + $this->dbw->insert( 'l10n_cache', $rows, __METHOD__ ); + } + $this->writesDone = true; + } catch ( DBQueryError $e ) { + if ( $this->dbw->wasReadOnlyError() ) { + $this->readOnly = true; // just avoid site down time + } else { + throw $e; + } } - $this->dbw->commit( __METHOD__ ); + $this->currentLang = null; - $this->dbw = null; $this->batch = array(); - $this->writesDone = true; } public function set( $key, $value ) { if ( $this->readOnly ) { return; - } - - if ( is_null( $this->currentLang ) ) { - throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' ); + } elseif ( is_null( $this->currentLang ) ) { + throw new MWException( __CLASS__ . ': must call startWrite() before set()' ); } $this->batch[] = array( 'lc_lang' => $this->currentLang, 'lc_key' => $key, - 'lc_value' => serialize( $value ) ); - - if ( count( $this->batch ) >= 100 ) { - $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ ); - $this->batch = array(); - } + 'lc_value' => $this->dbw->encodeBlob( serialize( $value ) ) ); } } @@ -1178,8 +1228,18 @@ class LCStore_DB implements LCStore { * * See Cdb.php and http://cr.yp.to/cdb.html */ -class LCStore_CDB implements LCStore { - var $readers, $writer, $currentLang, $directory; +class LCStoreCDB implements LCStore { + /** @var CdbReader[] */ + private $readers; + + /** @var CdbWriter */ + private $writer; + + /** @var string Current language code */ + private $currentLang; + + /** @var bool|string Cache directory. False if not set */ + private $directory; function __construct( $conf = array() ) { global $wgCacheDirectory; @@ -1195,21 +1255,30 @@ class LCStore_CDB implements LCStore { if ( !isset( $this->readers[$code] ) ) { $fileName = $this->getFileName( $code ); - if ( !file_exists( $fileName ) ) { - $this->readers[$code] = false; - } else { - $this->readers[$code] = CdbReader::open( $fileName ); + $this->readers[$code] = false; + if ( file_exists( $fileName ) ) { + try { + $this->readers[$code] = CdbReader::open( $fileName ); + } catch ( CdbException $e ) { + wfDebug( __METHOD__ . ": unable to open cdb file for reading\n" ); + } } } if ( !$this->readers[$code] ) { return null; } else { - $value = $this->readers[$code]->get( $key ); - + $value = false; + try { + $value = $this->readers[$code]->get( $key ); + } catch ( CdbException $e ) { + wfDebug( __METHOD__ . ": CdbException caught, error message was " + . $e->getMessage() . "\n" ); + } if ( $value === false ) { return null; } + return unserialize( $value ); } } @@ -1227,13 +1296,21 @@ class LCStore_CDB implements LCStore { $this->readers[$code]->close(); } - $this->writer = CdbWriter::open( $this->getFileName( $code ) ); + try { + $this->writer = CdbWriter::open( $this->getFileName( $code ) ); + } catch ( CdbException $e ) { + throw new MWException( $e->getMessage() ); + } $this->currentLang = $code; } public function finishWrite() { // Close the writer - $this->writer->close(); + try { + $this->writer->close(); + } catch ( CdbException $e ) { + throw new MWException( $e->getMessage() ); + } $this->writer = null; unset( $this->readers[$this->currentLang] ); $this->currentLang = null; @@ -1243,13 +1320,18 @@ class LCStore_CDB implements LCStore { if ( is_null( $this->writer ) ) { throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' ); } - $this->writer->set( $key, serialize( $value ) ); + try { + $this->writer->set( $key, serialize( $value ) ); + } catch ( CdbException $e ) { + throw new MWException( $e->getMessage() ); + } } protected function getFileName( $code ) { if ( strval( $code ) === '' || strpos( $code, '/' ) !== false ) { throw new MWException( __METHOD__ . ": Invalid language \"$code\"" ); } + return "{$this->directory}/l10n_cache-$code.cdb"; } } @@ -1257,42 +1339,47 @@ class LCStore_CDB implements LCStore { /** * Null store backend, used to avoid DB errors during install */ -class LCStore_Null implements LCStore { +class LCStoreNull implements LCStore { public function get( $code, $key ) { return null; } - public function startWrite( $code ) {} - public function finishWrite() {} - public function set( $key, $value ) {} + public function startWrite( $code ) { + } + + public function finishWrite() { + } + + public function set( $key, $value ) { + } } /** * A localisation cache optimised for loading large amounts of data for many * languages. Used by rebuildLocalisationCache.php. */ -class LocalisationCache_BulkLoad extends LocalisationCache { +class LocalisationCacheBulkLoad extends LocalisationCache { /** * A cache of the contents of data files. * Core files are serialized to avoid using ~1GB of RAM during a recache. */ - var $fileCache = array(); + private $fileCache = array(); /** * Most recently used languages. Uses the linked-list aspect of PHP hashtables * to keep the most recently used language codes at the end of the array, and * the language codes that are ready to be deleted at the beginning. */ - var $mruLangs = array(); + private $mruLangs = array(); /** * Maximum number of languages that may be loaded into $this->data */ - var $maxLoadedLangs = 10; + private $maxLoadedLangs = 10; /** - * @param $fileName - * @param $fileType + * @param string $fileName + * @param string $fileType * @return array|mixed */ protected function readPHPFile( $fileName, $fileType ) { @@ -1317,30 +1404,32 @@ class LocalisationCache_BulkLoad extends LocalisationCache { } /** - * @param $code - * @param $key + * @param string $code + * @param string $key * @return mixed */ public function getItem( $code, $key ) { unset( $this->mruLangs[$code] ); $this->mruLangs[$code] = true; + return parent::getItem( $code, $key ); } /** - * @param $code - * @param $key - * @param $subkey - * @return + * @param string $code + * @param string $key + * @param string $subkey + * @return mixed */ public function getSubitem( $code, $key, $subkey ) { unset( $this->mruLangs[$code] ); $this->mruLangs[$code] = true; + return parent::getSubitem( $code, $key, $subkey ); } /** - * @param $code + * @param string $code */ public function recache( $code ) { parent::recache( $code ); @@ -1350,7 +1439,7 @@ class LocalisationCache_BulkLoad extends LocalisationCache { } /** - * @param $code + * @param string $code */ public function unload( $code ) { unset( $this->mruLangs[$code] ); -- cgit v1.2.2