3 * Resource message blobs storage used by ResourceLoader.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
26 * This class provides access to the resource message blobs storage used
29 * A message blob is a JSON object containing the interface messages for a
30 * certain resource in a certain language. These message blobs are cached
31 * in the msg_resource table and automatically invalidated when one of their
32 * constituent messages or the resource itself is changed.
34 class MessageBlobStore
{
36 * In-process cache for message blobs.
38 * Keyed by language code, then module name.
42 protected $blobCache = array();
44 /* @var ResourceLoader */
45 protected $resourceloader;
48 * @param ResourceLoader $resourceloader
50 public function __construct( ResourceLoader
$resourceloader = null ) {
51 $this->resourceloader
= $resourceloader;
55 * Get the message blobs for a set of modules
57 * @param ResourceLoader $resourceLoader
58 * @param array $modules Array of module objects keyed by module name
59 * @param string $lang Language code
60 * @return array An array mapping module names to message blobs
62 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
63 if ( !count( $modules ) ) {
69 // Try in-process cache
70 $missingFromCache = array();
71 foreach ( $modules as $name => $module ) {
72 if ( isset( $this->blobCache
[$lang][$name] ) ) {
73 $blobs[$name] = $this->blobCache
[$lang][$name];
75 $missingFromCache[] = $name;
80 if ( $missingFromCache ) {
81 $blobs +
= $this->getFromDB( $resourceLoader, $missingFromCache, $lang );
84 // Generate new blobs for any remaining modules and store in DB
85 $missingFromDb = array_diff( array_keys( $modules ), array_keys( $blobs ) );
86 foreach ( $missingFromDb as $name ) {
87 $blob = $this->insertMessageBlob( $name, $modules[$name], $lang );
89 $blobs[$name] = $blob;
93 // Update in-process cache
94 if ( isset( $this->blobCache
[$lang] ) ) {
95 $this->blobCache
[$lang] +
= $blobs;
97 $this->blobCache
[$lang] = $blobs;
104 * Generate and insert a new message blob. If the blob was already
105 * present, it is not regenerated; instead, the preexisting blob
106 * is fetched and returned.
108 * @param string $name Module name
109 * @param ResourceLoaderModule $module
110 * @param string $lang Language code
111 * @return mixed Message blob or false if the module has no messages
113 public function insertMessageBlob( $name, ResourceLoaderModule
$module, $lang ) {
114 $blob = $this->generateMessageBlob( $module, $lang );
121 $dbw = wfGetDB( DB_MASTER
);
122 $success = $dbw->insert( 'msg_resource', array(
124 'mr_resource' => $name,
126 'mr_timestamp' => $dbw->timestamp()
132 if ( $success && $dbw->affectedRows() == 0 ) {
133 // Blob was already present, fetch it
134 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
135 'mr_resource' => $name,
141 } catch ( DBError
$e ) {
142 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
148 * Update the message blob for a given module in a given language
150 * @param string $name Module name
151 * @param ResourceLoaderModule $module
152 * @param string $lang Language code
153 * @return string|null Regenerated message blob, or null if there was no blob for
154 * the given module/language pair.
156 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
157 $dbw = wfGetDB( DB_MASTER
);
158 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
159 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
166 $newBlob = $this->generateMessageBlob( $module, $lang );
170 'mr_resource' => $name,
172 'mr_blob' => $newBlob,
173 'mr_timestamp' => $dbw->timestamp()
176 $dbw->replace( 'msg_resource',
177 array( array( 'mr_resource', 'mr_lang' ) ),
180 } catch ( Exception
$e ) {
181 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
187 * Update a single message in all message blobs it occurs in.
189 * @param string $key Message key
191 public function updateMessage( $key ) {
193 $dbw = wfGetDB( DB_MASTER
);
195 // Keep running until the updates queue is empty.
196 // Due to update conflicts, the queue might not be emptied
200 $updates = $this->getUpdatesForMessage( $key, $updates );
202 foreach ( $updates as $k => $update ) {
203 // Update the row on the condition that it
204 // didn't change since we fetched it by putting
205 // the timestamp in the WHERE clause.
206 $success = $dbw->update( 'msg_resource',
208 'mr_blob' => $update['newBlob'],
209 'mr_timestamp' => $dbw->timestamp() ),
211 'mr_resource' => $update['resource'],
212 'mr_lang' => $update['lang'],
213 'mr_timestamp' => $update['timestamp'] ),
217 // Only requeue conflicted updates.
218 // If update() returned false, don't retry, for
219 // fear of getting into an infinite loop
220 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
222 unset( $updates[$k] );
225 } while ( count( $updates ) );
227 } catch ( Exception
$e ) {
228 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
232 public function clear() {
234 // Not using TRUNCATE, because that needs extra permissions,
235 // which maybe not granted to the database user.
236 $dbw = wfGetDB( DB_MASTER
);
237 $dbw->delete( 'msg_resource', '*', __METHOD__
);
238 } catch ( Exception
$e ) {
239 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
244 * @return ResourceLoader
246 protected function getResourceLoader() {
247 // For back-compat this class supports instantiation without passing ResourceLoader
248 // Lazy-initialise this property because most callers don't need it.
249 if ( $this->resourceloader
=== null ) {
250 wfDebug( __CLASS__
. ' created without a ResourceLoader instance' );
251 $this->resourceloader
= new ResourceLoader();
254 return $this->resourceloader
;
258 * Create an update queue for updateMessage()
260 * @param string $key Message key
261 * @param array $prevUpdates Updates queue to refresh or null to build a fresh update queue
262 * @return array Updates queue
264 private function getUpdatesForMessage( $key, $prevUpdates = null ) {
265 $dbw = wfGetDB( DB_MASTER
);
267 if ( is_null( $prevUpdates ) ) {
268 $rl = $this->getResourceLoader();
269 $moduleNames = $rl->getModulesByMessage( $key );
270 // Fetch all blobs referencing $key
272 array( 'msg_resource' ),
273 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
275 'mr_resource' => $moduleNames,
280 // Refetch the blobs referenced by $prevUpdates
282 // Reorganize the (resource, lang) pairs in the format
283 // expected by makeWhereFrom2d()
286 foreach ( $prevUpdates as $update ) {
287 $twoD[$update['resource']][$update['lang']] = true;
290 $res = $dbw->select( 'msg_resource',
291 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
292 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
297 // Build the new updates queue
300 foreach ( $res as $row ) {
302 'resource' => $row->mr_resource
,
303 'lang' => $row->mr_lang
,
304 'timestamp' => $row->mr_timestamp
,
305 'newBlob' => $this->reencodeBlob( $row->mr_blob
, $key, $row->mr_lang
)
313 * @param string $key Message key
314 * @param string $lang Language code
317 private function fetchMessage( $key, $lang ) {
318 $message = wfMessage( $key )->inLanguage( $lang );
319 if ( !$message->exists() ) {
320 wfDebugLog( 'resourceloader', __METHOD__
. " failed to find: '$key' ($lang)" );
322 return $message->plain();
326 * Reencode a message blob with the updated value for a message
328 * @param string $blob Message blob (JSON object)
329 * @param string $key Message key
330 * @param string $lang Language code
331 * @return string Message blob with $key replaced with its new value
333 private function reencodeBlob( $blob, $key, $lang ) {
334 $decoded = FormatJson
::decode( $blob, true );
335 $decoded[$key] = $this->fetchMessage( $key, $lang );
336 return FormatJson
::encode( (object)$decoded );
340 * Get the message blobs for a set of modules from the database.
341 * Modules whose blobs are not in the database are silently dropped.
343 * @param ResourceLoader $resourceLoader
344 * @param array $modules Array of module names
345 * @param string $lang Language code
346 * @throws MWException
347 * @return array Array mapping module names to blobs
349 private function getFromDB( ResourceLoader
$resourceLoader, $modules, $lang ) {
350 if ( !count( $modules ) ) {
355 $dbr = wfGetDB( DB_SLAVE
);
356 $res = $dbr->select( 'msg_resource',
357 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
358 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
362 foreach ( $res as $row ) {
363 $module = $resourceLoader->getModule( $row->mr_resource
);
365 // This shouldn't be possible
366 throw new MWException( __METHOD__
. ' passed an invalid module name' );
369 // Update the module's blob if the list of messages changed
370 $blobKeys = array_keys( FormatJson
::decode( $row->mr_blob
, true ) );
371 $moduleMsgs = array_values( array_unique( $module->getMessages() ) );
372 if ( $blobKeys !== $moduleMsgs ) {
373 $retval[$row->mr_resource
] = $this->updateModule( $row->mr_resource
, $module, $lang );
375 $retval[$row->mr_resource
] = $row->mr_blob
;
383 * Generate the message blob for a given module in a given language.
385 * @param ResourceLoaderModule $module
386 * @param string $lang Language code
387 * @return string JSON object
389 private function generateMessageBlob( ResourceLoaderModule
$module, $lang ) {
392 foreach ( $module->getMessages() as $key ) {
393 $messages[$key] = $this->fetchMessage( $key, $lang );
396 return FormatJson
::encode( (object)$messages );