Merge "DatabaseMssql: Don't duplicate body of makeList()"
[lhc/web/wiklou.git] / includes / MessageBlobStore.php
1 <?php
2 /**
3 * Resource message blobs storage used by the resource loader.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
23 */
24
25 /**
26 * This class provides access to the resource message blobs storage used by
27 * the ResourceLoader.
28 *
29 * A message blob is a JSON object containing the interface messages for a
30 * certain resource in a certain language. These message blobs are cached
31 * in the msg_resource table and automatically invalidated when one of their
32 * constituent messages or the resource itself is changed.
33 */
34 class MessageBlobStore {
35 /**
36 * Get the singleton instance
37 *
38 * @since 1.24
39 * @return MessageBlobStore
40 */
41 public static function getInstance() {
42 static $instance = null;
43 if ( $instance === null ) {
44 $instance = new self;
45 }
46
47 return $instance;
48 }
49
50 /**
51 * Get the message blobs for a set of modules
52 *
53 * @param ResourceLoader $resourceLoader
54 * @param array $modules Array of module objects keyed by module name
55 * @param string $lang Language code
56 * @return array An array mapping module names to message blobs
57 */
58 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
59 if ( !count( $modules ) ) {
60 return array();
61 }
62 // Try getting from the DB first
63 $blobs = $this->getFromDB( $resourceLoader, array_keys( $modules ), $lang );
64
65 // Generate blobs for any missing modules and store them in the DB
66 $missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
67 foreach ( $missing as $name ) {
68 $blob = $this->insertMessageBlob( $name, $modules[$name], $lang );
69 if ( $blob ) {
70 $blobs[$name] = $blob;
71 }
72 }
73
74 return $blobs;
75 }
76
77 /**
78 * Generate and insert a new message blob. If the blob was already
79 * present, it is not regenerated; instead, the preexisting blob
80 * is fetched and returned.
81 *
82 * @param string $name Module name
83 * @param ResourceLoaderModule $module
84 * @param string $lang Language code
85 * @return mixed Message blob or false if the module has no messages
86 */
87 public function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
88 $blob = $this->generateMessageBlob( $module, $lang );
89
90 if ( !$blob ) {
91 return false;
92 }
93
94 try {
95 $dbw = wfGetDB( DB_MASTER );
96 $success = $dbw->insert( 'msg_resource', array(
97 'mr_lang' => $lang,
98 'mr_resource' => $name,
99 'mr_blob' => $blob,
100 'mr_timestamp' => $dbw->timestamp()
101 ),
102 __METHOD__,
103 array( 'IGNORE' )
104 );
105
106 if ( $success ) {
107 if ( $dbw->affectedRows() == 0 ) {
108 // Blob was already present, fetch it
109 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
110 'mr_resource' => $name,
111 'mr_lang' => $lang,
112 ),
113 __METHOD__
114 );
115 } else {
116 // Update msg_resource_links
117 $rows = array();
118
119 foreach ( $module->getMessages() as $key ) {
120 $rows[] = array(
121 'mrl_resource' => $name,
122 'mrl_message' => $key
123 );
124 }
125 $dbw->insert( 'msg_resource_links', $rows,
126 __METHOD__, array( 'IGNORE' )
127 );
128 }
129 }
130 } catch ( Exception $e ) {
131 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
132 }
133 return $blob;
134 }
135
136 /**
137 * Update the message blob for a given module in a given language
138 *
139 * @param string $name Module name
140 * @param ResourceLoaderModule $module
141 * @param string $lang Language code
142 * @return string Regenerated message blob, or null if there was no blob for
143 * the given module/language pair.
144 */
145 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
146 $dbw = wfGetDB( DB_MASTER );
147 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
148 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
149 __METHOD__
150 );
151 if ( !$row ) {
152 return null;
153 }
154
155 // Save the old and new blobs for later
156 $oldBlob = $row->mr_blob;
157 $newBlob = $this->generateMessageBlob( $module, $lang );
158
159 try {
160 $newRow = array(
161 'mr_resource' => $name,
162 'mr_lang' => $lang,
163 'mr_blob' => $newBlob,
164 'mr_timestamp' => $dbw->timestamp()
165 );
166
167 $dbw->replace( 'msg_resource',
168 array( array( 'mr_resource', 'mr_lang' ) ),
169 $newRow, __METHOD__
170 );
171
172 // Figure out which messages were added and removed
173 $oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
174 $newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
175 $added = array_diff( $newMessages, $oldMessages );
176 $removed = array_diff( $oldMessages, $newMessages );
177
178 // Delete removed messages, insert added ones
179 if ( $removed ) {
180 $dbw->delete( 'msg_resource_links', array(
181 'mrl_resource' => $name,
182 'mrl_message' => $removed
183 ), __METHOD__
184 );
185 }
186
187 $newLinksRows = array();
188
189 foreach ( $added as $message ) {
190 $newLinksRows[] = array(
191 'mrl_resource' => $name,
192 'mrl_message' => $message
193 );
194 }
195
196 if ( $newLinksRows ) {
197 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
198 array( 'IGNORE' ) // just in case
199 );
200 }
201 } catch ( Exception $e ) {
202 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
203 }
204 return $newBlob;
205 }
206
207 /**
208 * Update a single message in all message blobs it occurs in.
209 *
210 * @param string $key Message key
211 */
212 public function updateMessage( $key ) {
213 try {
214 $dbw = wfGetDB( DB_MASTER );
215
216 // Keep running until the updates queue is empty.
217 // Due to update conflicts, the queue might not be emptied
218 // in one iteration.
219 $updates = null;
220 do {
221 $updates = $this->getUpdatesForMessage( $key, $updates );
222
223 foreach ( $updates as $k => $update ) {
224 // Update the row on the condition that it
225 // didn't change since we fetched it by putting
226 // the timestamp in the WHERE clause.
227 $success = $dbw->update( 'msg_resource',
228 array(
229 'mr_blob' => $update['newBlob'],
230 'mr_timestamp' => $dbw->timestamp() ),
231 array(
232 'mr_resource' => $update['resource'],
233 'mr_lang' => $update['lang'],
234 'mr_timestamp' => $update['timestamp'] ),
235 __METHOD__
236 );
237
238 // Only requeue conflicted updates.
239 // If update() returned false, don't retry, for
240 // fear of getting into an infinite loop
241 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
242 // Not conflicted
243 unset( $updates[$k] );
244 }
245 }
246 } while ( count( $updates ) );
247
248 // No need to update msg_resource_links because we didn't add
249 // or remove any messages, we just changed their contents.
250 } catch ( Exception $e ) {
251 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
252 }
253 }
254
255 public function clear() {
256 // TODO: Give this some more thought
257 try {
258 // Not using TRUNCATE, because that needs extra permissions,
259 // which maybe not granted to the database user.
260 $dbw = wfGetDB( DB_MASTER );
261 $dbw->delete( 'msg_resource', '*', __METHOD__ );
262 $dbw->delete( 'msg_resource_links', '*', __METHOD__ );
263 } catch ( Exception $e ) {
264 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
265 }
266 }
267
268 /**
269 * Create an update queue for updateMessage()
270 *
271 * @param string $key Message key
272 * @param array $prevUpdates Updates queue to refresh or null to build a fresh update queue
273 * @return array Updates queue
274 */
275 private function getUpdatesForMessage( $key, $prevUpdates = null ) {
276 $dbw = wfGetDB( DB_MASTER );
277
278 if ( is_null( $prevUpdates ) ) {
279 // Fetch all blobs referencing $key
280 $res = $dbw->select(
281 array( 'msg_resource', 'msg_resource_links' ),
282 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
283 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
284 __METHOD__
285 );
286 } else {
287 // Refetch the blobs referenced by $prevUpdates
288
289 // Reorganize the (resource, lang) pairs in the format
290 // expected by makeWhereFrom2d()
291 $twoD = array();
292
293 foreach ( $prevUpdates as $update ) {
294 $twoD[$update['resource']][$update['lang']] = true;
295 }
296
297 $res = $dbw->select( 'msg_resource',
298 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
299 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
300 __METHOD__
301 );
302 }
303
304 // Build the new updates queue
305 $updates = array();
306
307 foreach ( $res as $row ) {
308 $updates[] = array(
309 'resource' => $row->mr_resource,
310 'lang' => $row->mr_lang,
311 'timestamp' => $row->mr_timestamp,
312 'newBlob' => $this->reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
313 );
314 }
315
316 return $updates;
317 }
318
319 /**
320 * Reencode a message blob with the updated value for a message
321 *
322 * @param string $blob Message blob (JSON object)
323 * @param string $key Message key
324 * @param string $lang Language code
325 * @return string Message blob with $key replaced with its new value
326 */
327 private function reencodeBlob( $blob, $key, $lang ) {
328 $decoded = FormatJson::decode( $blob, true );
329 $decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
330
331 return FormatJson::encode( (object)$decoded );
332 }
333
334 /**
335 * Get the message blobs for a set of modules from the database.
336 * Modules whose blobs are not in the database are silently dropped.
337 *
338 * @param ResourceLoader $resourceLoader
339 * @param array $modules Array of module names
340 * @param string $lang Language code
341 * @throws MWException
342 * @return array Array mapping module names to blobs
343 */
344 private function getFromDB( ResourceLoader $resourceLoader, $modules, $lang ) {
345 $config = $resourceLoader->getConfig();
346 $retval = array();
347 $dbr = wfGetDB( DB_SLAVE );
348 $res = $dbr->select( 'msg_resource',
349 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
350 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
351 __METHOD__
352 );
353
354 foreach ( $res as $row ) {
355 $module = $resourceLoader->getModule( $row->mr_resource );
356 if ( !$module ) {
357 // This shouldn't be possible
358 throw new MWException( __METHOD__ . ' passed an invalid module name' );
359 }
360
361 // Update the module's blobs if the set of messages changed or if the blob is
362 // older than the CacheEpoch setting
363 $keys = array_keys( FormatJson::decode( $row->mr_blob, true ) );
364 $values = array_values( array_unique( $module->getMessages() ) );
365 if ( $keys !== $values
366 || wfTimestamp( TS_MW, $row->mr_timestamp ) <= $config->get( 'CacheEpoch' )
367 ) {
368 $retval[$row->mr_resource] = $this->updateModule( $row->mr_resource, $module, $lang );
369 } else {
370 $retval[$row->mr_resource] = $row->mr_blob;
371 }
372 }
373
374 return $retval;
375 }
376
377 /**
378 * Generate the message blob for a given module in a given language.
379 *
380 * @param ResourceLoaderModule $module
381 * @param string $lang Language code
382 * @return string JSON object
383 */
384 private function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
385 $messages = array();
386
387 foreach ( $module->getMessages() as $key ) {
388 $messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
389 }
390
391 return FormatJson::encode( (object)$messages );
392 }
393 }