Made ResourceLoader an instantiable object, rather than a static one, making it more...
[lhc/web/wiklou.git] / includes / MessageBlobStore.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @author Roan Kattouw
19 * @author Trevor Parscal
20 */
21
22 /**
23 * This class provides access to the resource message blobs storage used by
24 * the ResourceLoader.
25 *
26 * A message blob is a JSON object containing the interface messages for a
27 * certain resource in a certain language. These message blobs are cached
28 * in the msg_resource table and automatically invalidated when one of their
29 * consistuent messages or the resource itself is changed.
30 */
31 class MessageBlobStore {
32 /**
33 * Get the message blobs for a set of modules
34 * @param $modules array Array of module objects keyed by module name
35 * @param $lang string Language code
36 * @return array An array mapping module names to message blobs
37 */
38 public static function get( $modules, $lang ) {
39 // TODO: Invalidate blob when module touched
40 wfProfileIn( __METHOD__ );
41 if ( !count( $modules ) ) {
42 wfProfileOut( __METHOD__ );
43 return array();
44 }
45 // Try getting from the DB first
46 $blobs = self::getFromDB( array_keys( $modules ), $lang );
47
48 // Generate blobs for any missing modules and store them in the DB
49 $missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
50 foreach ( $missing as $name ) {
51 $blob = self::insertMessageBlob( $name, $modules[$name], $lang );
52 if ( $blob ) {
53 $blobs[$name] = $blob;
54 }
55 }
56
57 wfProfileOut( __METHOD__ );
58 return $blobs;
59 }
60
61 /**
62 * Generate and insert a new message blob. If the blob was already
63 * present, it is not regenerated; instead, the preexisting blob
64 * is fetched and returned.
65 * @param $module string Module name
66 * @param $lang string Language code
67 * @return mixed Message blob or false if the module has no messages
68 */
69 public static function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
70 $blob = self::generateMessageBlob( $name, $module, $lang );
71
72 if ( !$blob ) {
73 return false;
74 }
75
76 $dbw = wfGetDB( DB_MASTER );
77 $success = $dbw->insert( 'msg_resource', array(
78 'mr_lang' => $lang,
79 'mr_resource' => $name,
80 'mr_blob' => $blob,
81 'mr_timestamp' => $dbw->timestamp()
82 ),
83 __METHOD__,
84 array( 'IGNORE' )
85 );
86
87 if ( $success ) {
88 if ( $dbw->affectedRows() == 0 ) {
89 // Blob was already present, fetch it
90 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
91 'mr_resource' => $name,
92 'mr_lang' => $lang,
93 ),
94 __METHOD__
95 );
96 } else {
97 // Update msg_resource_links
98 $rows = array();
99
100 foreach ( $module->getMessages() as $key ) {
101 $rows[] = array(
102 'mrl_resource' => $name,
103 'mrl_message' => $key
104 );
105 }
106 $dbw->insert( 'msg_resource_links', $rows,
107 __METHOD__, array( 'IGNORE' )
108 );
109 }
110 }
111
112 return $blob;
113 }
114
115 /**
116 * Update all message blobs for a given module.
117 * @param $module string Module name
118 * @param $lang string Language code (optional)
119 * @return mixed If $lang is set, the new message blob for that language is
120 * returned if present. Otherwise, null is returned.
121 */
122 public static function updateModule( $name, ResourceLoaderModule $module, $lang = null ) {
123 $retval = null;
124
125 // Find all existing blobs for this module
126 $dbw = wfGetDB( DB_MASTER );
127 $res = $dbw->select( 'msg_resource',
128 array( 'mr_lang', 'mr_blob' ),
129 array( 'mr_resource' => $name ),
130 __METHOD__
131 );
132
133 // Build the new msg_resource rows
134 $newRows = array();
135 $now = $dbw->timestamp();
136 // Save the last-processed old and new blobs for later
137 $oldBlob = $newBlob = null;
138
139 foreach ( $res as $row ) {
140 $oldBlob = $row->mr_blob;
141 $newBlob = self::generateMessageBlob( $name, $module, $row->mr_lang );
142
143 if ( $row->mr_lang === $lang ) {
144 $retval = $newBlob;
145 }
146 $newRows[] = array(
147 'mr_resource' => $name,
148 'mr_lang' => $row->mr_lang,
149 'mr_blob' => $newBlob,
150 'mr_timestamp' => $now
151 );
152 }
153
154 $dbw->replace( 'msg_resource',
155 array( array( 'mr_resource', 'mr_lang' ) ),
156 $newRows, __METHOD__
157 );
158
159 // Figure out which messages were added and removed
160 $oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
161 $newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
162 $added = array_diff( $newMessages, $oldMessages );
163 $removed = array_diff( $oldMessages, $newMessages );
164
165 // Delete removed messages, insert added ones
166 if ( $removed ) {
167 $dbw->delete( 'msg_resource_links', array(
168 'mrl_resource' => $name,
169 'mrl_message' => $removed
170 ), __METHOD__
171 );
172 }
173
174 $newLinksRows = array();
175
176 foreach ( $added as $message ) {
177 $newLinksRows[] = array(
178 'mrl_resource' => $name,
179 'mrl_message' => $message
180 );
181 }
182
183 if ( $newLinksRows ) {
184 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
185 array( 'IGNORE' ) // just in case
186 );
187 }
188
189 return $retval;
190 }
191
192 /**
193 * Update a single message in all message blobs it occurs in.
194 * @param $key string Message key
195 */
196 public static function updateMessage( $key ) {
197 $dbw = wfGetDB( DB_MASTER );
198
199 // Keep running until the updates queue is empty.
200 // Due to update conflicts, the queue might not be emptied
201 // in one iteration.
202 $updates = null;
203 do {
204 $updates = self::getUpdatesForMessage( $key, $updates );
205
206 foreach ( $updates as $key => $update ) {
207 // Update the row on the condition that it
208 // didn't change since we fetched it by putting
209 // the timestamp in the WHERE clause.
210 $success = $dbw->update( 'msg_resource',
211 array(
212 'mr_blob' => $update['newBlob'],
213 'mr_timestamp' => $dbw->timestamp() ),
214 array(
215 'mr_resource' => $update['resource'],
216 'mr_lang' => $update['lang'],
217 'mr_timestamp' => $update['timestamp'] ),
218 __METHOD__
219 );
220
221 // Only requeue conflicted updates.
222 // If update() returned false, don't retry, for
223 // fear of getting into an infinite loop
224 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
225 // Not conflicted
226 unset( $updates[$key] );
227 }
228 }
229 } while ( count( $updates ) );
230
231 // No need to update msg_resource_links because we didn't add
232 // or remove any messages, we just changed their contents.
233 }
234
235 public static function clear() {
236 // TODO: Give this some more thought
237 // TODO: Is TRUNCATE better?
238 $dbw = wfGetDB( DB_MASTER );
239 $dbw->delete( 'msg_resource', '*', __METHOD__ );
240 $dbw->delete( 'msg_resource_links', '*', __METHOD__ );
241 }
242
243 /**
244 * Create an update queue for updateMessage()
245 * @param $key string Message key
246 * @param $prevUpdates array Updates queue to refresh or null to build a fresh update queue
247 * @return array Updates queue
248 */
249 private static function getUpdatesForMessage( $key, $prevUpdates = null ) {
250 $dbw = wfGetDB( DB_MASTER );
251
252 if ( is_null( $prevUpdates ) ) {
253 // Fetch all blobs referencing $key
254 $res = $dbw->select(
255 array( 'msg_resource', 'msg_resource_links' ),
256 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
257 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
258 __METHOD__
259 );
260 } else {
261 // Refetch the blobs referenced by $prevUpdates
262
263 // Reorganize the (resource, lang) pairs in the format
264 // expected by makeWhereFrom2d()
265 $twoD = array();
266
267 foreach ( $prevUpdates as $update ) {
268 $twoD[$update['resource']][$update['lang']] = true;
269 }
270
271 $res = $dbw->select( 'msg_resource',
272 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
273 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
274 __METHOD__
275 );
276 }
277
278 // Build the new updates queue
279 $updates = array();
280
281 foreach ( $res as $row ) {
282 $updates[] = array(
283 'resource' => $row->mr_resource,
284 'lang' => $row->mr_lang,
285 'timestamp' => $row->mr_timestamp,
286 'newBlob' => self::reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
287 );
288 }
289
290 return $updates;
291 }
292
293 /**
294 * Reencode a message blob with the updated value for a message
295 * @param $blob string Message blob (JSON object)
296 * @param $key string Message key
297 * @param $lang string Language code
298 * @return Message blob with $key replaced with its new value
299 */
300 private static function reencodeBlob( $blob, $key, $lang ) {
301 $decoded = FormatJson::decode( $blob, true );
302 $decoded[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
303
304 return FormatJson::encode( $decoded );
305 }
306
307 /**
308 * Get the message blobs for a set of modules from the database.
309 * Modules whose blobs are not in the database are silently dropped.
310 * @param $modules array Array of module names
311 * @param $lang string Language code
312 * @return array Array mapping module names to blobs
313 */
314 private static function getFromDB( $modules, $lang ) {
315 $retval = array();
316 $dbr = wfGetDB( DB_SLAVE );
317 $res = $dbr->select( 'msg_resource',
318 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
319 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
320 __METHOD__
321 );
322
323 foreach ( $res as $row ) {
324 $module = ResourceLoader::getModule( $row->mr_resource );
325 if ( !$module ) {
326 // This shouldn't be possible
327 throw new MWException( __METHOD__ . ' passed an invalid module name' );
328 }
329 if ( array_keys( FormatJson::decode( $row->mr_blob, true ) ) !== $module->getMessages() ) {
330 $retval[$row->mr_resource] = self::updateModule( $row->mr_resource, $lang );
331 } else {
332 $retval[$row->mr_resource] = $row->mr_blob;
333 }
334 }
335
336 return $retval;
337 }
338
339 /**
340 * Generate the message blob for a given module in a given language.
341 * @param $module string Module name
342 * @param $lang string Language code
343 * @return string JSON object
344 */
345 private static function generateMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
346 $messages = array();
347
348 foreach ( $module->getMessages() as $key ) {
349 $messages[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
350 }
351
352 return FormatJson::encode( $messages );
353 }
354 }