Allow storing local message cache as PHP source instead of serialized array, this...
[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 function loadFromScript( $hash ) {
117 global $wgLocalMessageCache, $wgDBname;
118 if ( $wgLocalMessageCache === false ) {
119 return;
120 }
121
122 $filename = "$wgLocalMessageCache/messages-$wgDBname";
123
124 wfSuppressWarnings();
125 $file = fopen( $filename, 'r' );
126 wfRestoreWarnings();
127 if ( !$file ) {
128 return;
129 }
130 $localHash=substr(fread($file,40),8);
131 fclose($file);
132 if ($hash!=$localHash) {
133 return;
134 }
135 require("$wgLocalMessageCache/messages-$wgDBname");
136 }
137
138 function saveToScript($array, $hash) {
139 global $wgLocalMessageCache, $wgDBname;
140 if ( $wgLocalMessageCache === false ) {
141 return;
142 }
143
144 $filename = "$wgLocalMessageCache/messages-$wgDBname";
145 $oldUmask = umask( 0 );
146 wfMkdirParents( $wgLocalMessageCache, 0777 );
147 umask( $oldUmask );
148 $file = fopen( $filename.'.tmp', 'w');
149 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
150
151 $re="/(?<!\\\\)'/";
152 foreach ($array as $key => $message) {
153 fwrite($file, "'". preg_replace($re, "\'", $key).
154 "' => '" . preg_replace( $re, "\'", $message) . "',\n");
155 }
156 fwrite($file,");\n?>");
157 fclose($file);
158 rename($filename.'.tmp',$filename);
159 }
160
161 /**
162 * Loads messages either from memcached or the database, if not disabled
163 * On error, quietly switches to a fallback mode
164 * Returns false for a reportable error, true otherwise
165 */
166 function load() {
167 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
168
169 if ( $this->mDisable ) {
170 static $shownDisabled = false;
171 if ( !$shownDisabled ) {
172 wfDebug( "MessageCache::load(): disabled\n" );
173 $shownDisabled = true;
174 }
175 return true;
176 }
177 $fname = 'MessageCache::load';
178 wfProfileIn( $fname );
179 $success = true;
180
181 if ( $this->mUseCache ) {
182 $this->mCache = false;
183
184 # Try local cache
185 wfProfileIn( $fname.'-fromlocal' );
186 $hash = $this->mMemc->get( "{$this->mMemcKey}-hash" );
187 if ( $hash ) {
188 if ($wgLocalMessageCacheSerialized) {
189 $this->loadFromLocal( $hash );
190 } else {
191 $this->loadFromScript( $hash );
192 }
193 }
194 wfProfileOut( $fname.'-fromlocal' );
195
196 # Try memcached
197 if ( !$this->mCache ) {
198 wfProfileIn( $fname.'-fromcache' );
199 $this->mCache = $this->mMemc->get( $this->mMemcKey );
200
201 # Save to local cache
202 if ( $wgLocalMessageCache !== false ) {
203 $serialized = serialize( $this->mCache );
204 if ( !$hash ) {
205 $hash = md5( $serialized );
206 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
207 }
208 if ($wgLocalMessageCacheSerialized) {
209 $this->saveToLocal( $serialized,$hash );
210 } else {
211 $this->saveToScript( $this->mCache, $hash );
212 }
213 }
214 wfProfileOut( $fname.'-fromcache' );
215 }
216
217
218 # If there's nothing in memcached, load all the messages from the database
219 if ( !$this->mCache ) {
220 wfDebug( "MessageCache::load(): loading all messages\n" );
221 $this->lock();
222 # Other threads don't need to load the messages if another thread is doing it.
223 $success = $this->mMemc->add( $this->mMemcKey.'-status', "loading", MSG_LOAD_TIMEOUT );
224 if ( $success ) {
225 wfProfileIn( $fname.'-load' );
226 $this->loadFromDB();
227 wfProfileOut( $fname.'-load' );
228
229 # Save in memcached
230 # Keep trying if it fails, this is kind of important
231 wfProfileIn( $fname.'-save' );
232 for ($i=0; $i<20 &&
233 !$this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
234 $i++ ) {
235 usleep(mt_rand(500000,1500000));
236 }
237
238 # Save to local cache
239 if ( $wgLocalMessageCache !== false ) {
240 $serialized = serialize( $this->mCache );
241 $hash = md5( $serialized );
242 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
243 if ($wgLocalMessageCacheSerialized) {
244 $this->saveToLocal( $serialized,$hash );
245 } else {
246 $this->saveToScript( $this->mCache, $hash );
247 }
248 }
249
250 wfProfileOut( $fname.'-save' );
251 if ( $i == 20 ) {
252 $this->mMemc->set( $this->mMemcKey.'-status', 'error', 60*5 );
253 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
254 }
255 }
256 $this->unlock();
257 }
258
259 if ( !is_array( $this->mCache ) ) {
260 wfDebug( "MessageCache::load(): individual message mode\n" );
261 # If it is 'loading' or 'error', switch to individual message mode, otherwise disable
262 # Causing too much DB load, disabling -- TS
263 $this->mDisable = true;
264 /*
265 if ( $this->mCache == "loading" ) {
266 $this->mUseCache = false;
267 } elseif ( $this->mCache == "error" ) {
268 $this->mUseCache = false;
269 $success = false;
270 } else {
271 $this->mDisable = true;
272 $success = false;
273 }*/
274 $this->mCache = false;
275 }
276 }
277 wfProfileOut( $fname );
278 $this->mDeferred = false;
279 return $success;
280 }
281
282 /**
283 * Loads all or main part of cacheable messages from the database
284 */
285 function loadFromDB() {
286 global $wgAllMessagesEn, $wgLang;
287
288 $fname = 'MessageCache::loadFromDB';
289 $dbr =& wfGetDB( DB_SLAVE );
290 if ( !$dbr ) {
291 wfDebugDieBacktrace( 'Invalid database object' );
292 }
293 $conditions = array( 'page_is_redirect' => 0,
294 'page_namespace' => NS_MEDIAWIKI);
295 $res = $dbr->select( array( 'page', 'revision', 'text' ),
296 array( 'page_title', 'old_text', 'old_flags' ),
297 'page_is_redirect=0 AND page_namespace='.NS_MEDIAWIKI.' AND page_latest=rev_id AND rev_text_id=old_id',
298 $fname
299 );
300
301 $this->mCache = array();
302 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
303 $this->mCache[$row->page_title] = Revision::getRevisionText( $row );
304 }
305
306 # Negative caching
307 # Go through the language array and the extension array and make a note of
308 # any keys missing from the cache
309 foreach ( $wgAllMessagesEn as $key => $value ) {
310 $uckey = $wgLang->ucfirst( $key );
311 if ( !array_key_exists( $uckey, $this->mCache ) ) {
312 $this->mCache[$uckey] = false;
313 }
314 }
315 foreach ( $this->mExtensionMessages as $key => $value ) {
316 $uckey = $wgLang->ucfirst( $key );
317 if ( !array_key_exists( $uckey, $this->mCache ) ) {
318 $this->mCache[$uckey] = false;
319 }
320 }
321
322 $dbr->freeResult( $res );
323 }
324
325 /**
326 * Not really needed anymore
327 */
328 function getKeys() {
329 global $wgAllMessagesEn, $wgContLang;
330 if ( !$this->mKeys ) {
331 $this->mKeys = array();
332 foreach ( $wgAllMessagesEn as $key => $value ) {
333 $title = $wgContLang->ucfirst( $key );
334 array_push( $this->mKeys, $title );
335 }
336 }
337 return $this->mKeys;
338 }
339
340 /**
341 * @deprecated
342 */
343 function isCacheable( $key ) {
344 return true;
345 }
346
347 function replace( $title, $text ) {
348 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc, $wgDBname;
349
350 $this->lock();
351 $this->load();
352 $parserMemc->delete("$wgDBname:sidebar");
353 if ( is_array( $this->mCache ) ) {
354 $this->mCache[$title] = $text;
355 $this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
356
357 # Save to local cache
358 if ( $wgLocalMessageCache !== false ) {
359 $serialized = serialize( $this->mCache );
360 $hash = md5( $serialized );
361 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
362 if ($wgLocalMessageCacheSerialized) {
363 $this->saveToLocal( $serialized,$hash );
364 } else {
365 $this->saveToScript( $this->mCache, $hash );
366 }
367 }
368
369
370 }
371 $this->unlock();
372 }
373
374 /**
375 * Returns success
376 * Represents a write lock on the messages key
377 */
378 function lock() {
379 if ( !$this->mUseCache ) {
380 return true;
381 }
382
383 $lockKey = $this->mMemcKey . 'lock';
384 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
385 sleep(1);
386 }
387
388 return $i >= MSG_WAIT_TIMEOUT;
389 }
390
391 function unlock() {
392 if ( !$this->mUseCache ) {
393 return;
394 }
395
396 $lockKey = $this->mMemcKey . 'lock';
397 $this->mMemc->delete( $lockKey );
398 }
399
400 function get( $key, $useDB, $forcontent=true, $isfullkey = false ) {
401 global $wgContLanguageCode;
402 if( $forcontent ) {
403 global $wgContLang;
404 $lang =& $wgContLang;
405 $langcode = $wgContLanguageCode;
406 } else {
407 global $wgLang, $wgLanguageCode;
408 $lang =& $wgLang;
409 $langcode = $wgLanguageCode;
410 }
411 # If uninitialised, someone is trying to call this halfway through Setup.php
412 if( !$this->mInitialised ) {
413 return '&lt;' . htmlspecialchars($key) . '&gt;';
414 }
415 # If cache initialization was deferred, start it now.
416 if( $this->mDeferred && !$this->mDisable && $useDB ) {
417 $this->load();
418 }
419
420 $message = false;
421 if( !$this->mDisable && $useDB ) {
422 $title = $lang->ucfirst( $key );
423 if(!$isfullkey && ($langcode != $wgContLanguageCode) ) {
424 $title .= '/' . $langcode;
425 }
426 $message = $this->getFromCache( $title );
427 }
428 # Try the extension array
429 if( $message === false && array_key_exists( $key, $this->mExtensionMessages ) ) {
430 $message = $this->mExtensionMessages[$key];
431 }
432
433 # Try the array in the language object
434 if( $message === false ) {
435 wfSuppressWarnings();
436 $message = $lang->getMessage( $key );
437 wfRestoreWarnings();
438 if ( is_null( $message ) ) {
439 $message = false;
440 }
441 }
442
443 # Try the English array
444 if( $message === false && $langcode != 'en' ) {
445 wfSuppressWarnings();
446 $message = Language::getMessage( $key );
447 wfRestoreWarnings();
448 if ( is_null( $message ) ) {
449 $message = false;
450 }
451 }
452
453 # Is this a custom message? Try the default language in the db...
454 if( $message === false &&
455 !$this->mDisable && $useDB &&
456 !$isfullkey && ($langcode != $wgContLanguageCode) ) {
457 $message = $this->getFromCache( $lang->ucfirst( $key ) );
458 }
459
460 # Final fallback
461 if( $message === false ) {
462 return '&lt;' . htmlspecialchars($key) . '&gt;';
463 }
464
465 # Replace brace tags
466 $message = $this->transform( $message );
467 return $message;
468 }
469
470 function getFromCache( $title ) {
471 $message = false;
472
473 # Try the cache
474 if( $this->mUseCache && is_array( $this->mCache ) && array_key_exists( $title, $this->mCache ) ) {
475 return $this->mCache[$title];
476 }
477
478 # Try individual message cache
479 if ( $this->mUseCache ) {
480 $message = $this->mMemc->get( $this->mMemcKey . ':' . $title );
481 if ( $message == '###NONEXISTENT###' ) {
482 return false;
483 } elseif( !is_null( $message ) ) {
484 $this->mCache[$title] = $message;
485 return $message;
486 } else {
487 $message = false;
488 }
489 }
490
491 # Call message Hooks, in case they are defined
492 wfRunHooks('MessagesPreLoad',array($title,&$message));
493
494 # If it wasn't in the cache, load each message from the DB individually
495 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
496 if( $revision ) {
497 $message = $revision->getText();
498 if ($this->mUseCache) {
499 $this->mCache[$title]=$message;
500 /* individual messages may be often
501 recached until proper purge code exists
502 */
503 $this->mMemc->set( $this->mMemcKey . ':' . $title, $message, 300 );
504 }
505 } else {
506 # Negative caching
507 # Use some special text instead of false, because false gets converted to '' somewhere
508 $this->mMemc->set( $this->mMemcKey . ':' . $title, '###NONEXISTENT###', $this->mExpiry );
509 }
510
511 return $message;
512 }
513
514 function transform( $message ) {
515 if( !$this->mDisableTransform ) {
516 if( strpos( $message, '{{' ) !== false ) {
517 $message = $this->mParser->transformMsg( $message, $this->mParserOptions );
518 }
519 }
520 return $message;
521 }
522
523 function disable() { $this->mDisable = true; }
524 function enable() { $this->mDisable = false; }
525 function disableTransform() { $this->mDisableTransform = true; }
526 function enableTransform() { $this->mDisableTransform = false; }
527 function setTransform( $x ) { $this->mDisableTransform = $x; }
528 function getTransform() { return $this->mDisableTransform; }
529
530 /**
531 * Add a message to the cache
532 *
533 * @param mixed $key
534 * @param mixed $value
535 */
536 function addMessage( $key, $value ) {
537 $this->mExtensionMessages[$key] = $value;
538 }
539
540 /**
541 * Add an associative array of message to the cache
542 *
543 * @param array $messages An associative array of key => values to be added
544 */
545 function addMessages( $messages ) {
546 foreach ( $messages as $key => $value ) {
547 $this->addMessage( $key, $value );
548 }
549 }
550
551 /**
552 * Clear all stored messages. Mainly used after a mass rebuild.
553 */
554 function clear() {
555 if( $this->mUseCache ) {
556 $this->mMemc->delete( $this->mMemcKey );
557 }
558 }
559 }
560 ?>