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