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