summaryrefslogtreecommitdiff
path: root/includes/MessageBlobStore.php
blob: c96ea56ea6a7b67fb88220d29a63a61db5763fe3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
/**
 * Resource message blobs storage used by the resource loader.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Roan Kattouw
 * @author Trevor Parscal
 */

/**
 * This class provides access to the resource message blobs storage used by
 * the ResourceLoader.
 *
 * A message blob is a JSON object containing the interface messages for a
 * certain resource in a certain language. These message blobs are cached
 * in the msg_resource table and automatically invalidated when one of their
 * consistuent messages or the resource itself is changed.
 */
class MessageBlobStore {

	/**
	 * Get the message blobs for a set of modules
	 *
	 * @param $resourceLoader ResourceLoader object
	 * @param $modules array Array of module objects keyed by module name
	 * @param $lang string Language code
	 * @return array An array mapping module names to message blobs
	 */
	public static function get( ResourceLoader $resourceLoader, $modules, $lang ) {
		wfProfileIn( __METHOD__ );
		if ( !count( $modules ) ) {
			wfProfileOut( __METHOD__ );
			return array();
		}
		// Try getting from the DB first
		$blobs = self::getFromDB( $resourceLoader, array_keys( $modules ), $lang );

		// Generate blobs for any missing modules and store them in the DB
		$missing = array_diff( array_keys( $modules ), array_keys( $blobs ) );
		foreach ( $missing as $name ) {
			$blob = self::insertMessageBlob( $name, $modules[$name], $lang );
			if ( $blob ) {
				$blobs[$name] = $blob;
			}
		}

		wfProfileOut( __METHOD__ );
		return $blobs;
	}

	/**
	 * Generate and insert a new message blob. If the blob was already
	 * present, it is not regenerated; instead, the preexisting blob
	 * is fetched and returned.
	 *
	 * @param $name String: module name
	 * @param $module ResourceLoaderModule object
	 * @param $lang String: language code
	 * @return mixed Message blob or false if the module has no messages
	 */
	public static function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
		$blob = self::generateMessageBlob( $module, $lang );

		if ( !$blob ) {
			return false;
		}

		try {
			$dbw = wfGetDB( DB_MASTER );
			$success = $dbw->insert( 'msg_resource', array(
					'mr_lang' => $lang,
					'mr_resource' => $name,
					'mr_blob' => $blob,
					'mr_timestamp' => $dbw->timestamp()
				),
				__METHOD__,
				array( 'IGNORE' )
			);

			if ( $success ) {
				if ( $dbw->affectedRows() == 0 ) {
					// Blob was already present, fetch it
					$blob = $dbw->selectField( 'msg_resource', 'mr_blob', array(
							'mr_resource' => $name,
							'mr_lang' => $lang,
						),
						__METHOD__
					);
				} else {
					// Update msg_resource_links
					$rows = array();

					foreach ( $module->getMessages() as $key ) {
						$rows[] = array(
							'mrl_resource' => $name,
							'mrl_message' => $key
						);
					}
					$dbw->insert( 'msg_resource_links', $rows,
						__METHOD__, array( 'IGNORE' )
					);
				}
			}
		} catch ( Exception $e ) {
			wfDebug( __METHOD__ . " failed to update DB: $e\n" );
		}
		return $blob;
	}

	/**
	 * Update the message blob for a given module in a given language
	 *
	 * @param $name String: module name
	 * @param $module ResourceLoaderModule object
	 * @param $lang String: language code
	 * @return String Regenerated message blob, or null if there was no blob for the given module/language pair
	 */
	public static function updateModule( $name, ResourceLoaderModule $module, $lang ) {
		$dbw = wfGetDB( DB_MASTER );
		$row = $dbw->selectRow( 'msg_resource', 'mr_blob',
			array( 'mr_resource' => $name, 'mr_lang' => $lang ),
			__METHOD__
		);
		if ( !$row ) {
			return null;
		}

		// Save the old and new blobs for later
		$oldBlob = $row->mr_blob;
		$newBlob = self::generateMessageBlob( $module, $lang );

		try {
			$newRow = array(
				'mr_resource' => $name,
				'mr_lang' => $lang,
				'mr_blob' => $newBlob,
				'mr_timestamp' => $dbw->timestamp()
			);

			$dbw->replace( 'msg_resource',
				array( array( 'mr_resource', 'mr_lang' ) ),
				$newRow, __METHOD__
			);

			// Figure out which messages were added and removed
			$oldMessages = array_keys( FormatJson::decode( $oldBlob, true ) );
			$newMessages = array_keys( FormatJson::decode( $newBlob, true ) );
			$added = array_diff( $newMessages, $oldMessages );
			$removed = array_diff( $oldMessages, $newMessages );

			// Delete removed messages, insert added ones
			if ( $removed ) {
				$dbw->delete( 'msg_resource_links', array(
						'mrl_resource' => $name,
						'mrl_message' => $removed
					), __METHOD__
				);
			}

			$newLinksRows = array();

			foreach ( $added as $message ) {
				$newLinksRows[] = array(
					'mrl_resource' => $name,
					'mrl_message' => $message
				);
			}

			if ( $newLinksRows ) {
				$dbw->insert( 'msg_resource_links', $newLinksRows, __METHOD__,
					array( 'IGNORE' ) // just in case
				);
			}
		} catch ( Exception $e ) {
			wfDebug( __METHOD__ . " failed to update DB: $e\n" );
		}
		return $newBlob;
	}

	/**
	 * Update a single message in all message blobs it occurs in.
	 *
	 * @param $key String: message key
	 */
	public static function updateMessage( $key ) {
		try {
			$dbw = wfGetDB( DB_MASTER );

			// Keep running until the updates queue is empty.
			// Due to update conflicts, the queue might not be emptied
			// in one iteration.
			$updates = null;
			do {
				$updates = self::getUpdatesForMessage( $key, $updates );

				foreach ( $updates as $k => $update ) {
					// Update the row on the condition that it
					// didn't change since we fetched it by putting
					// the timestamp in the WHERE clause.
					$success = $dbw->update( 'msg_resource',
						array(
							'mr_blob' => $update['newBlob'],
							'mr_timestamp' => $dbw->timestamp() ),
						array(
							'mr_resource' => $update['resource'],
							'mr_lang' => $update['lang'],
							'mr_timestamp' => $update['timestamp'] ),
						__METHOD__
					);

					// Only requeue conflicted updates.
					// If update() returned false, don't retry, for
					// fear of getting into an infinite loop
					if ( !( $success && $dbw->affectedRows() == 0 ) ) {
						// Not conflicted
						unset( $updates[$k] );
					}
				}
			} while ( count( $updates ) );

			// No need to update msg_resource_links because we didn't add
			// or remove any messages, we just changed their contents.
		} catch ( Exception $e ) {
			wfDebug( __METHOD__ . " failed to update DB: $e\n" );
		}
	}

	public static function clear() {
		// TODO: Give this some more thought
		// TODO: Is TRUNCATE better?
		try {
			$dbw = wfGetDB( DB_MASTER );
			$dbw->delete( 'msg_resource', '*', __METHOD__ );
			$dbw->delete( 'msg_resource_links', '*', __METHOD__ );
		} catch ( Exception $e ) {
			wfDebug( __METHOD__ . " failed to update DB: $e\n" );
		}
	}

	/**
	 * Create an update queue for updateMessage()
	 *
	 * @param $key String: message key
	 * @param $prevUpdates Array: updates queue to refresh or null to build a fresh update queue
	 * @return Array: updates queue
	 */
	private static function getUpdatesForMessage( $key, $prevUpdates = null ) {
		$dbw = wfGetDB( DB_MASTER );

		if ( is_null( $prevUpdates ) ) {
			// Fetch all blobs referencing $key
			$res = $dbw->select(
				array( 'msg_resource', 'msg_resource_links' ),
				array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
				array( 'mrl_message' => $key, 'mr_resource=mrl_resource' ),
				__METHOD__
			);
		} else {
			// Refetch the blobs referenced by $prevUpdates

			// Reorganize the (resource, lang) pairs in the format
			// expected by makeWhereFrom2d()
			$twoD = array();

			foreach ( $prevUpdates as $update ) {
				$twoD[$update['resource']][$update['lang']] = true;
			}

			$res = $dbw->select( 'msg_resource',
				array( 'mr_resource', 'mr_lang', 'mr_blob', 'mr_timestamp' ),
				$dbw->makeWhereFrom2d( $twoD, 'mr_resource', 'mr_lang' ),
				__METHOD__
			);
		}

		// Build the new updates queue
		$updates = array();

		foreach ( $res as $row ) {
			$updates[] = array(
				'resource' => $row->mr_resource,
				'lang' => $row->mr_lang,
				'timestamp' => $row->mr_timestamp,
				'newBlob' => self::reencodeBlob( $row->mr_blob, $key, $row->mr_lang )
			);
		}

		return $updates;
	}

	/**
	 * Reencode a message blob with the updated value for a message
	 *
	 * @param $blob String: message blob (JSON object)
	 * @param $key String: message key
	 * @param $lang String: language code
	 * @return Message blob with $key replaced with its new value
	 */
	private static function reencodeBlob( $blob, $key, $lang ) {
		$decoded = FormatJson::decode( $blob, true );
		$decoded[$key] = wfMessage( $key )->inLanguage( $lang )->plain();

		return FormatJson::encode( (object)$decoded );
	}

	/**
	 * Get the message blobs for a set of modules from the database.
	 * Modules whose blobs are not in the database are silently dropped.
	 *
	 * @param $resourceLoader ResourceLoader object
	 * @param $modules Array of module names
	 * @param $lang String: language code
	 * @return array Array mapping module names to blobs
	 */
	private static function getFromDB( ResourceLoader $resourceLoader, $modules, $lang ) {
		global $wgCacheEpoch;
		$retval = array();
		$dbr = wfGetDB( DB_SLAVE );
		$res = $dbr->select( 'msg_resource',
			array( 'mr_blob', 'mr_resource', 'mr_timestamp' ),
			array( 'mr_resource' => $modules, 'mr_lang' => $lang ),
			__METHOD__
		);

		foreach ( $res as $row ) {
			$module = $resourceLoader->getModule( $row->mr_resource );
			if ( !$module ) {
				// This shouldn't be possible
				throw new MWException( __METHOD__ . ' passed an invalid module name' );
			}
			// Update the module's blobs if the set of messages changed or if the blob is
			// older than $wgCacheEpoch
			if ( array_keys( FormatJson::decode( $row->mr_blob, true ) ) !== array_values( array_unique( $module->getMessages() ) ) ||
					wfTimestamp( TS_MW, $row->mr_timestamp ) <= $wgCacheEpoch ) {
				$retval[$row->mr_resource] = self::updateModule( $row->mr_resource, $module, $lang );
			} else {
				$retval[$row->mr_resource] = $row->mr_blob;
			}
		}

		return $retval;
	}

	/**
	 * Generate the message blob for a given module in a given language.
	 *
	 * @param $module ResourceLoaderModule object
	 * @param $lang String: language code
	 * @return String: JSON object
	 */
	private static function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
		$messages = array();

		foreach ( $module->getMessages() as $key ) {
			$messages[$key] = wfMessage( $key )->inLanguage( $lang )->plain();
		}

		return FormatJson::encode( (object)$messages );
	}
}