Merge "Handle missing namespace prefix in XML dumps more gracefully"
[lhc/web/wiklou.git] / includes / cache / MessageBlobStore.php
1 <?php
2 /**
3 * Message blobs storage used by ResourceLoader.
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 * @author Timo Tijhof
24 */
25
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\NullLogger;
29
30 /**
31 * This class generates message blobs for use by ResourceLoader modules.
32 *
33 * A message blob is a JSON object containing the interface messages for a certain module in
34 * a certain language.
35 */
36 class MessageBlobStore implements LoggerAwareInterface {
37
38 /* @var ResourceLoader|null */
39 private $resourceloader;
40
41 /**
42 * @var LoggerInterface
43 */
44 protected $logger;
45
46 /**
47 * @var WANObjectCache
48 */
49 protected $wanCache;
50
51 /**
52 * @param ResourceLoader $rl
53 * @param LoggerInterface $logger
54 */
55 public function __construct( ResourceLoader $rl = null, LoggerInterface $logger = null ) {
56 $this->resourceloader = $rl;
57 $this->logger = $logger ?: new NullLogger();
58 $this->wanCache = ObjectCache::getMainWANInstance();
59 }
60
61 /**
62 * @since 1.27
63 * @param LoggerInterface $logger
64 */
65 public function setLogger( LoggerInterface $logger ) {
66 $this->logger = $logger;
67 }
68
69 /**
70 * Get the message blob for a module
71 *
72 * @since 1.27
73 * @param ResourceLoaderModule $module
74 * @param string $lang Language code
75 * @return string JSON
76 */
77 public function getBlob( ResourceLoaderModule $module, $lang ) {
78 $blobs = $this->getBlobs( [ $module->getName() => $module ], $lang );
79 return $blobs[$module->getName()];
80 }
81
82 /**
83 * Get the message blobs for a set of modules
84 *
85 * @since 1.27
86 * @param ResourceLoaderModule[] $modules Array of module objects keyed by name
87 * @param string $lang Language code
88 * @return array An array mapping module names to message blobs
89 */
90 public function getBlobs( array $modules, $lang ) {
91 // Each cache key for a message blob by module name and language code also has a generic
92 // check key without language code. This is used to invalidate any and all language subkeys
93 // that exist for a module from the updateMessage() method.
94 $cache = $this->wanCache;
95 $checkKeys = [
96 // Global check key, see clear()
97 $cache->makeKey( __CLASS__ )
98 ];
99 $cacheKeys = [];
100 foreach ( $modules as $name => $module ) {
101 $cacheKey = $this->makeCacheKey( $module, $lang );
102 $cacheKeys[$name] = $cacheKey;
103 // Per-module check key, see updateMessage()
104 $checkKeys[$cacheKey][] = $cache->makeKey( __CLASS__, $name );
105 }
106 $curTTLs = [];
107 $result = $cache->getMulti( array_values( $cacheKeys ), $curTTLs, $checkKeys );
108
109 $blobs = [];
110 foreach ( $modules as $name => $module ) {
111 $key = $cacheKeys[$name];
112 if ( !isset( $result[$key] ) || $curTTLs[$key] === null || $curTTLs[$key] < 0 ) {
113 $blobs[$name] = $this->recacheMessageBlob( $key, $module, $lang );
114 } else {
115 // Use unexpired cache
116 $blobs[$name] = $result[$key];
117 }
118 }
119 return $blobs;
120 }
121
122 /**
123 * @deprecated since 1.27 Use getBlobs() instead
124 * @return array
125 */
126 public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
127 return $this->getBlobs( $modules, $lang );
128 }
129
130 /**
131 * @deprecated since 1.27 Obsolete. Used to populate a cache table in the database.
132 * @return bool
133 */
134 public function insertMessageBlob( $name, ResourceLoaderModule $module, $lang ) {
135 return false;
136 }
137
138 /**
139 * @since 1.27
140 * @param ResourceLoaderModule $module
141 * @param string $lang
142 * @return string Cache key
143 */
144 private function makeCacheKey( ResourceLoaderModule $module, $lang ) {
145 $messages = array_values( array_unique( $module->getMessages() ) );
146 sort( $messages );
147 return $this->wanCache->makeKey( __CLASS__, $module->getName(), $lang,
148 md5( json_encode( $messages ) )
149 );
150 }
151
152 /**
153 * @since 1.27
154 * @param string $cacheKey
155 * @param ResourceLoaderModule $module
156 * @param string $lang
157 * @return string JSON blob
158 */
159 protected function recacheMessageBlob( $cacheKey, ResourceLoaderModule $module, $lang ) {
160 $blob = $this->generateMessageBlob( $module, $lang );
161 $cache = $this->wanCache;
162 $cache->set( $cacheKey, $blob,
163 // Add part of a day to TTL to avoid all modules expiring at once
164 $cache::TTL_WEEK + mt_rand( 0, $cache::TTL_DAY ),
165 Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) )
166 );
167 return $blob;
168 }
169
170 /**
171 * Invalidate cache keys for modules using this message key.
172 * Called by MessageCache when a message has changed.
173 *
174 * @param string $key Message key
175 */
176 public function updateMessage( $key ) {
177 $moduleNames = $this->getResourceLoader()->getModulesByMessage( $key );
178 foreach ( $moduleNames as $moduleName ) {
179 // Uses a holdoff to account for database replica DB lag (for MessageCache)
180 $this->wanCache->touchCheckKey( $this->wanCache->makeKey( __CLASS__, $moduleName ) );
181 }
182 }
183
184 /**
185 * Invalidate cache keys for all known modules.
186 * Called by LocalisationCache after cache is regenerated.
187 */
188 public function clear() {
189 $cache = $this->wanCache;
190 // Disable holdoff because this invalidates all modules and also not needed since
191 // LocalisationCache is stored outside the database and doesn't have lag.
192 $cache->touchCheckKey( $cache->makeKey( __CLASS__ ), $cache::HOLDOFF_NONE );
193 }
194
195 /**
196 * @since 1.27
197 * @return ResourceLoader
198 */
199 protected function getResourceLoader() {
200 // Back-compat: This class supports instantiation without a ResourceLoader object.
201 // Lazy-initialise this property because most callers don't need it.
202 if ( $this->resourceloader === null ) {
203 $this->logger->warning( __CLASS__ . ' created without a ResourceLoader instance' );
204 $this->resourceloader = new ResourceLoader();
205 }
206 return $this->resourceloader;
207 }
208
209 /**
210 * @since 1.27
211 * @param string $key Message key
212 * @param string $lang Language code
213 * @return string
214 */
215 protected function fetchMessage( $key, $lang ) {
216 $message = wfMessage( $key )->inLanguage( $lang );
217 $value = $message->plain();
218 if ( !$message->exists() ) {
219 $this->logger->warning( 'Failed to find {messageKey} ({lang})', [
220 'messageKey' => $key,
221 'lang' => $lang,
222 ] );
223 }
224 return $value;
225 }
226
227 /**
228 * Generate the message blob for a given module in a given language.
229 *
230 * @param ResourceLoaderModule $module
231 * @param string $lang Language code
232 * @return string JSON blob
233 */
234 private function generateMessageBlob( ResourceLoaderModule $module, $lang ) {
235 $messages = [];
236 foreach ( $module->getMessages() as $key ) {
237 $messages[$key] = $this->fetchMessage( $key, $lang );
238 }
239
240 $json = FormatJson::encode( (object)$messages );
241 if ( $json === false ) {
242 $this->logger->warning( 'Failed to encode message blob for {module} ({lang})', [
243 'module' => $module->getName(),
244 'lang' => $lang,
245 ] );
246 $json = '{}';
247 }
248 return $json;
249 }
250 }