ea7ae52e09a0b5292df7d3005db2a942a625e534
[lhc/web/wiklou.git] / includes / MessageCache.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage Cache
6 */
7
8 /** */
9 require_once( 'Revision.php' );
10
11 /**
12 *
13 */
14 define( 'MSG_LOAD_TIMEOUT', 60);
15 define( 'MSG_LOCK_TIMEOUT', 10);
16 define( 'MSG_WAIT_TIMEOUT', 10);
17
18 /**
19 * Message cache
20 * Performs various useful MediaWiki namespace-related functions
21 *
22 * @package MediaWiki
23 */
24 class MessageCache {
25 var $mCache, $mUseCache, $mDisable, $mExpiry;
26 var $mMemcKey, $mKeys, $mParserOptions, $mParser;
27 var $mExtensionMessages = array();
28 var $mInitialised = false;
29 var $mDeferred = true;
30
31 function initialise( &$memCached, $useDB, $expiry, $memcPrefix) {
32 $fname = 'MessageCache::initialise';
33 wfProfileIn( $fname );
34
35 $this->mUseCache = !is_null( $memCached );
36 $this->mMemc = &$memCached;
37 $this->mDisable = !$useDB;
38 $this->mExpiry = $expiry;
39 $this->mDisableTransform = false;
40 $this->mMemcKey = $memcPrefix.':messages';
41 $this->mKeys = false; # initialised on demand
42 $this->mInitialised = true;
43
44 wfProfileIn( $fname.'-parseropt' );
45 $this->mParserOptions = ParserOptions::newFromUser( $u=NULL );
46 wfProfileOut( $fname.'-parseropt' );
47 wfProfileIn( $fname.'-parser' );
48 $this->mParser = new Parser;
49 wfProfileOut( $fname.'-parser' );
50
51 # When we first get asked for a message,
52 # then we'll fill up the cache. If we
53 # can return a cache hit, this saves
54 # some extra milliseconds
55 $this->mDeferred = true;
56
57 wfProfileOut( $fname );
58 }
59
60 /**
61 * Try to load the cache from a local file
62 */
63 function loadFromLocal( $hash ) {
64 global $wgLocalMessageCache, $wgDBname;
65
66 $this->mCache = false;
67 if ( $wgLocalMessageCache === false ) {
68 return;
69 }
70
71 $filename = "$wgLocalMessageCache/messages-$wgDBname";
72
73 wfSuppressWarnings();
74 $file = fopen( $filename, 'r' );
75 wfRestoreWarnings();
76 if ( !$file ) {
77 return;
78 }
79
80 // Check to see if the file has the hash specified
81 $localHash = fread( $file, 32 );
82 if ( $hash == $localHash ) {
83 // All good, get the rest of it
84 $serialized = fread( $file, 1000000 );
85 $this->mCache = unserialize( $serialized );
86 }
87 fclose( $file );
88 }
89
90 /**
91 * Save the cache to a local file
92 */
93 function saveToLocal( $serialized, $hash ) {
94 global $wgLocalMessageCache, $wgDBname;
95
96 if ( $wgLocalMessageCache === false ) {
97 return;
98 }
99
100 $filename = "$wgLocalMessageCache/messages-$wgDBname";
101 $oldUmask = umask( 0 );
102 wfMkdirParents( $wgLocalMessageCache, 0777 );
103 umask( $oldUmask );
104
105 $file = fopen( $filename, 'w' );
106 if ( !$file ) {
107 wfDebug( "Unable to open local cache file for writing\n" );
108 return;
109 }
110
111 fwrite( $file, $hash . $serialized );
112 fclose( $file );
113 @chmod( $filename, 0666 );
114 }
115
116
117 /**
118 * Loads messages either from memcached or the database, if not disabled
119 * On error, quietly switches to a fallback mode
120 * Returns false for a reportable error, true otherwise
121 */
122 function load() {
123 global $wgLocalMessageCache;
124
125 if ( $this->mDisable ) {
126 static $shownDisabled = false;
127 if ( !$shownDisabled ) {
128 wfDebug( "MessageCache::load(): disabled\n" );
129 $shownDisabled = true;
130 }
131 return true;
132 }
133 $fname = 'MessageCache::load';
134 wfProfileIn( $fname );
135 $success = true;
136
137 if ( $this->mUseCache ) {
138 $this->mCache = false;
139
140 # Try local cache
141 wfProfileIn( $fname.'-fromlocal' );
142 $hash = $this->mMemc->get( "{$this->mMemcKey}-hash" );
143 if ( $hash ) {
144 $this->loadFromLocal( $hash );
145 }
146 wfProfileOut( $fname.'-fromlocal' );
147
148 # Try memcached
149 if ( !$this->mCache ) {
150 wfProfileIn( $fname.'-fromcache' );
151 $this->mCache = $this->mMemc->get( $this->mMemcKey );
152
153 # Save to local cache
154 if ( $wgLocalMessageCache !== false ) {
155 $serialized = serialize( $this->mCache );
156 if ( !$hash ) {
157 $hash = md5( $serialized );
158 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
159 }
160 $this->saveToLocal( $serialized, $hash );
161 }
162 wfProfileOut( $fname.'-fromcache' );
163 }
164
165
166 # If there's nothing in memcached, load all the messages from the database
167 if ( !$this->mCache ) {
168 wfDebug( "MessageCache::load(): loading all messages\n" );
169 $this->lock();
170 # Other threads don't need to load the messages if another thread is doing it.
171 $success = $this->mMemc->add( $this->mMemcKey.'-status', "loading", MSG_LOAD_TIMEOUT );
172 if ( $success ) {
173 wfProfileIn( $fname.'-load' );
174 $this->loadFromDB();
175 wfProfileOut( $fname.'-load' );
176
177 # Save in memcached
178 # Keep trying if it fails, this is kind of important
179 wfProfileIn( $fname.'-save' );
180 for ($i=0; $i<20 &&
181 !$this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
182 $i++ ) {
183 usleep(mt_rand(500000,1500000));
184 }
185
186 # Save to local cache
187 if ( $wgLocalMessageCache !== false ) {
188 $serialized = serialize( $this->mCache );
189 $hash = md5( $serialized );
190 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
191 $this->saveToLocal( $serialized, $hash );
192 }
193
194 wfProfileOut( $fname.'-save' );
195 if ( $i == 20 ) {
196 $this->mMemc->set( $this->mMemcKey.'-status', 'error', 60*5 );
197 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
198 }
199 }
200 $this->unlock();
201 }
202
203 if ( !is_array( $this->mCache ) ) {
204 wfDebug( "MessageCache::load(): individual message mode\n" );
205 # If it is 'loading' or 'error', switch to individual message mode, otherwise disable
206 # Causing too much DB load, disabling -- TS
207 $this->mDisable = true;
208 /*
209 if ( $this->mCache == "loading" ) {
210 $this->mUseCache = false;
211 } elseif ( $this->mCache == "error" ) {
212 $this->mUseCache = false;
213 $success = false;
214 } else {
215 $this->mDisable = true;
216 $success = false;
217 }*/
218 $this->mCache = false;
219 }
220 }
221 wfProfileOut( $fname );
222 $this->mDeferred = false;
223 return $success;
224 }
225
226 /**
227 * Loads all or main part of cacheable messages from the database
228 */
229 function loadFromDB() {
230 global $wgAllMessagesEn, $wgLang;
231
232 $fname = 'MessageCache::loadFromDB';
233 $dbr =& wfGetDB( DB_SLAVE );
234 if ( !$dbr ) {
235 wfDebugDieBacktrace( 'Invalid database object' );
236 }
237 $conditions = array( 'page_is_redirect' => 0,
238 'page_namespace' => NS_MEDIAWIKI);
239 $res = $dbr->select( array( 'page', 'revision', 'text' ),
240 array( 'page_title', 'old_text', 'old_flags' ),
241 'page_is_redirect=0 AND page_namespace='.NS_MEDIAWIKI.' AND page_latest=rev_id AND rev_text_id=old_id',
242 $fname
243 );
244
245 $this->mCache = array();
246 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
247 $this->mCache[$row->page_title] = Revision::getRevisionText( $row );
248 }
249
250 # Negative caching
251 # Go through the language array and the extension array and make a note of
252 # any keys missing from the cache
253 foreach ( $wgAllMessagesEn as $key => $value ) {
254 $uckey = $wgLang->ucfirst( $key );
255 if ( !array_key_exists( $uckey, $this->mCache ) ) {
256 $this->mCache[$uckey] = false;
257 }
258 }
259 foreach ( $this->mExtensionMessages as $key => $value ) {
260 $uckey = $wgLang->ucfirst( $key );
261 if ( !array_key_exists( $uckey, $this->mCache ) ) {
262 $this->mCache[$uckey] = false;
263 }
264 }
265
266 $dbr->freeResult( $res );
267 }
268
269 /**
270 * Not really needed anymore
271 */
272 function getKeys() {
273 global $wgAllMessagesEn, $wgContLang;
274 if ( !$this->mKeys ) {
275 $this->mKeys = array();
276 foreach ( $wgAllMessagesEn as $key => $value ) {
277 $title = $wgContLang->ucfirst( $key );
278 array_push( $this->mKeys, $title );
279 }
280 }
281 return $this->mKeys;
282 }
283
284 /**
285 * @deprecated
286 */
287 function isCacheable( $key ) {
288 return true;
289 }
290
291 function replace( $title, $text ) {
292 global $wgLocalMessageCache, $parserMemc, $wgDBname;
293
294 $this->lock();
295 $this->load();
296 $parserMemc->delete("$wgDBname:sidebar");
297 if ( is_array( $this->mCache ) ) {
298 $this->mCache[$title] = $text;
299 $this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
300
301 # Save to local cache
302 if ( $wgLocalMessageCache !== false ) {
303 $serialized = serialize( $this->mCache );
304 $hash = md5( $serialized );
305 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
306 $this->saveToLocal( $serialized, $hash );
307 }
308
309
310 }
311 $this->unlock();
312 }
313
314 /**
315 * Returns success
316 * Represents a write lock on the messages key
317 */
318 function lock() {
319 if ( !$this->mUseCache ) {
320 return true;
321 }
322
323 $lockKey = $this->mMemcKey . 'lock';
324 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
325 sleep(1);
326 }
327
328 return $i >= MSG_WAIT_TIMEOUT;
329 }
330
331 function unlock() {
332 if ( !$this->mUseCache ) {
333 return;
334 }
335
336 $lockKey = $this->mMemcKey . 'lock';
337 $this->mMemc->delete( $lockKey );
338 }
339
340 function get( $key, $useDB, $forcontent=true, $isfullkey = false ) {
341 global $wgContLanguageCode;
342 if( $forcontent ) {
343 global $wgContLang;
344 $lang =& $wgContLang;
345 $langcode = $wgContLanguageCode;
346 } else {
347 global $wgLang, $wgLanguageCode;
348 $lang =& $wgLang;
349 $langcode = $wgLanguageCode;
350 }
351 # If uninitialised, someone is trying to call this halfway through Setup.php
352 if( !$this->mInitialised ) {
353 return '&lt;' . htmlspecialchars($key) . '&gt;';
354 }
355 # If cache initialization was deferred, start it now.
356 if( $this->mDeferred && !$this->mDisable && $useDB ) {
357 $this->load();
358 }
359
360 $message = false;
361 if( !$this->mDisable && $useDB ) {
362 $title = $lang->ucfirst( $key );
363 if(!$isfullkey && ($langcode != $wgContLanguageCode) ) {
364 $title .= '/' . $langcode;
365 }
366 $message = $this->getFromCache( $title );
367 }
368 # Try the extension array
369 if( $message === false && array_key_exists( $key, $this->mExtensionMessages ) ) {
370 $message = $this->mExtensionMessages[$key];
371 }
372
373 # Try the array in the language object
374 if( $message === false ) {
375 wfSuppressWarnings();
376 $message = $lang->getMessage( $key );
377 wfRestoreWarnings();
378 if ( is_null( $message ) ) {
379 $message = false;
380 }
381 }
382
383 # Try the English array
384 if( $message === false && $langcode != 'en' ) {
385 wfSuppressWarnings();
386 $message = Language::getMessage( $key );
387 wfRestoreWarnings();
388 if ( is_null( $message ) ) {
389 $message = false;
390 }
391 }
392
393 # Is this a custom message? Try the default language in the db...
394 if( $message === false &&
395 !$this->mDisable && $useDB &&
396 !$isfullkey && ($langcode != $wgContLanguageCode) ) {
397 $message = $this->getFromCache( $lang->ucfirst( $key ) );
398 }
399
400 # Final fallback
401 if( $message === false ) {
402 return '&lt;' . htmlspecialchars($key) . '&gt;';
403 }
404
405 # Replace brace tags
406 $message = $this->transform( $message );
407 return $message;
408 }
409
410 function getFromCache( $title ) {
411 $message = false;
412
413 # Try the cache
414 if( $this->mUseCache && is_array( $this->mCache ) && array_key_exists( $title, $this->mCache ) ) {
415 return $this->mCache[$title];
416 }
417
418 # Try individual message cache
419 if ( $this->mUseCache ) {
420 $message = $this->mMemc->get( $this->mMemcKey . ':' . $title );
421 if ( $message == '###NONEXISTENT###' ) {
422 return false;
423 } elseif( !is_null( $message ) ) {
424 $this->mCache[$title] = $message;
425 return $message;
426 } else {
427 $message = false;
428 }
429 }
430
431 # Call message Hooks, in case they are defined
432 wfRunHooks('MessagesPreLoad',array($title,&$message));
433
434 # If it wasn't in the cache, load each message from the DB individually
435 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
436 if( $revision ) {
437 $message = $revision->getText();
438 if ($this->mUseCache) {
439 $this->mCache[$title]=$message;
440 /* individual messages may be often
441 recached until proper purge code exists
442 */
443 $this->mMemc->set( $this->mMemcKey . ':' . $title, $message, 300 );
444 }
445 } else {
446 # Negative caching
447 # Use some special text instead of false, because false gets converted to '' somewhere
448 $this->mMemc->set( $this->mMemcKey . ':' . $title, '###NONEXISTENT###', $this->mExpiry );
449 }
450
451 return $message;
452 }
453
454 function transform( $message ) {
455 if( !$this->mDisableTransform ) {
456 if( strpos( $message, '{{' ) !== false ) {
457 $message = $this->mParser->transformMsg( $message, $this->mParserOptions );
458 }
459 }
460 return $message;
461 }
462
463 function disable() { $this->mDisable = true; }
464 function enable() { $this->mDisable = false; }
465 function disableTransform() { $this->mDisableTransform = true; }
466 function enableTransform() { $this->mDisableTransform = false; }
467 function setTransform( $x ) { $this->mDisableTransform = $x; }
468 function getTransform() { return $this->mDisableTransform; }
469
470 /**
471 * Add a message to the cache
472 *
473 * @param mixed $key
474 * @param mixed $value
475 */
476 function addMessage( $key, $value ) {
477 $this->mExtensionMessages[$key] = $value;
478 }
479
480 /**
481 * Add an associative array of message to the cache
482 *
483 * @param array $messages An associative array of key => values to be added
484 */
485 function addMessages( $messages ) {
486 foreach ( $messages as $key => $value ) {
487 $this->addMessage( $key, $value );
488 }
489 }
490
491 /**
492 * Clear all stored messages. Mainly used after a mass rebuild.
493 */
494 function clear() {
495 if( $this->mUseCache ) {
496 $this->mMemc->delete( $this->mMemcKey );
497 }
498 }
499 }
500 ?>