Revert r72816 and do it properly: the SELECT should be executed on the master
[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 names
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( $modules, $lang );
47
48 // Generate blobs for any missing modules and store them in the DB
49 $missing = array_diff( $modules, array_keys( $blobs ) );
50 foreach ( $missing as $module ) {
51 $blob = self::insertMessageBlob( $module, $lang );
52 if ( $blob ) {
53 $blobs[$module] = $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( $module, $lang ) {
70 $blob = self::generateMessageBlob( $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' => $module,
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' => $module,
92 'mr_lang' => $lang,
93 ),
94 __METHOD__
95 );
96 } else {
97 // Update msg_resource_links
98 $rows = array();
99 $mod = ResourceLoader::getModule( $module );
100
101 foreach ( $mod->getMessages() as $key ) {
102 $rows[] = array(
103 'mrl_resource' => $module,
104 'mrl_message' => $key
105 );
106 }
107 $dbw->insert( 'msg_resource_links', $rows,
108 __METHOD__, array( 'IGNORE' )
109 );
110 }
111 }
112
113 return $blob;
114 }
115
116 /**
117 * Update all message blobs for a given module.
118 * @param $module string Module name
119 * @param $lang string Language code (optional)
120 * @return mixed If $lang is set, the new message blob for that language is
121 * returned if present. Otherwise, null is returned.
122 */
123 public static function updateModule( $module, $lang = null ) {
124 $retval = null;
125
126 // Find all existing blobs for this module
127 $dbw = wfGetDB( DB_MASTER );
128 $res = $dbw->select( 'msg_resource',
129 array( 'mr_lang', 'mr_blob' ),
130 array( 'mr_resource' => $module ),
131 __METHOD__
132 );
133
134 // Build the new msg_resource rows
135 $newRows = array();
136 $now = $dbw->timestamp();
137 // Save the last-processed old and new blobs for later
138 $oldBlob = $newBlob = null;
139
140 foreach ( $res as $row ) {
141 $oldBlob = $row->mr_blob;
142 $newBlob = self::generateMessageBlob( $module, $row->mr_lang );
143
144 if ( $row->mr_lang === $lang ) {
145 $retval = $newBlob;
146 }
147 $newRows[] = array(
148 'mr_resource' => $module,
149 'mr_lang' => $row->mr_lang,
150 'mr_blob' => $newBlob,
151 'mr_timestamp' => $now
152 );
153 }
154
155 $dbw->replace( 'msg_resource',
156 array( array( 'mr_resource', 'mr_lang' ) ),
157 $newRows, __METHOD__
158 );
159
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 );
165
166 // Delete removed messages, insert added ones
167 if ( $removed ) {
168 $dbw->delete( 'msg_resource_links', array(
169 'mrl_resource' => $module,
170 'mrl_message' => $removed
171 ), __METHOD__
172 );
173 }
174
175 $newLinksRows = array();
176
177 foreach ( $added as $message ) {
178 $newLinksRows[] = array(
179 'mrl_resource' => $module,
180 'mrl_message' => $message
181 );
182 }
183
184 if ( $newLinksRows ) {
185 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
186 array( 'IGNORE' ) // just in case
187 );
188 }
189
190 return $retval;
191 }
192
193 /**
194 * Update a single message in all message blobs it occurs in.
195 * @param $key string Message key
196 */
197 public static function updateMessage( $key ) {
198 $dbw = wfGetDB( DB_MASTER );
199
200 // Keep running until the updates queue is empty.
201 // Due to update conflicts, the queue might not be emptied
202 // in one iteration.
203 $updates = null;
204 do {
205 $updates = self::getUpdatesForMessage( $key, $updates );
206
207 foreach ( $updates as $key => $update ) {
208 // Update the row on the condition that it
209 // didn't change since we fetched it by putting
210 // the timestamp in the WHERE clause.
211 $success = $dbw->update( 'msg_resource',
212 array(
213 'mr_blob' => $update['newBlob'],
214 'mr_timestamp' => $dbw->timestamp() ),
215 array(
216 'mr_resource' => $update['resource'],
217 'mr_lang' => $update['lang'],
218 'mr_timestamp' => $update['timestamp'] ),
219 __METHOD__
220 );
221
222 // Only requeue conflicted updates.
223 // If update() returned false, don't retry, for
224 // fear of getting into an infinite loop
225 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
226 // Not conflicted
227 unset( $updates[$key] );
228 }
229 }
230 } while ( count( $updates ) );
231
232 // No need to update msg_resource_links because we didn't add
233 // or remove any messages, we just changed their contents.
234 }
235
236 public static function clear() {
237 // TODO: Give this some more thought
238 // TODO: Is TRUNCATE better?
239 $dbw = wfGetDB( DB_MASTER );
240 $dbw->delete( 'msg_resource', '*', __METHOD__ );
241 $dbw->delete( 'msg_resource_links', '*', __METHOD__ );
242 }
243
244 /**
245 * Create an update queue for updateMessage()
246 * @param $key string Message key
247 * @param $prevUpdates array Updates queue to refresh or null to build a fresh update queue
248 * @return array Updates queue
249 */
250 private static function getUpdatesForMessage( $key, $prevUpdates = null ) {
251 $dbw = wfGetDB( DB_MASTER );
252
253 if ( is_null( $prevUpdates ) ) {
254 // Fetch all blobs referencing $key
255 $res = $dbw->select(
256 array( 'msg_resource', 'msg_resource_links' ),
257 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
258 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
259 __METHOD__
260 );
261 } else {
262 // Refetch the blobs referenced by $prevUpdates
263
264 // Reorganize the (resource, lang) pairs in the format
265 // expected by makeWhereFrom2d()
266 $twoD = array();
267
268 foreach ( $prevUpdates as $update ) {
269 $twoD[$update['resource']][$update['lang']] = true;
270 }
271
272 $res = $dbw->select( 'msg_resource',
273 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
274 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
275 __METHOD__
276 );
277 }
278
279 // Build the new updates queue
280 $updates = array();
281
282 foreach ( $res as $row ) {
283 $updates[] = array(
284 'resource' => $row->mr_resource,
285 'lang' => $row->mr_lang,
286 'timestamp' => $row->mr_timestamp,
287 'newBlob' => self::reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
288 );
289 }
290
291 return $updates;
292 }
293
294 /**
295 * Reencode a message blob with the updated value for a message
296 * @param $blob string Message blob (JSON object)
297 * @param $key string Message key
298 * @param $lang string Language code
299 * @return Message blob with $key replaced with its new value
300 */
301 private static function reencodeBlob( $blob, $key, $lang ) {
302 $decoded = FormatJson::decode( $blob, true );
303 $decoded[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
304
305 return FormatJson::encode( $decoded );
306 }
307
308 /**
309 * Get the message blobs for a set of modules from the database.
310 * Modules whose blobs are not in the database are silently dropped.
311 * @param $modules array Array of module names
312 * @param $lang string Language code
313 * @return array Array mapping module names to blobs
314 */
315 private static function getFromDB( $modules, $lang ) {
316 $retval = array();
317 $dbr = wfGetDB( DB_SLAVE );
318 $res = $dbr->select( 'msg_resource',
319 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
320 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
321 __METHOD__
322 );
323
324 foreach ( $res as $row ) {
325 $module = ResourceLoader::getModule( $row->mr_resource );
326 if ( !$module ) {
327 // This shouldn't be possible
328 throw new MWException( __METHOD__ . ' passed an invalid module name' );
329 }
330 if ( array_keys( FormatJson::decode( $row->mr_blob, true ) ) !== $module->getMessages() ) {
331 $retval[$row->mr_resource] = self::updateModule( $row->mr_resource, $lang );
332 } else {
333 $retval[$row->mr_resource] = $row->mr_blob;
334 }
335 }
336
337 return $retval;
338 }
339
340 /**
341 * Generate the message blob for a given module in a given language.
342 * @param $module string Module name
343 * @param $lang string Language code
344 * @return string JSON object
345 */
346 private static function generateMessageBlob( $module, $lang ) {
347 $mod = ResourceLoader::getModule( $module );
348 $messages = array();
349
350 foreach ( $mod->getMessages() as $key ) {
351 $messages[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
352 }
353
354 return FormatJson::encode( $messages );
355 }
356 }