Merge "Add hook EnhancedChangesList::getLogText"
[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 $dbw->startAtomic( __METHOD__ );
97 $success = $dbw->insert( 'msg_resource', array(
98 'mr_lang' => $lang,
99 'mr_resource' => $name,
100 'mr_blob' => $blob,
101 'mr_timestamp' => $dbw->timestamp()
102 ),
103 __METHOD__,
104 array( 'IGNORE' )
105 );
106
107 if ( $success ) {
108 if ( $dbw->affectedRows() == 0 ) {
109 // Blob was already present, fetch it
110 $blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
111 'mr_resource' => $name,
112 'mr_lang' => $lang,
113 ),
114 __METHOD__
115 );
116 } else {
117 // Update msg_resource_links
118 $rows = array();
119
120 foreach ( $module->getMessages() as $key ) {
121 $rows[] = array(
122 'mrl_resource' => $name,
123 'mrl_message' => $key
124 );
125 }
126 $dbw->insert( 'msg_resource_links', $rows,
127 __METHOD__, array( 'IGNORE' )
128 );
129 }
130 }
131 $dbw->endAtomic( __METHOD__ );
132 } catch ( DBError $e ) {
133 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
134 }
135 return $blob;
136 }
137
138 /**
139 * Update the message blob for a given module in a given language
140 *
141 * @param string $name Module name
142 * @param ResourceLoaderModule $module
143 * @param string $lang Language code
144 * @return string Regenerated message blob, or null if there was no blob for
145 * the given module/language pair.
146 */
147 public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
148 $dbw = wfGetDB( DB_MASTER );
149 $row = $dbw->selectRow( 'msg_resource', 'mr_blob',
150 array( 'mr_resource' => $name, 'mr_lang' => $lang ),
151 __METHOD__
152 );
153 if ( !$row ) {
154 return null;
155 }
156
157 // Save the old and new blobs for later
158 $oldBlob = $row->mr_blob;
159 $newBlob = $this->generateMessageBlob( $module, $lang );
160
161 try {
162 $newRow = array(
163 'mr_resource' => $name,
164 'mr_lang' => $lang,
165 'mr_blob' => $newBlob,
166 'mr_timestamp' => $dbw->timestamp()
167 );
168
169 $dbw->replace( 'msg_resource',
170 array( array( 'mr_resource', 'mr_lang' ) ),
171 $newRow, __METHOD__
172 );
173
174 // Figure out which messages were added and removed
175 $oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
176 $newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
177 $added = array_diff( $newMessages, $oldMessages );
178 $removed = array_diff( $oldMessages, $newMessages );
179
180 // Delete removed messages, insert added ones
181 if ( $removed ) {
182 $dbw->delete( 'msg_resource_links', array(
183 'mrl_resource' => $name,
184 'mrl_message' => $removed
185 ), __METHOD__
186 );
187 }
188
189 $newLinksRows = array();
190
191 foreach ( $added as $message ) {
192 $newLinksRows[] = array(
193 'mrl_resource' => $name,
194 'mrl_message' => $message
195 );
196 }
197
198 if ( $newLinksRows ) {
199 $dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
200 array( 'IGNORE' ) // just in case
201 );
202 }
203 } catch ( Exception $e ) {
204 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
205 }
206 return $newBlob;
207 }
208
209 /**
210 * Update a single message in all message blobs it occurs in.
211 *
212 * @param string $key Message key
213 */
214 public function updateMessage( $key ) {
215 try {
216 $dbw = wfGetDB( DB_MASTER );
217
218 // Keep running until the updates queue is empty.
219 // Due to update conflicts, the queue might not be emptied
220 // in one iteration.
221 $updates = null;
222 do {
223 $updates = $this->getUpdatesForMessage( $key, $updates );
224
225 foreach ( $updates as $k => $update ) {
226 // Update the row on the condition that it
227 // didn't change since we fetched it by putting
228 // the timestamp in the WHERE clause.
229 $success = $dbw->update( 'msg_resource',
230 array(
231 'mr_blob' => $update['newBlob'],
232 'mr_timestamp' => $dbw->timestamp() ),
233 array(
234 'mr_resource' => $update['resource'],
235 'mr_lang' => $update['lang'],
236 'mr_timestamp' => $update['timestamp'] ),
237 __METHOD__
238 );
239
240 // Only requeue conflicted updates.
241 // If update() returned false, don't retry, for
242 // fear of getting into an infinite loop
243 if ( !( $success && $dbw->affectedRows() == 0 ) ) {
244 // Not conflicted
245 unset( $updates[$k] );
246 }
247 }
248 } while ( count( $updates ) );
249
250 // No need to update msg_resource_links because we didn't add
251 // or remove any messages, we just changed their contents.
252 } catch ( Exception $e ) {
253 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
254 }
255 }
256
257 public function clear() {
258 // TODO: Give this some more thought
259 try {
260 // Not using TRUNCATE, because that needs extra permissions,
261 // which maybe not granted to the database user.
262 $dbw = wfGetDB( DB_MASTER );
263 $dbw->delete( 'msg_resource', '*', __METHOD__ );
264 $dbw->delete( 'msg_resource_links', '*', __METHOD__ );
265 } catch ( Exception $e ) {
266 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
267 }
268 }
269
270 /**
271 * Create an update queue for updateMessage()
272 *
273 * @param string $key Message key
274 * @param array $prevUpdates Updates queue to refresh or null to build a fresh update queue
275 * @return array Updates queue
276 */
277 private function getUpdatesForMessage( $key, $prevUpdates = null ) {
278 $dbw = wfGetDB( DB_MASTER );
279
280 if ( is_null( $prevUpdates ) ) {
281 // Fetch all blobs referencing $key
282 $res = $dbw->select(
283 array( 'msg_resource', 'msg_resource_links' ),
284 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
285 array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
286 __METHOD__
287 );
288 } else {
289 // Refetch the blobs referenced by $prevUpdates
290
291 // Reorganize the (resource, lang) pairs in the format
292 // expected by makeWhereFrom2d()
293 $twoD = array();
294
295 foreach ( $prevUpdates as $update ) {
296 $twoD[$update['resource']][$update['lang']] = true;
297 }
298
299 $res = $dbw->select( 'msg_resource',
300 array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
301 $dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
302 __METHOD__
303 );
304 }
305
306 // Build the new updates queue
307 $updates = array();
308
309 foreach ( $res as $row ) {
310 $updates[] = array(
311 'resource' => $row->mr_resource,
312 'lang' => $row->mr_lang,
313 'timestamp' => $row->mr_timestamp,
314 'newBlob' => $this->reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
315 );
316 }
317
318 return $updates;
319 }
320
321 /**
322 * Reencode a message blob with the updated value for a message
323 *
324 * @param string $blob Message blob (JSON object)
325 * @param string $key Message key
326 * @param string $lang Language code
327 * @return string Message blob with $key replaced with its new value
328 */
329 private function reencodeBlob( $blob, $key, $lang ) {
330 $decoded = FormatJson::decode( $blob, true );
331 $decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
332
333 return FormatJson::encode( (object)$decoded );
334 }
335
336 /**
337 * Get the message blobs for a set of modules from the database.
338 * Modules whose blobs are not in the database are silently dropped.
339 *
340 * @param ResourceLoader $resourceLoader
341 * @param array $modules Array of module names
342 * @param string $lang Language code
343 * @throws MWException
344 * @return array Array mapping module names to blobs
345 */
346 private function getFromDB( ResourceLoader $resourceLoader, $modules, $lang ) {
347 $config = $resourceLoader->getConfig();
348 $retval = array();
349 $dbr = wfGetDB( DB_SLAVE );
350 $res = $dbr->select( 'msg_resource',
351 array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
352 array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
353 __METHOD__
354 );
355
356 foreach ( $res as $row ) {
357 $module = $resourceLoader->getModule( $row->mr_resource );
358 if ( !$module ) {
359 // This shouldn't be possible
360 throw new MWException( __METHOD__ . ' passed an invalid module name' );
361 }
362
363 // Update the module's blobs if the set of messages changed or if the blob is
364 // older than the CacheEpoch setting
365 $keys = array_keys( FormatJson::decode( $row->mr_blob, true ) );
366 $values = array_values( array_unique( $module->getMessages() ) );
367 if ( $keys !== $values
368 || wfTimestamp( TS_MW, $row->mr_timestamp ) <= $config->get( 'CacheEpoch' )
369 ) {
370 $retval[$row->mr_resource] = $this->updateModule( $row->mr_resource, $module, $lang );
371 } else {
372 $retval[$row->mr_resource] = $row->mr_blob;
373 }
374 }
375
376 return $retval;
377 }
378
379 /**
380 * Generate the message blob for a given module in a given language.
381 *
382 * @param ResourceLoaderModule $module
383 * @param string $lang Language code
384 * @return string JSON object
385 */
386 private function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
387 $messages = array();
388
389 foreach ( $module->getMessages() as $key ) {
390 $messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
391 }
392
393 return FormatJson::encode( (object)$messages );
394 }
395 }