Update and fixes.
[mediawiki.git] / includes / BagOStuff.php
blobb4fefc97aad02956172292a1765e495e8d59de58
1 <?php
3 # Copyright (C) 2003-2004 Brion Vibber <brion@pobox.com>
4 # http://www.mediawiki.org/
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 # http://www.gnu.org/copyleft/gpl.html
21 /**
22 * @defgroup Cache Cache
24 * @file
25 * @ingroup Cache
28 /**
29 * interface is intended to be more or less compatible with
30 * the PHP memcached client.
32 * backends for local hash array and SQL table included:
33 * <code>
34 * $bag = new HashBagOStuff();
35 * $bag = new MediaWikiBagOStuff($tablename); # connect to db first
36 * </code>
38 * @ingroup Cache
40 class BagOStuff {
41 var $debugmode;
43 function __construct() {
44 $this->set_debug( false );
47 function set_debug($bool) {
48 $this->debugmode = $bool;
51 /* *** THE GUTS OF THE OPERATION *** */
52 /* Override these with functional things in subclasses */
54 function get($key) {
55 /* stub */
56 return false;
59 function set($key, $value, $exptime=0) {
60 /* stub */
61 return false;
64 function delete($key, $time=0) {
65 /* stub */
66 return false;
69 function lock($key, $timeout = 0) {
70 /* stub */
71 return true;
74 function unlock($key) {
75 /* stub */
76 return true;
79 function keys() {
80 /* stub */
81 return array();
84 /* *** Emulated functions *** */
85 /* Better performance can likely be got with custom written versions */
86 function get_multi($keys) {
87 $out = array();
88 foreach($keys as $key)
89 $out[$key] = $this->get($key);
90 return $out;
93 function set_multi($hash, $exptime=0) {
94 foreach($hash as $key => $value)
95 $this->set($key, $value, $exptime);
98 function add($key, $value, $exptime=0) {
99 if( $this->get($key) == false ) {
100 $this->set($key, $value, $exptime);
101 return true;
105 function add_multi($hash, $exptime=0) {
106 foreach($hash as $key => $value)
107 $this->add($key, $value, $exptime);
110 function delete_multi($keys, $time=0) {
111 foreach($keys as $key)
112 $this->delete($key, $time);
115 function replace($key, $value, $exptime=0) {
116 if( $this->get($key) !== false )
117 $this->set($key, $value, $exptime);
120 function incr($key, $value=1) {
121 if ( !$this->lock($key) ) {
122 return false;
124 $value = intval($value);
125 if($value < 0) $value = 0;
127 $n = false;
128 if( ($n = $this->get($key)) !== false ) {
129 $n += $value;
130 $this->set($key, $n); // exptime?
132 $this->unlock($key);
133 return $n;
136 function decr($key, $value=1) {
137 if ( !$this->lock($key) ) {
138 return false;
140 $value = intval($value);
141 if($value < 0) $value = 0;
143 $m = false;
144 if( ($n = $this->get($key)) !== false ) {
145 $m = $n - $value;
146 if($m < 0) $m = 0;
147 $this->set($key, $m); // exptime?
149 $this->unlock($key);
150 return $m;
153 function _debug($text) {
154 if($this->debugmode)
155 wfDebug("BagOStuff debug: $text\n");
159 * Convert an optionally relative time to an absolute time
161 static function convertExpiry( $exptime ) {
162 if(($exptime != 0) && ($exptime < 3600*24*30)) {
163 return time() + $exptime;
164 } else {
165 return $exptime;
172 * Functional versions!
173 * This is a test of the interface, mainly. It stores things in an associative
174 * array, which is not going to persist between program runs.
176 * @ingroup Cache
178 class HashBagOStuff extends BagOStuff {
179 var $bag;
181 function __construct() {
182 $this->bag = array();
185 function _expire($key) {
186 $et = $this->bag[$key][1];
187 if(($et == 0) || ($et > time()))
188 return false;
189 $this->delete($key);
190 return true;
193 function get($key) {
194 if(!$this->bag[$key])
195 return false;
196 if($this->_expire($key))
197 return false;
198 return $this->bag[$key][0];
201 function set($key,$value,$exptime=0) {
202 $this->bag[$key] = array( $value, BagOStuff::convertExpiry( $exptime ) );
205 function delete($key,$time=0) {
206 if(!$this->bag[$key])
207 return false;
208 unset($this->bag[$key]);
209 return true;
212 function keys() {
213 return array_keys( $this->bag );
218 * Generic class to store objects in a database
220 * @ingroup Cache
222 abstract class SqlBagOStuff extends BagOStuff {
223 var $table;
224 var $lastexpireall = 0;
227 * Constructor
229 * @param $tablename String: name of the table to use
231 function __construct($tablename = 'objectcache') {
232 $this->table = $tablename;
235 function get($key) {
236 /* expire old entries if any */
237 $this->garbageCollect();
239 $res = $this->_query(
240 "SELECT value,exptime FROM $0 WHERE keyname='$1'", $key);
241 if(!$res) {
242 $this->_debug("get: ** error: " . $this->_dberror($res) . " **");
243 return false;
245 if($row=$this->_fetchobject($res)) {
246 $this->_debug("get: retrieved data; exp time is " . $row->exptime);
247 if ( $row->exptime != $this->_maxdatetime() &&
248 wfTimestamp( TS_UNIX, $row->exptime ) < time() )
250 $this->_debug("get: key has expired, deleting");
251 $this->delete($key);
252 return false;
254 return $this->_unserialize($this->_blobdecode($row->value));
255 } else {
256 $this->_debug('get: no matching rows');
258 return false;
261 function set($key,$value,$exptime=0) {
262 if ( $this->_readonly() ) {
263 return false;
265 $exptime = intval($exptime);
266 if($exptime < 0) $exptime = 0;
267 if($exptime == 0) {
268 $exp = $this->_maxdatetime();
269 } else {
270 if($exptime < 3.16e8) # ~10 years
271 $exptime += time();
272 $exp = $this->_fromunixtime($exptime);
274 $this->delete( $key );
275 $this->_doinsert($this->getTableName(), array(
276 'keyname' => $key,
277 'value' => $this->_blobencode($this->_serialize($value)),
278 'exptime' => $exp
280 return true; /* ? */
283 function delete($key,$time=0) {
284 if ( $this->_readonly() ) {
285 return false;
287 $this->_query(
288 "DELETE FROM $0 WHERE keyname='$1'", $key );
289 return true; /* ? */
292 function keys() {
293 $res = $this->_query( "SELECT keyname FROM $0" );
294 if(!$res) {
295 $this->_debug("keys: ** error: " . $this->_dberror($res) . " **");
296 return array();
298 $result = array();
299 while( $row = $this->_fetchobject($res) ) {
300 $result[] = $row->keyname;
302 return $result;
305 function getTableName() {
306 return $this->table;
309 function _query($sql) {
310 $reps = func_get_args();
311 $reps[0] = $this->getTableName();
312 // ewwww
313 for($i=0;$i<count($reps);$i++) {
314 $sql = str_replace(
315 '$' . $i,
316 $i > 0 ? $this->_strencode($reps[$i]) : $reps[$i],
317 $sql);
319 $res = $this->_doquery($sql);
320 if($res == false) {
321 $this->_debug('query failed: ' . $this->_dberror($res));
323 return $res;
326 function _strencode($str) {
327 /* Protect strings in SQL */
328 return str_replace( "'", "''", $str );
330 function _blobencode($str) {
331 return $str;
333 function _blobdecode($str) {
334 return $str;
337 abstract function _doinsert($table, $vals);
338 abstract function _doquery($sql);
340 abstract function _readonly();
342 function _freeresult($result) {
343 /* stub */
344 return false;
347 function _dberror($result) {
348 /* stub */
349 return 'unknown error';
352 abstract function _maxdatetime();
353 abstract function _fromunixtime($ts);
355 function garbageCollect() {
356 /* Ignore 99% of requests */
357 if ( !mt_rand( 0, 100 ) ) {
358 $nowtime = time();
359 /* Avoid repeating the delete within a few seconds */
360 if ( $nowtime > ($this->lastexpireall + 1) ) {
361 $this->lastexpireall = $nowtime;
362 $this->expireall();
367 function expireall() {
368 /* Remove any items that have expired */
369 if ( $this->_readonly() ) {
370 return false;
372 $now = $this->_fromunixtime( time() );
373 $this->_query( "DELETE FROM $0 WHERE exptime < '$now'" );
376 function deleteall() {
377 /* Clear *all* items from cache table */
378 if ( $this->_readonly() ) {
379 return false;
381 $this->_query( "DELETE FROM $0" );
385 * Serialize an object and, if possible, compress the representation.
386 * On typical message and page data, this can provide a 3X decrease
387 * in storage requirements.
389 * @param $data mixed
390 * @return string
392 function _serialize( &$data ) {
393 $serial = serialize( $data );
394 if( function_exists( 'gzdeflate' ) ) {
395 return gzdeflate( $serial );
396 } else {
397 return $serial;
402 * Unserialize and, if necessary, decompress an object.
403 * @param $serial string
404 * @return mixed
406 function _unserialize( $serial ) {
407 if( function_exists( 'gzinflate' ) ) {
408 $decomp = @gzinflate( $serial );
409 if( false !== $decomp ) {
410 $serial = $decomp;
413 $ret = unserialize( $serial );
414 return $ret;
419 * Stores objects in the main database of the wiki
421 * @ingroup Cache
423 class MediaWikiBagOStuff extends SqlBagOStuff {
424 var $tableInitialised = false;
426 function _getDB(){
427 static $db;
428 if( !isset( $db ) )
429 $db = wfGetDB( DB_MASTER );
430 return $db;
432 function _doquery($sql) {
433 return $this->_getDB()->query( $sql, __METHOD__ );
435 function _doinsert($t, $v) {
436 return $this->_getDB()->insert($t, $v, __METHOD__, array( 'IGNORE' ) );
438 function _fetchobject($result) {
439 return $this->_getDB()->fetchObject($result);
441 function _freeresult($result) {
442 return $this->_getDB()->freeResult($result);
444 function _dberror($result) {
445 return $this->_getDB()->lastError();
447 function _maxdatetime() {
448 if ( time() > 0x7fffffff ) {
449 return $this->_fromunixtime( 1<<62 );
450 } else {
451 return $this->_fromunixtime( 0x7fffffff );
454 function _fromunixtime($ts) {
455 return $this->_getDB()->timestamp($ts);
457 function _readonly(){
458 return wfReadOnly();
460 function _strencode($s) {
461 return $this->_getDB()->strencode($s);
463 function _blobencode($s) {
464 return $this->_getDB()->encodeBlob($s);
466 function _blobdecode($s) {
467 return $this->_getDB()->decodeBlob($s);
469 function getTableName() {
470 if ( !$this->tableInitialised ) {
471 $dbw = $this->_getDB();
472 /* This is actually a hack, we should be able
473 to use Language classes here... or not */
474 if (!$dbw)
475 throw new MWException("Could not connect to database");
476 $this->table = $dbw->tableName( $this->table );
477 $this->tableInitialised = true;
479 return $this->table;
484 * This is a wrapper for Turck MMCache's shared memory functions.
486 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
487 * to use a weird custom serializer that randomly segfaults. So we wrap calls
488 * with serialize()/unserialize().
490 * The thing I noticed about the Turck serialized data was that unlike ordinary
491 * serialize(), it contained the names of methods, and judging by the amount of
492 * binary data, perhaps even the bytecode of the methods themselves. It may be
493 * that Turck's serializer is faster, so a possible future extension would be
494 * to use it for arrays but not for objects.
496 * @ingroup Cache
498 class TurckBagOStuff extends BagOStuff {
499 function get($key) {
500 $val = mmcache_get( $key );
501 if ( is_string( $val ) ) {
502 $val = unserialize( $val );
504 return $val;
507 function set($key, $value, $exptime=0) {
508 mmcache_put( $key, serialize( $value ), $exptime );
509 return true;
512 function delete($key, $time=0) {
513 mmcache_rm( $key );
514 return true;
517 function lock($key, $waitTimeout = 0 ) {
518 mmcache_lock( $key );
519 return true;
522 function unlock($key) {
523 mmcache_unlock( $key );
524 return true;
529 * This is a wrapper for APC's shared memory functions
531 * @ingroup Cache
533 class APCBagOStuff extends BagOStuff {
534 function get($key) {
535 $val = apc_fetch($key);
536 if ( is_string( $val ) ) {
537 $val = unserialize( $val );
539 return $val;
542 function set($key, $value, $exptime=0) {
543 apc_store($key, serialize($value), $exptime);
544 return true;
547 function delete($key, $time=0) {
548 apc_delete($key);
549 return true;
555 * This is a wrapper for eAccelerator's shared memory functions.
557 * This is basically identical to the Turck MMCache version,
558 * mostly because eAccelerator is based on Turck MMCache.
560 * @ingroup Cache
562 class eAccelBagOStuff extends BagOStuff {
563 function get($key) {
564 $val = eaccelerator_get( $key );
565 if ( is_string( $val ) ) {
566 $val = unserialize( $val );
568 return $val;
571 function set($key, $value, $exptime=0) {
572 eaccelerator_put( $key, serialize( $value ), $exptime );
573 return true;
576 function delete($key, $time=0) {
577 eaccelerator_rm( $key );
578 return true;
581 function lock($key, $waitTimeout = 0 ) {
582 eaccelerator_lock( $key );
583 return true;
586 function unlock($key) {
587 eaccelerator_unlock( $key );
588 return true;
593 * Wrapper for XCache object caching functions; identical interface
594 * to the APC wrapper
596 * @ingroup Cache
598 class XCacheBagOStuff extends BagOStuff {
601 * Get a value from the XCache object cache
603 * @param $key String: cache key
604 * @return mixed
606 public function get( $key ) {
607 $val = xcache_get( $key );
608 if( is_string( $val ) )
609 $val = unserialize( $val );
610 return $val;
614 * Store a value in the XCache object cache
616 * @param $key String: cache key
617 * @param $value Mixed: object to store
618 * @param $expire Int: expiration time
619 * @return bool
621 public function set( $key, $value, $expire = 0 ) {
622 xcache_set( $key, serialize( $value ), $expire );
623 return true;
627 * Remove a value from the XCache object cache
629 * @param $key String: cache key
630 * @param $time Int: not used in this implementation
631 * @return bool
633 public function delete( $key, $time = 0 ) {
634 xcache_unset( $key );
635 return true;
641 * @todo document
642 * @ingroup Cache
644 class DBABagOStuff extends BagOStuff {
645 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
647 function __construct( $handler = 'db3', $dir = false ) {
648 if ( $dir === false ) {
649 global $wgTmpDirectory;
650 $dir = $wgTmpDirectory;
652 $this->mFile = "$dir/mw-cache-" . wfWikiID();
653 $this->mFile .= '.db';
654 wfDebug( __CLASS__.": using cache file {$this->mFile}\n" );
655 $this->mHandler = $handler;
659 * Encode value and expiry for storage
661 function encode( $value, $expiry ) {
662 # Convert to absolute time
663 $expiry = BagOStuff::convertExpiry( $expiry );
664 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
668 * @return list containing value first and expiry second
670 function decode( $blob ) {
671 if ( !is_string( $blob ) ) {
672 return array( null, 0 );
673 } else {
674 return array(
675 unserialize( substr( $blob, 11 ) ),
676 intval( substr( $blob, 0, 10 ) )
681 function getReader() {
682 if ( file_exists( $this->mFile ) ) {
683 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
684 } else {
685 $handle = $this->getWriter();
687 if ( !$handle ) {
688 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
690 return $handle;
693 function getWriter() {
694 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
695 if ( !$handle ) {
696 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
698 return $handle;
701 function get( $key ) {
702 wfProfileIn( __METHOD__ );
703 wfDebug( __METHOD__."($key)\n" );
704 $handle = $this->getReader();
705 if ( !$handle ) {
706 return null;
708 $val = dba_fetch( $key, $handle );
709 list( $val, $expiry ) = $this->decode( $val );
710 # Must close ASAP because locks are held
711 dba_close( $handle );
713 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
714 # Key is expired, delete it
715 $handle = $this->getWriter();
716 dba_delete( $key, $handle );
717 dba_close( $handle );
718 wfDebug( __METHOD__.": $key expired\n" );
719 $val = null;
721 wfProfileOut( __METHOD__ );
722 return $val;
725 function set( $key, $value, $exptime=0 ) {
726 wfProfileIn( __METHOD__ );
727 wfDebug( __METHOD__."($key)\n" );
728 $blob = $this->encode( $value, $exptime );
729 $handle = $this->getWriter();
730 if ( !$handle ) {
731 return false;
733 $ret = dba_replace( $key, $blob, $handle );
734 dba_close( $handle );
735 wfProfileOut( __METHOD__ );
736 return $ret;
739 function delete( $key, $time = 0 ) {
740 wfProfileIn( __METHOD__ );
741 wfDebug( __METHOD__."($key)\n" );
742 $handle = $this->getWriter();
743 if ( !$handle ) {
744 return false;
746 $ret = dba_delete( $key, $handle );
747 dba_close( $handle );
748 wfProfileOut( __METHOD__ );
749 return $ret;
752 function add( $key, $value, $exptime = 0 ) {
753 wfProfileIn( __METHOD__ );
754 $blob = $this->encode( $value, $exptime );
755 $handle = $this->getWriter();
756 if ( !$handle ) {
757 return false;
759 $ret = dba_insert( $key, $blob, $handle );
760 # Insert failed, check to see if it failed due to an expired key
761 if ( !$ret ) {
762 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
763 if ( $expiry < time() ) {
764 # Yes expired, delete and try again
765 dba_delete( $key, $handle );
766 $ret = dba_insert( $key, $blob, $handle );
767 # This time if it failed then it will be handled by the caller like any other race
771 dba_close( $handle );
772 wfProfileOut( __METHOD__ );
773 return $ret;
776 function keys() {
777 $reader = $this->getReader();
778 $k1 = dba_firstkey( $reader );
779 if( !$k1 ) {
780 return array();
782 $result[] = $k1;
783 while( $key = dba_nextkey( $reader ) ) {
784 $result[] = $key;
786 return $result;