Made TempFSFile try to purge files on fatals too
[mediawiki.git] / includes / MessageBlobStore.php
blob7e1c7452e5c0eaf148893feef6d28e7618adcf9c
1 <?php
2 /**
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
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 /**
26 * This class provides access to the resource message blobs storage used by
27 * the ResourceLoader.
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 /**
37 * Get the message blobs for a set of modules
39 * @param $resourceLoader ResourceLoader object
40 * @param array $modules Array of module objects keyed by module name
41 * @param string $lang Language code
42 * @return array An array mapping module names to message blobs
44 public static function get( ResourceLoader $resourceLoader, $modules, $lang ) {
45 wfProfileIn( __METHOD__ );
46 if ( !count( $modules ) ) {
47 wfProfileOut( __METHOD__ );
48 return array();
50 // Try getting from the DB first
51 $blobs = self::getFromDB( $resourceLoader, array_keys( $modules ), $lang );
53 // Generate blobs for any missing modules and store them in the DB
54 $missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
55 foreach ( $missing as $name ) {
56 $blob = self::insertMessageBlob( $name, $modules[$name], $lang );
57 if ( $blob ) {
58 $blobs[$name] = $blob;
62 wfProfileOut( __METHOD__ );
63 return $blobs;
66 /**
67 * Generate and insert a new message blob. If the blob was already
68 * present, it is not regenerated; instead, the preexisting blob
69 * is fetched and returned.
71 * @param string $name module name
72 * @param $module ResourceLoaderModule object
73 * @param string $lang language code
74 * @return mixed Message blob or false if the module has no messages
76 public static function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
77 $blob = self::generateMessageBlob( $module, $lang );
79 if ( !$blob ) {
80 return false;
83 try {
84 $dbw = wfGetDB( DB_MASTER );
85 $success = $dbw->insert( 'msg_resource', array(
86 'mr_lang' => $lang,
87 'mr_resource' => $name,
88 'mr_blob' => $blob,
89 'mr_timestamp' => $dbw->timestamp()
91 __METHOD__,
92 array( 'IGNORE' )
95 if ( $success ) {
96 if ( $dbw->affectedRows() == 0 ) {
97 // Blob was already present, fetch it
98 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
99 'mr_resource' => $name,
100 'mr_lang' => $lang,
102 __METHOD__
104 } else {
105 // Update msg_resource_links
106 $rows = array();
108 foreach ( $module->getMessages() as $key ) {
109 $rows[] = array(
110 'mrl_resource' => $name,
111 'mrl_message' => $key
114 $dbw->insert( 'msg_resource_links', $rows,
115 __METHOD__, array( 'IGNORE' )
119 } catch ( Exception $e ) {
120 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
122 return $blob;
126 * Update the message blob for a given module in a given language
128 * @param string $name module name
129 * @param $module ResourceLoaderModule object
130 * @param string $lang language code
131 * @return String Regenerated message blob, or null if there was no blob for the given module/language pair
133 public static function updateModule( $name, ResourceLoaderModule $module, $lang ) {
134 $dbw = wfGetDB( DB_MASTER );
135 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
136 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
137 __METHOD__
139 if ( !$row ) {
140 return null;
143 // Save the old and new blobs for later
144 $oldBlob = $row->mr_blob;
145 $newBlob = self::generateMessageBlob( $module, $lang );
147 try {
148 $newRow = array(
149 'mr_resource' => $name,
150 'mr_lang' => $lang,
151 'mr_blob' => $newBlob,
152 'mr_timestamp' => $dbw->timestamp()
155 $dbw->replace( 'msg_resource',
156 array( array( 'mr_resource', 'mr_lang' ) ),
157 $newRow, __METHOD__
160 // Figure out which messages were added and removed
161 $oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
162 $newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
163 $added = array_diff( $newMessages, $oldMessages );
164 $removed = array_diff( $oldMessages, $newMessages );
166 // Delete removed messages, insert added ones
167 if ( $removed ) {
168 $dbw->delete( 'msg_resource_links', array(
169 'mrl_resource' => $name,
170 'mrl_message' => $removed
171 ), __METHOD__
175 $newLinksRows = array();
177 foreach ( $added as $message ) {
178 $newLinksRows[] = array(
179 'mrl_resource' => $name,
180 'mrl_message' => $message
184 if ( $newLinksRows ) {
185 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
186 array( 'IGNORE' ) // just in case
189 } catch ( Exception $e ) {
190 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
192 return $newBlob;
196 * Update a single message in all message blobs it occurs in.
198 * @param string $key message key
200 public static function updateMessage( $key ) {
201 try {
202 $dbw = wfGetDB( DB_MASTER );
204 // Keep running until the updates queue is empty.
205 // Due to update conflicts, the queue might not be emptied
206 // in one iteration.
207 $updates = null;
208 do {
209 $updates = self::getUpdatesForMessage( $key, $updates );
211 foreach ( $updates as $k => $update ) {
212 // Update the row on the condition that it
213 // didn't change since we fetched it by putting
214 // the timestamp in the WHERE clause.
215 $success = $dbw->update( 'msg_resource',
216 array(
217 'mr_blob' => $update['newBlob'],
218 'mr_timestamp' => $dbw->timestamp() ),
219 array(
220 'mr_resource' => $update['resource'],
221 'mr_lang' => $update['lang'],
222 'mr_timestamp' => $update['timestamp'] ),
223 __METHOD__
226 // Only requeue conflicted updates.
227 // If update() returned false, don't retry, for
228 // fear of getting into an infinite loop
229 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
230 // Not conflicted
231 unset( $updates[$k] );
234 } while ( count( $updates ) );
236 // No need to update msg_resource_links because we didn't add
237 // or remove any messages, we just changed their contents.
238 } catch ( Exception $e ) {
239 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
243 public static function clear() {
244 // TODO: Give this some more thought
245 try {
246 // Not using TRUNCATE, because that needs extra permissions,
247 // which maybe not granted to the database user.
248 $dbw = wfGetDB( DB_MASTER );
249 $dbw->delete( 'msg_resource', '*', __METHOD__ );
250 $dbw->delete( 'msg_resource_links', '*', __METHOD__ );
251 } catch ( Exception $e ) {
252 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
257 * Create an update queue for updateMessage()
259 * @param string $key message key
260 * @param array $prevUpdates updates queue to refresh or null to build a fresh update queue
261 * @return Array: updates queue
263 private static function getUpdatesForMessage( $key, $prevUpdates = null ) {
264 $dbw = wfGetDB( DB_MASTER );
266 if ( is_null( $prevUpdates ) ) {
267 // Fetch all blobs referencing $key
268 $res = $dbw->select(
269 array( 'msg_resource', 'msg_resource_links' ),
270 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
271 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
272 __METHOD__
274 } else {
275 // Refetch the blobs referenced by $prevUpdates
277 // Reorganize the (resource, lang) pairs in the format
278 // expected by makeWhereFrom2d()
279 $twoD = array();
281 foreach ( $prevUpdates as $update ) {
282 $twoD[$update['resource']][$update['lang']] = true;
285 $res = $dbw->select( 'msg_resource',
286 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
287 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
288 __METHOD__
292 // Build the new updates queue
293 $updates = array();
295 foreach ( $res as $row ) {
296 $updates[] = array(
297 'resource' => $row->mr_resource,
298 'lang' => $row->mr_lang,
299 'timestamp' => $row->mr_timestamp,
300 'newBlob' => self::reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
304 return $updates;
308 * Reencode a message blob with the updated value for a message
310 * @param string $blob message blob (JSON object)
311 * @param string $key message key
312 * @param string $lang language code
313 * @return Message blob with $key replaced with its new value
315 private static function reencodeBlob( $blob, $key, $lang ) {
316 $decoded = FormatJson::decode( $blob, true );
317 $decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
319 return FormatJson::encode( (object)$decoded );
323 * Get the message blobs for a set of modules from the database.
324 * Modules whose blobs are not in the database are silently dropped.
326 * @param $resourceLoader ResourceLoader object
327 * @param array $modules of module names
328 * @param string $lang language code
329 * @throws MWException
330 * @return array Array mapping module names to blobs
332 private static function getFromDB( ResourceLoader $resourceLoader, $modules, $lang ) {
333 global $wgCacheEpoch;
334 $retval = array();
335 $dbr = wfGetDB( DB_SLAVE );
336 $res = $dbr->select( 'msg_resource',
337 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
338 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
339 __METHOD__
342 foreach ( $res as $row ) {
343 $module = $resourceLoader->getModule( $row->mr_resource );
344 if ( !$module ) {
345 // This shouldn't be possible
346 throw new MWException( __METHOD__ . ' passed an invalid module name' );
348 // Update the module's blobs if the set of messages changed or if the blob is
349 // older than $wgCacheEpoch
350 if ( array_keys( FormatJson::decode( $row->mr_blob, true ) ) !== array_values( array_unique( $module->getMessages() ) ) ||
351 wfTimestamp( TS_MW, $row->mr_timestamp ) <= $wgCacheEpoch ) {
352 $retval[$row->mr_resource] = self::updateModule( $row->mr_resource, $module, $lang );
353 } else {
354 $retval[$row->mr_resource] = $row->mr_blob;
358 return $retval;
362 * Generate the message blob for a given module in a given language.
364 * @param $module ResourceLoaderModule object
365 * @param string $lang language code
366 * @return String: JSON object
368 private static function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
369 $messages = array();
371 foreach ( $module->getMessages() as $key ) {
372 $messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
375 return FormatJson::encode( (object)$messages );