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