Fixed mistake in r73686 where I wrapped CSS in a JavaScript conditional.
[mediawiki.git] / includes / BagOStuff.php
blob5482dcd809ee17df05d895c1dc7dee1daf05e28f
1 <?php
2 /**
3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Cache
27 /**
28 * @defgroup Cache Cache
31 /**
32 * interface is intended to be more or less compatible with
33 * the PHP memcached client.
35 * backends for local hash array and SQL table included:
36 * <code>
37 * $bag = new HashBagOStuff();
38 * $bag = new SqlBagOStuff(); # connect to db first
39 * </code>
41 * @ingroup Cache
43 abstract class BagOStuff {
44 var $debugMode = false;
46 public function set_debug( $bool ) {
47 $this->debugMode = $bool;
50 /* *** THE GUTS OF THE OPERATION *** */
51 /* Override these with functional things in subclasses */
53 /**
54 * Get an item with the given key. Returns false if it does not exist.
55 * @param $key string
57 abstract public function get( $key );
59 /**
60 * Set an item.
61 * @param $key string
62 * @param $value mixed
63 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
65 abstract public function set( $key, $value, $exptime = 0 );
68 * Delete an item.
69 * @param $key string
70 * @param $time int Amount of time to delay the operation (mostly memcached-specific)
72 abstract public function delete( $key, $time = 0 );
74 public function lock( $key, $timeout = 0 ) {
75 /* stub */
76 return true;
79 public function unlock( $key ) {
80 /* stub */
81 return true;
84 public function keys() {
85 /* stub */
86 return array();
89 /* *** Emulated functions *** */
90 /* Better performance can likely be got with custom written versions */
91 public function get_multi( $keys ) {
92 $out = array();
94 foreach ( $keys as $key ) {
95 $out[$key] = $this->get( $key );
98 return $out;
101 public function set_multi( $hash, $exptime = 0 ) {
102 foreach ( $hash as $key => $value ) {
103 $this->set( $key, $value, $exptime );
107 public function add( $key, $value, $exptime = 0 ) {
108 if ( !$this->get( $key ) ) {
109 $this->set( $key, $value, $exptime );
111 return true;
115 public function add_multi( $hash, $exptime = 0 ) {
116 foreach ( $hash as $key => $value ) {
117 $this->add( $key, $value, $exptime );
121 public function delete_multi( $keys, $time = 0 ) {
122 foreach ( $keys as $key ) {
123 $this->delete( $key, $time );
127 public function replace( $key, $value, $exptime = 0 ) {
128 if ( $this->get( $key ) !== false ) {
129 $this->set( $key, $value, $exptime );
133 public function incr( $key, $value = 1 ) {
134 if ( !$this->lock( $key ) ) {
135 return false;
138 $value = intval( $value );
140 $n = false;
141 if ( ( $n = $this->get( $key ) ) !== false ) {
142 $n += $value;
143 $this->set( $key, $n ); // exptime?
145 $this->unlock( $key );
147 return $n;
150 public function decr( $key, $value = 1 ) {
151 return $this->incr( $key, - $value );
154 public function debug( $text ) {
155 if ( $this->debugMode ) {
156 wfDebug( "BagOStuff debug: $text\n" );
161 * Convert an optionally relative time to an absolute time
163 protected function convertExpiry( $exptime ) {
164 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
165 return time() + $exptime;
166 } else {
167 return $exptime;
173 * Functional versions!
174 * This is a test of the interface, mainly. It stores things in an associative
175 * array, which is not going to persist between program runs.
177 * @ingroup Cache
179 class HashBagOStuff extends BagOStuff {
180 var $bag;
182 function __construct() {
183 $this->bag = array();
186 protected function expire( $key ) {
187 $et = $this->bag[$key][1];
189 if ( ( $et == 0 ) || ( $et > time() ) ) {
190 return false;
193 $this->delete( $key );
195 return true;
198 function get( $key ) {
199 if ( !isset( $this->bag[$key] ) ) {
200 return false;
203 if ( $this->expire( $key ) ) {
204 return false;
207 return $this->bag[$key][0];
210 function set( $key, $value, $exptime = 0 ) {
211 $this->bag[$key] = array( $value, $this->convertExpiry( $exptime ) );
214 function delete( $key, $time = 0 ) {
215 if ( !isset( $this->bag[$key] ) ) {
216 return false;
219 unset( $this->bag[$key] );
221 return true;
224 function keys() {
225 return array_keys( $this->bag );
230 * Class to store objects in the database
232 * @ingroup Cache
234 class SqlBagOStuff extends BagOStuff {
235 var $lb, $db;
236 var $lastExpireAll = 0;
238 protected function getDB() {
239 global $wgDBtype;
241 if ( !isset( $this->db ) ) {
242 /* We must keep a separate connection to MySQL in order to avoid deadlocks
243 * However, SQLite has an opposite behaviour.
244 * @todo Investigate behaviour for other databases
246 if ( $wgDBtype == 'sqlite' ) {
247 $this->db = wfGetDB( DB_MASTER );
248 } else {
249 $this->lb = wfGetLBFactory()->newMainLB();
250 $this->db = $this->lb->getConnection( DB_MASTER );
251 $this->db->clearFlag( DBO_TRX );
255 return $this->db;
258 public function get( $key ) {
259 # expire old entries if any
260 $this->garbageCollect();
261 $db = $this->getDB();
262 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
263 array( 'keyname' => $key ), __METHOD__ );
265 if ( !$row ) {
266 $this->debug( 'get: no matching rows' );
267 return false;
270 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
272 if ( $this->isExpired( $row->exptime ) ) {
273 $this->debug( "get: key has expired, deleting" );
274 try {
275 $db->begin();
276 # Put the expiry time in the WHERE condition to avoid deleting a
277 # newly-inserted value
278 $db->delete( 'objectcache',
279 array(
280 'keyname' => $key,
281 'exptime' => $row->exptime
282 ), __METHOD__ );
283 $db->commit();
284 } catch ( DBQueryError $e ) {
285 $this->handleWriteError( $e );
288 return false;
291 return $this->unserialize( $db->decodeBlob( $row->value ) );
294 public function set( $key, $value, $exptime = 0 ) {
295 $db = $this->getDB();
296 $exptime = intval( $exptime );
298 if ( $exptime < 0 ) {
299 $exptime = 0;
302 if ( $exptime == 0 ) {
303 $encExpiry = $this->getMaxDateTime();
304 } else {
305 if ( $exptime < 3.16e8 ) { # ~10 years
306 $exptime += time();
309 $encExpiry = $db->timestamp( $exptime );
311 try {
312 $db->begin();
313 // (bug 24425) use a replace if the db supports it instead of
314 // delete/insert to avoid clashes with conflicting keynames
315 $db->replace( 'objectcache', array( 'keyname' ),
316 array(
317 'keyname' => $key,
318 'value' => $db->encodeBlob( $this->serialize( $value ) ),
319 'exptime' => $encExpiry
320 ), __METHOD__ );
321 $db->commit();
322 } catch ( DBQueryError $e ) {
323 $this->handleWriteError( $e );
325 return false;
328 return true;
331 public function delete( $key, $time = 0 ) {
332 $db = $this->getDB();
334 try {
335 $db->begin();
336 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
337 $db->commit();
338 } catch ( DBQueryError $e ) {
339 $this->handleWriteError( $e );
341 return false;
344 return true;
347 public function incr( $key, $step = 1 ) {
348 $db = $this->getDB();
349 $step = intval( $step );
351 try {
352 $db->begin();
353 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
354 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
355 if ( $row === false ) {
356 // Missing
357 $db->commit();
359 return false;
361 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
362 if ( $this->isExpired( $row->exptime ) ) {
363 // Expired, do not reinsert
364 $db->commit();
366 return false;
369 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
370 $newValue = $oldValue + $step;
371 $db->insert( 'objectcache',
372 array(
373 'keyname' => $key,
374 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
375 'exptime' => $row->exptime
376 ), __METHOD__ );
377 $db->commit();
378 } catch ( DBQueryError $e ) {
379 $this->handleWriteError( $e );
381 return false;
384 return $newValue;
387 public function keys() {
388 $db = $this->getDB();
389 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
390 $result = array();
392 foreach ( $res as $row ) {
393 $result[] = $row->keyname;
396 return $result;
399 protected function isExpired( $exptime ) {
400 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
403 protected function getMaxDateTime() {
404 if ( time() > 0x7fffffff ) {
405 return $this->getDB()->timestamp( 1 << 62 );
406 } else {
407 return $this->getDB()->timestamp( 0x7fffffff );
411 protected function garbageCollect() {
412 /* Ignore 99% of requests */
413 if ( !mt_rand( 0, 100 ) ) {
414 $now = time();
415 /* Avoid repeating the delete within a few seconds */
416 if ( $now > ( $this->lastExpireAll + 1 ) ) {
417 $this->lastExpireAll = $now;
418 $this->expireAll();
423 public function expireAll() {
424 $db = $this->getDB();
425 $now = $db->timestamp();
427 try {
428 $db->begin();
429 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
430 $db->commit();
431 } catch ( DBQueryError $e ) {
432 $this->handleWriteError( $e );
436 public function deleteAll() {
437 $db = $this->getDB();
439 try {
440 $db->begin();
441 $db->delete( 'objectcache', '*', __METHOD__ );
442 $db->commit();
443 } catch ( DBQueryError $e ) {
444 $this->handleWriteError( $e );
449 * Serialize an object and, if possible, compress the representation.
450 * On typical message and page data, this can provide a 3X decrease
451 * in storage requirements.
453 * @param $data mixed
454 * @return string
456 protected function serialize( &$data ) {
457 $serial = serialize( $data );
459 if ( function_exists( 'gzdeflate' ) ) {
460 return gzdeflate( $serial );
461 } else {
462 return $serial;
467 * Unserialize and, if necessary, decompress an object.
468 * @param $serial string
469 * @return mixed
471 protected function unserialize( $serial ) {
472 if ( function_exists( 'gzinflate' ) ) {
473 $decomp = @gzinflate( $serial );
475 if ( false !== $decomp ) {
476 $serial = $decomp;
480 $ret = unserialize( $serial );
482 return $ret;
486 * Handle a DBQueryError which occurred during a write operation.
487 * Ignore errors which are due to a read-only database, rethrow others.
489 protected function handleWriteError( $exception ) {
490 $db = $this->getDB();
492 if ( !$db->wasReadOnlyError() ) {
493 throw $exception;
496 try {
497 $db->rollback();
498 } catch ( DBQueryError $e ) {
501 wfDebug( __METHOD__ . ": ignoring query error\n" );
502 $db->ignoreErrors( false );
507 * Backwards compatibility alias
509 class MediaWikiBagOStuff extends SqlBagOStuff { }
512 * This is a wrapper for APC's shared memory functions
514 * @ingroup Cache
516 class APCBagOStuff extends BagOStuff {
517 public function get( $key ) {
518 $val = apc_fetch( $key );
520 if ( is_string( $val ) ) {
521 $val = unserialize( $val );
524 return $val;
527 public function set( $key, $value, $exptime = 0 ) {
528 apc_store( $key, serialize( $value ), $exptime );
530 return true;
533 public function delete( $key, $time = 0 ) {
534 apc_delete( $key );
536 return true;
539 public function keys() {
540 $info = apc_cache_info( 'user' );
541 $list = $info['cache_list'];
542 $keys = array();
544 foreach ( $list as $entry ) {
545 $keys[] = $entry['info'];
548 return $keys;
553 * This is a wrapper for eAccelerator's shared memory functions.
555 * This is basically identical to the deceased Turck MMCache version,
556 * mostly because eAccelerator is based on Turck MMCache.
558 * @ingroup Cache
560 class eAccelBagOStuff extends BagOStuff {
561 public function get( $key ) {
562 $val = eaccelerator_get( $key );
564 if ( is_string( $val ) ) {
565 $val = unserialize( $val );
568 return $val;
571 public function set( $key, $value, $exptime = 0 ) {
572 eaccelerator_put( $key, serialize( $value ), $exptime );
574 return true;
577 public function delete( $key, $time = 0 ) {
578 eaccelerator_rm( $key );
580 return true;
583 public function lock( $key, $waitTimeout = 0 ) {
584 eaccelerator_lock( $key );
586 return true;
589 public function unlock( $key ) {
590 eaccelerator_unlock( $key );
592 return true;
597 * Wrapper for XCache object caching functions; identical interface
598 * to the APC wrapper
600 * @ingroup Cache
602 class XCacheBagOStuff extends BagOStuff {
604 * Get a value from the XCache object cache
606 * @param $key String: cache key
607 * @return mixed
609 public function get( $key ) {
610 $val = xcache_get( $key );
612 if ( is_string( $val ) ) {
613 $val = unserialize( $val );
616 return $val;
620 * Store a value in the XCache object cache
622 * @param $key String: cache key
623 * @param $value Mixed: object to store
624 * @param $expire Int: expiration time
625 * @return bool
627 public function set( $key, $value, $expire = 0 ) {
628 xcache_set( $key, serialize( $value ), $expire );
630 return true;
634 * Remove a value from the XCache object cache
636 * @param $key String: cache key
637 * @param $time Int: not used in this implementation
638 * @return bool
640 public function delete( $key, $time = 0 ) {
641 xcache_unset( $key );
643 return true;
648 * Cache that uses DBA as a backend.
649 * Slow due to the need to constantly open and close the file to avoid holding
650 * writer locks. Intended for development use only, as a memcached workalike
651 * for systems that don't have it.
653 * @ingroup Cache
655 class DBABagOStuff extends BagOStuff {
656 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
658 public function __construct( $dir = false ) {
659 global $wgDBAhandler;
661 if ( $dir === false ) {
662 global $wgTmpDirectory;
663 $dir = $wgTmpDirectory;
666 $this->mFile = "$dir/mw-cache-" . wfWikiID();
667 $this->mFile .= '.db';
668 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
669 $this->mHandler = $wgDBAhandler;
673 * Encode value and expiry for storage
675 function encode( $value, $expiry ) {
676 # Convert to absolute time
677 $expiry = $this->convertExpiry( $expiry );
679 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
683 * @return list containing value first and expiry second
685 function decode( $blob ) {
686 if ( !is_string( $blob ) ) {
687 return array( null, 0 );
688 } else {
689 return array(
690 unserialize( substr( $blob, 11 ) ),
691 intval( substr( $blob, 0, 10 ) )
696 function getReader() {
697 if ( file_exists( $this->mFile ) ) {
698 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
699 } else {
700 $handle = $this->getWriter();
703 if ( !$handle ) {
704 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
707 return $handle;
710 function getWriter() {
711 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
713 if ( !$handle ) {
714 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
717 return $handle;
720 function get( $key ) {
721 wfProfileIn( __METHOD__ );
722 wfDebug( __METHOD__ . "($key)\n" );
724 $handle = $this->getReader();
725 if ( !$handle ) {
726 return null;
729 $val = dba_fetch( $key, $handle );
730 list( $val, $expiry ) = $this->decode( $val );
732 # Must close ASAP because locks are held
733 dba_close( $handle );
735 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
736 # Key is expired, delete it
737 $handle = $this->getWriter();
738 dba_delete( $key, $handle );
739 dba_close( $handle );
740 wfDebug( __METHOD__ . ": $key expired\n" );
741 $val = null;
744 wfProfileOut( __METHOD__ );
745 return $val;
748 function set( $key, $value, $exptime = 0 ) {
749 wfProfileIn( __METHOD__ );
750 wfDebug( __METHOD__ . "($key)\n" );
752 $blob = $this->encode( $value, $exptime );
754 $handle = $this->getWriter();
755 if ( !$handle ) {
756 return false;
759 $ret = dba_replace( $key, $blob, $handle );
760 dba_close( $handle );
762 wfProfileOut( __METHOD__ );
763 return $ret;
766 function delete( $key, $time = 0 ) {
767 wfProfileIn( __METHOD__ );
768 wfDebug( __METHOD__ . "($key)\n" );
770 $handle = $this->getWriter();
771 if ( !$handle ) {
772 return false;
775 $ret = dba_delete( $key, $handle );
776 dba_close( $handle );
778 wfProfileOut( __METHOD__ );
779 return $ret;
782 function add( $key, $value, $exptime = 0 ) {
783 wfProfileIn( __METHOD__ );
785 $blob = $this->encode( $value, $exptime );
787 $handle = $this->getWriter();
789 if ( !$handle ) {
790 return false;
793 $ret = dba_insert( $key, $blob, $handle );
795 # Insert failed, check to see if it failed due to an expired key
796 if ( !$ret ) {
797 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
799 if ( $expiry < time() ) {
800 # Yes expired, delete and try again
801 dba_delete( $key, $handle );
802 $ret = dba_insert( $key, $blob, $handle );
803 # This time if it failed then it will be handled by the caller like any other race
807 dba_close( $handle );
809 wfProfileOut( __METHOD__ );
810 return $ret;
813 function keys() {
814 $reader = $this->getReader();
815 $k1 = dba_firstkey( $reader );
817 if ( !$k1 ) {
818 return array();
821 $result[] = $k1;
823 while ( $key = dba_nextkey( $reader ) ) {
824 $result[] = $key;
827 return $result;
832 * Wrapper for WinCache object caching functions; identical interface
833 * to the APC wrapper
835 * @ingroup Cache
837 class WinCacheBagOStuff extends BagOStuff {
840 * Get a value from the WinCache object cache
842 * @param $key String: cache key
843 * @return mixed
845 public function get( $key ) {
846 $val = wincache_ucache_get( $key );
848 if ( is_string( $val ) ) {
849 $val = unserialize( $val );
852 return $val;
856 * Store a value in the WinCache object cache
858 * @param $key String: cache key
859 * @param $value Mixed: object to store
860 * @param $expire Int: expiration time
861 * @return bool
863 public function set( $key, $value, $expire = 0 ) {
864 wincache_ucache_set( $key, serialize( $value ), $expire );
866 return true;
870 * Remove a value from the WinCache object cache
872 * @param $key String: cache key
873 * @param $time Int: not used in this implementation
874 * @return bool
876 public function delete( $key, $time = 0 ) {
877 wincache_ucache_delete( $key );
879 return true;
882 public function keys() {
883 $info = wincache_ucache_info();
884 $list = $info['ucache_entries'];
885 $keys = array();
887 foreach ( $list as $entry ) {
888 $keys[] = $entry['key_name'];
891 return $keys;