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