Add support for Number grouping(commafy) based on CLDR number grouping patterns like...
[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 /**
34 * Get the message blobs for a set of modules
35 *
36 * @param $resourceLoader ResourceLoader object
37 * @param $modules array Array of module objects keyed by module name
38 * @param $lang string Language code
39 * @return array An array mapping module names to message blobs
40 */
41 public static function get( ResourceLoader $resourceLoader, $modules, $lang ) {
42 wfProfileIn( __METHOD__ );
43 if ( !count( $modules ) ) {
44 wfProfileOut( __METHOD__ );
45 return array();
46 }
47 // Try getting from the DB first
48 $blobs = self::getFromDB( $resourceLoader, array_keys( $modules ), $lang );
49
50 // Generate blobs for any missing modules and store them in the DB
51 $missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
52 foreach ( $missing as $name ) {
53 $blob = self::insertMessageBlob( $name, $modules[$name], $lang );
54 if ( $blob ) {
55 $blobs[$name] = $blob;
56 }
57 }
58
59 wfProfileOut( __METHOD__ );
60 return $blobs;
61 }
62
63 /**
64 * Generate and insert a new message blob. If the blob was already
65 * present, it is not regenerated; instead, the preexisting blob
66 * is fetched and returned.
67 *
68 * @param $name String: module name
69 * @param $module ResourceLoaderModule object
70 * @param $lang String: language code
71 * @return mixed Message blob or false if the module has no messages
72 */
73 public static function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
74 $blob = self::generateMessageBlob( $module, $lang );
75
76 if ( !$blob ) {
77 return false;
78 }
79
80 $dbw = wfGetDB( DB_MASTER );
81 $success = $dbw->insert( 'msg_resource', array(
82 'mr_lang' => $lang,
83 'mr_resource' => $name,
84 'mr_blob' => $blob,
85 'mr_timestamp' => $dbw->timestamp()
86 ),
87 __METHOD__,
88 array( 'IGNORE' )
89 );
90
91 if ( $success ) {
92 if ( $dbw->affectedRows() == 0 ) {
93 // Blob was already present, fetch it
94 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
95 'mr_resource' => $name,
96 'mr_lang' => $lang,
97 ),
98 __METHOD__
99 );
100 } else {
101 // Update msg_resource_links
102 $rows = array();
103
104 foreach ( $module->getMessages() as $key ) {
105 $rows[] = array(
106 'mrl_resource' => $name,
107 'mrl_message' => $key
108 );
109 }
110 $dbw->insert( 'msg_resource_links', $rows,
111 __METHOD__, array( 'IGNORE' )
112 );
113 }
114 }
115
116 return $blob;
117 }
118
119 /**
120 * Update the message blob for a given module in a given language
121 *
122 * @param $name String: module name
123 * @param $module ResourceLoaderModule object
124 * @param $lang String: language code
125 * @return String Regenerated message blob, or null if there was no blob for the given module/language pair
126 */
127 public static function updateModule( $name, ResourceLoaderModule $module, $lang ) {
128 $dbw = wfGetDB( DB_MASTER );
129 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
130 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
131 __METHOD__
132 );
133 if ( !$row ) {
134 return null;
135 }
136
137 // Save the old and new blobs for later
138 $oldBlob = $row->mr_blob;
139 $newBlob = self::generateMessageBlob( $module, $lang );
140
141 $newRow = array(
142 'mr_resource' => $name,
143 'mr_lang' => $lang,
144 'mr_blob' => $newBlob,
145 'mr_timestamp' => $dbw->timestamp()
146 );
147
148 $dbw->replace( 'msg_resource',
149 array( array( 'mr_resource', 'mr_lang' ) ),
150 $newRow, __METHOD__
151 );
152
153 // Figure out which messages were added and removed
154 $oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
155 $newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
156 $added = array_diff( $newMessages, $oldMessages );
157 $removed = array_diff( $oldMessages, $newMessages );
158
159 // Delete removed messages, insert added ones
160 if ( $removed ) {
161 $dbw->delete( 'msg_resource_links', array(
162 'mrl_resource' => $name,
163 'mrl_message' => $removed
164 ), __METHOD__
165 );
166 }
167
168 $newLinksRows = array();
169
170 foreach ( $added as $message ) {
171 $newLinksRows[] = array(
172 'mrl_resource' => $name,
173 'mrl_message' => $message
174 );
175 }
176
177 if ( $newLinksRows ) {
178 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
179 array( 'IGNORE' ) // just in case
180 );
181 }
182
183 return $newBlob;
184 }
185
186 /**
187 * Update a single message in all message blobs it occurs in.
188 *
189 * @param $key String: message key
190 */
191 public static function updateMessage( $key ) {
192 $dbw = wfGetDB( DB_MASTER );
193
194 // Keep running until the updates queue is empty.
195 // Due to update conflicts, the queue might not be emptied
196 // in one iteration.
197 $updates = null;
198 do {
199 $updates = self::getUpdatesForMessage( $key, $updates );
200
201 foreach ( $updates as $k => $update ) {
202 // Update the row on the condition that it
203 // didn't change since we fetched it by putting
204 // the timestamp in the WHERE clause.
205 $success = $dbw->update( 'msg_resource',
206 array(
207 'mr_blob' => $update['newBlob'],
208 'mr_timestamp' => $dbw->timestamp() ),
209 array(
210 '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[$k] );
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 *
241 * @param $key String: message key
242 * @param $prevUpdates Array: updates queue to refresh or null to build a fresh update queue
243 * @return Array: updates queue
244 */
245 private static function getUpdatesForMessage( $key, $prevUpdates = null ) {
246 $dbw = wfGetDB( DB_MASTER );
247
248 if ( is_null( $prevUpdates ) ) {
249 // Fetch all blobs referencing $key
250 $res = $dbw->select(
251 array( 'msg_resource', 'msg_resource_links' ),
252 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
253 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
254 __METHOD__
255 );
256 } else {
257 // Refetch the blobs referenced by $prevUpdates
258
259 // Reorganize the (resource, lang) pairs in the format
260 // expected by makeWhereFrom2d()
261 $twoD = array();
262
263 foreach ( $prevUpdates as $update ) {
264 $twoD[$update['resource']][$update['lang']] = true;
265 }
266
267 $res = $dbw->select( 'msg_resource',
268 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
269 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
270 __METHOD__
271 );
272 }
273
274 // Build the new updates queue
275 $updates = array();
276
277 foreach ( $res as $row ) {
278 $updates[] = array(
279 'resource' => $row->mr_resource,
280 'lang' => $row->mr_lang,
281 'timestamp' => $row->mr_timestamp,
282 'newBlob' => self::reencodeBlob( $row->mr_blob, $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 *
292 * @param $blob String: message blob (JSON object)
293 * @param $key String: message key
294 * @param $lang String: language code
295 * @return Message blob with $key replaced with its new value
296 */
297 private static function reencodeBlob( $blob, $key, $lang ) {
298 $decoded = FormatJson::decode( $blob, true );
299 $decoded[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
300
301 return FormatJson::encode( (object)$decoded );
302 }
303
304 /**
305 * Get the message blobs for a set of modules from the database.
306 * Modules whose blobs are not in the database are silently dropped.
307 *
308 * @param $resourceLoader ResourceLoader object
309 * @param $modules Array of module names
310 * @param $lang String: language code
311 * @return array Array mapping module names to blobs
312 */
313 private static function getFromDB( ResourceLoader $resourceLoader, $modules, $lang ) {
314 global $wgCacheEpoch;
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 // Update the module's blobs if the set of messages changed or if the blob is
330 // older than $wgCacheEpoch
331 if ( array_keys( FormatJson::decode( $row->mr_blob, true ) ) !== array_values( array_unique( $module->getMessages() ) ) ||
332 wfTimestamp( TS_MW, $row->mr_timestamp ) <= $wgCacheEpoch ) {
333 $retval[$row->mr_resource] = self::updateModule( $row->mr_resource, $module, $lang );
334 } else {
335 $retval[$row->mr_resource] = $row->mr_blob;
336 }
337 }
338
339 return $retval;
340 }
341
342 /**
343 * Generate the message blob for a given module in a given language.
344 *
345 * @param $module ResourceLoaderModule object
346 * @param $lang String: language code
347 * @return String: JSON object
348 */
349 private static function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
350 $messages = array();
351
352 foreach ( $module->getMessages() as $key ) {
353 $messages[$key] = wfMsgExt( $key, array( 'language' => $lang ) );
354 }
355
356 return FormatJson::encode( (object)$messages );
357 }
358 }