3 * Resource message blobs storage used by the resource loader.
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 by
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 * Get the singleton instance
39 * @return MessageBlobStore
41 public static function getInstance() {
42 static $instance = null;
43 if ( $instance === null ) {
51 * Get the message blobs for a set of modules
53 * @param ResourceLoader $resourceLoader
54 * @param array $modules Array of module objects keyed by module name
55 * @param string $lang Language code
56 * @return array An array mapping module names to message blobs
58 public function get( ResourceLoader
$resourceLoader, $modules, $lang ) {
59 if ( !count( $modules ) ) {
62 // Try getting from the DB first
63 $blobs = $this->getFromDB( $resourceLoader, array_keys( $modules ), $lang );
65 // Generate blobs for any missing modules and store them in the DB
66 $missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
67 foreach ( $missing as $name ) {
68 $blob = $this->insertMessageBlob( $name, $modules[$name], $lang );
70 $blobs[$name] = $blob;
78 * Generate and insert a new message blob. If the blob was already
79 * present, it is not regenerated; instead, the preexisting blob
80 * is fetched and returned.
82 * @param string $name Module name
83 * @param ResourceLoaderModule $module
84 * @param string $lang Language code
85 * @return mixed Message blob or false if the module has no messages
87 public function insertMessageBlob( $name, ResourceLoaderModule
$module, $lang ) {
88 $blob = $this->generateMessageBlob( $module, $lang );
95 $dbw = wfGetDB( DB_MASTER
);
96 $dbw->startAtomic( __METHOD__
);
97 $success = $dbw->insert( 'msg_resource', array(
99 'mr_resource' => $name,
101 'mr_timestamp' => $dbw->timestamp()
108 if ( $dbw->affectedRows() == 0 ) {
109 // Blob was already present, fetch it
110 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
111 'mr_resource' => $name,
117 // Update msg_resource_links
120 foreach ( $module->getMessages() as $key ) {
122 'mrl_resource' => $name,
123 'mrl_message' => $key
126 $dbw->insert( 'msg_resource_links', $rows,
127 __METHOD__
, array( 'IGNORE' )
131 $dbw->endAtomic( __METHOD__
);
132 } catch ( DBError
$e ) {
133 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
139 * Update the message blob for a given module in a given language
141 * @param string $name Module name
142 * @param ResourceLoaderModule $module
143 * @param string $lang Language code
144 * @return string Regenerated message blob, or null if there was no blob for
145 * the given module/language pair.
147 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
148 $dbw = wfGetDB( DB_MASTER
);
149 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
150 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
157 // Save the old and new blobs for later
158 $oldBlob = $row->mr_blob
;
159 $newBlob = $this->generateMessageBlob( $module, $lang );
163 'mr_resource' => $name,
165 'mr_blob' => $newBlob,
166 'mr_timestamp' => $dbw->timestamp()
169 $dbw->replace( 'msg_resource',
170 array( array( 'mr_resource', 'mr_lang' ) ),
174 // Figure out which messages were added and removed
175 $oldMessages = array_keys( FormatJson
::decode( $oldBlob, true ) );
176 $newMessages = array_keys( FormatJson
::decode( $newBlob, true ) );
177 $added = array_diff( $newMessages, $oldMessages );
178 $removed = array_diff( $oldMessages, $newMessages );
180 // Delete removed messages, insert added ones
182 $dbw->delete( 'msg_resource_links', array(
183 'mrl_resource' => $name,
184 'mrl_message' => $removed
189 $newLinksRows = array();
191 foreach ( $added as $message ) {
192 $newLinksRows[] = array(
193 'mrl_resource' => $name,
194 'mrl_message' => $message
198 if ( $newLinksRows ) {
199 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__
,
200 array( 'IGNORE' ) // just in case
203 } catch ( Exception
$e ) {
204 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
210 * Update a single message in all message blobs it occurs in.
212 * @param string $key Message key
214 public function updateMessage( $key ) {
216 $dbw = wfGetDB( DB_MASTER
);
218 // Keep running until the updates queue is empty.
219 // Due to update conflicts, the queue might not be emptied
223 $updates = $this->getUpdatesForMessage( $key, $updates );
225 foreach ( $updates as $k => $update ) {
226 // Update the row on the condition that it
227 // didn't change since we fetched it by putting
228 // the timestamp in the WHERE clause.
229 $success = $dbw->update( 'msg_resource',
231 'mr_blob' => $update['newBlob'],
232 'mr_timestamp' => $dbw->timestamp() ),
234 'mr_resource' => $update['resource'],
235 'mr_lang' => $update['lang'],
236 'mr_timestamp' => $update['timestamp'] ),
240 // Only requeue conflicted updates.
241 // If update() returned false, don't retry, for
242 // fear of getting into an infinite loop
243 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
245 unset( $updates[$k] );
248 } while ( count( $updates ) );
250 // No need to update msg_resource_links because we didn't add
251 // or remove any messages, we just changed their contents.
252 } catch ( Exception
$e ) {
253 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
257 public function clear() {
258 // TODO: Give this some more thought
260 // Not using TRUNCATE, because that needs extra permissions,
261 // which maybe not granted to the database user.
262 $dbw = wfGetDB( DB_MASTER
);
263 $dbw->delete( 'msg_resource', '*', __METHOD__
);
264 $dbw->delete( 'msg_resource_links', '*', __METHOD__
);
265 } catch ( Exception
$e ) {
266 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
271 * Create an update queue for updateMessage()
273 * @param string $key Message key
274 * @param array $prevUpdates Updates queue to refresh or null to build a fresh update queue
275 * @return array Updates queue
277 private function getUpdatesForMessage( $key, $prevUpdates = null ) {
278 $dbw = wfGetDB( DB_MASTER
);
280 if ( is_null( $prevUpdates ) ) {
281 // Fetch all blobs referencing $key
283 array( 'msg_resource', 'msg_resource_links' ),
284 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
285 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
289 // Refetch the blobs referenced by $prevUpdates
291 // Reorganize the (resource, lang) pairs in the format
292 // expected by makeWhereFrom2d()
295 foreach ( $prevUpdates as $update ) {
296 $twoD[$update['resource']][$update['lang']] = true;
299 $res = $dbw->select( 'msg_resource',
300 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
301 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
306 // Build the new updates queue
309 foreach ( $res as $row ) {
311 'resource' => $row->mr_resource
,
312 'lang' => $row->mr_lang
,
313 'timestamp' => $row->mr_timestamp
,
314 'newBlob' => $this->reencodeBlob( $row->mr_blob
, $key, $row->mr_lang
)
322 * Reencode a message blob with the updated value for a message
324 * @param string $blob Message blob (JSON object)
325 * @param string $key Message key
326 * @param string $lang Language code
327 * @return string Message blob with $key replaced with its new value
329 private function reencodeBlob( $blob, $key, $lang ) {
330 $decoded = FormatJson
::decode( $blob, true );
331 $decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
333 return FormatJson
::encode( (object)$decoded );
337 * Get the message blobs for a set of modules from the database.
338 * Modules whose blobs are not in the database are silently dropped.
340 * @param ResourceLoader $resourceLoader
341 * @param array $modules Array of module names
342 * @param string $lang Language code
343 * @throws MWException
344 * @return array Array mapping module names to blobs
346 private function getFromDB( ResourceLoader
$resourceLoader, $modules, $lang ) {
347 $config = $resourceLoader->getConfig();
349 $dbr = wfGetDB( DB_SLAVE
);
350 $res = $dbr->select( 'msg_resource',
351 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
352 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
356 foreach ( $res as $row ) {
357 $module = $resourceLoader->getModule( $row->mr_resource
);
359 // This shouldn't be possible
360 throw new MWException( __METHOD__
. ' passed an invalid module name' );
363 // Update the module's blobs if the set of messages changed or if the blob is
364 // older than the CacheEpoch setting
365 $keys = array_keys( FormatJson
::decode( $row->mr_blob
, true ) );
366 $values = array_values( array_unique( $module->getMessages() ) );
367 if ( $keys !== $values
368 ||
wfTimestamp( TS_MW
, $row->mr_timestamp
) <= $config->get( 'CacheEpoch' )
370 $retval[$row->mr_resource
] = $this->updateModule( $row->mr_resource
, $module, $lang );
372 $retval[$row->mr_resource
] = $row->mr_blob
;
380 * Generate the message blob for a given module in a given language.
382 * @param ResourceLoaderModule $module
383 * @param string $lang Language code
384 * @return string JSON object
386 private function generateMessageBlob( ResourceLoaderModule
$module, $lang ) {
389 foreach ( $module->getMessages() as $key ) {
390 $messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
393 return FormatJson
::encode( (object)$messages );