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