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