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 $success = $dbw->insert( 'msg_resource', array(
98 'mr_resource' => $name,
100 'mr_timestamp' => $dbw->timestamp()
107 if ( $dbw->affectedRows() == 0 ) {
108 // Blob was already present, fetch it
109 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
110 'mr_resource' => $name,
116 // Update msg_resource_links
119 foreach ( $module->getMessages() as $key ) {
121 'mrl_resource' => $name,
122 'mrl_message' => $key
125 $dbw->insert( 'msg_resource_links', $rows,
126 __METHOD__
, array( 'IGNORE' )
130 } catch ( DBError
$e ) {
131 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
137 * Update the message blob for a given module in a given language
139 * @param string $name Module name
140 * @param ResourceLoaderModule $module
141 * @param string $lang Language code
142 * @return string Regenerated message blob, or null if there was no blob for
143 * the given module/language pair.
145 public function updateModule( $name, ResourceLoaderModule
$module, $lang ) {
146 $dbw = wfGetDB( DB_MASTER
);
147 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
148 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
155 // Save the old and new blobs for later
156 $oldBlob = $row->mr_blob
;
157 $newBlob = $this->generateMessageBlob( $module, $lang );
161 'mr_resource' => $name,
163 'mr_blob' => $newBlob,
164 'mr_timestamp' => $dbw->timestamp()
167 $dbw->replace( 'msg_resource',
168 array( array( 'mr_resource', 'mr_lang' ) ),
172 // Figure out which messages were added and removed
173 $oldMessages = array_keys( FormatJson
::decode( $oldBlob, true ) );
174 $newMessages = array_keys( FormatJson
::decode( $newBlob, true ) );
175 $added = array_diff( $newMessages, $oldMessages );
176 $removed = array_diff( $oldMessages, $newMessages );
178 // Delete removed messages, insert added ones
180 $dbw->delete( 'msg_resource_links', array(
181 'mrl_resource' => $name,
182 'mrl_message' => $removed
187 $newLinksRows = array();
189 foreach ( $added as $message ) {
190 $newLinksRows[] = array(
191 'mrl_resource' => $name,
192 'mrl_message' => $message
196 if ( $newLinksRows ) {
197 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__
,
198 array( 'IGNORE' ) // just in case
201 } catch ( Exception
$e ) {
202 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
208 * Update a single message in all message blobs it occurs in.
210 * @param string $key Message key
212 public function updateMessage( $key ) {
214 $dbw = wfGetDB( DB_MASTER
);
216 // Keep running until the updates queue is empty.
217 // Due to update conflicts, the queue might not be emptied
221 $updates = $this->getUpdatesForMessage( $key, $updates );
223 foreach ( $updates as $k => $update ) {
224 // Update the row on the condition that it
225 // didn't change since we fetched it by putting
226 // the timestamp in the WHERE clause.
227 $success = $dbw->update( 'msg_resource',
229 'mr_blob' => $update['newBlob'],
230 'mr_timestamp' => $dbw->timestamp() ),
232 'mr_resource' => $update['resource'],
233 'mr_lang' => $update['lang'],
234 'mr_timestamp' => $update['timestamp'] ),
238 // Only requeue conflicted updates.
239 // If update() returned false, don't retry, for
240 // fear of getting into an infinite loop
241 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
243 unset( $updates[$k] );
246 } while ( count( $updates ) );
248 // No need to update msg_resource_links because we didn't add
249 // or remove any messages, we just changed their contents.
250 } catch ( Exception
$e ) {
251 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
255 public function clear() {
256 // TODO: Give this some more thought
258 // Not using TRUNCATE, because that needs extra permissions,
259 // which maybe not granted to the database user.
260 $dbw = wfGetDB( DB_MASTER
);
261 $dbw->delete( 'msg_resource', '*', __METHOD__
);
262 $dbw->delete( 'msg_resource_links', '*', __METHOD__
);
263 } catch ( Exception
$e ) {
264 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
269 * Create an update queue for updateMessage()
271 * @param string $key Message key
272 * @param array $prevUpdates Updates queue to refresh or null to build a fresh update queue
273 * @return array Updates queue
275 private function getUpdatesForMessage( $key, $prevUpdates = null ) {
276 $dbw = wfGetDB( DB_MASTER
);
278 if ( is_null( $prevUpdates ) ) {
279 // Fetch all blobs referencing $key
281 array( 'msg_resource', 'msg_resource_links' ),
282 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
283 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
287 // Refetch the blobs referenced by $prevUpdates
289 // Reorganize the (resource, lang) pairs in the format
290 // expected by makeWhereFrom2d()
293 foreach ( $prevUpdates as $update ) {
294 $twoD[$update['resource']][$update['lang']] = true;
297 $res = $dbw->select( 'msg_resource',
298 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
299 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
304 // Build the new updates queue
307 foreach ( $res as $row ) {
309 'resource' => $row->mr_resource
,
310 'lang' => $row->mr_lang
,
311 'timestamp' => $row->mr_timestamp
,
312 'newBlob' => $this->reencodeBlob( $row->mr_blob
, $key, $row->mr_lang
)
320 * Reencode a message blob with the updated value for a message
322 * @param string $blob Message blob (JSON object)
323 * @param string $key Message key
324 * @param string $lang Language code
325 * @return string Message blob with $key replaced with its new value
327 private function reencodeBlob( $blob, $key, $lang ) {
328 $decoded = FormatJson
::decode( $blob, true );
329 $decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
331 return FormatJson
::encode( (object)$decoded );
335 * Get the message blobs for a set of modules from the database.
336 * Modules whose blobs are not in the database are silently dropped.
338 * @param ResourceLoader $resourceLoader
339 * @param array $modules Array of module names
340 * @param string $lang Language code
341 * @throws MWException
342 * @return array Array mapping module names to blobs
344 private function getFromDB( ResourceLoader
$resourceLoader, $modules, $lang ) {
345 $config = $resourceLoader->getConfig();
347 $dbr = wfGetDB( DB_SLAVE
);
348 $res = $dbr->select( 'msg_resource',
349 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
350 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
354 foreach ( $res as $row ) {
355 $module = $resourceLoader->getModule( $row->mr_resource
);
357 // This shouldn't be possible
358 throw new MWException( __METHOD__
. ' passed an invalid module name' );
361 // Update the module's blobs if the set of messages changed or if the blob is
362 // older than the CacheEpoch setting
363 $keys = array_keys( FormatJson
::decode( $row->mr_blob
, true ) );
364 $values = array_values( array_unique( $module->getMessages() ) );
365 if ( $keys !== $values
366 ||
wfTimestamp( TS_MW
, $row->mr_timestamp
) <= $config->get( 'CacheEpoch' )
368 $retval[$row->mr_resource
] = $this->updateModule( $row->mr_resource
, $module, $lang );
370 $retval[$row->mr_resource
] = $row->mr_blob
;
378 * Generate the message blob for a given module in a given language.
380 * @param ResourceLoaderModule $module
381 * @param string $lang Language code
382 * @return string JSON object
384 private function generateMessageBlob( ResourceLoaderModule
$module, $lang ) {
387 foreach ( $module->getMessages() as $key ) {
388 $messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
391 return FormatJson
::encode( (object)$messages );