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
26 * Simple generic object store
28 * interface is intended to be more or less compatible with
29 * the PHP memcached client.
31 * backends for local hash array and SQL table included:
32 * $bag = new HashBagOStuff();
33 * $bag = new MysqlBagOStuff($tablename); # connect to db first
40 function BagOStuff() {
41 $this->set_debug( false );
44 function set_debug($bool) {
45 $this->debugmode
= $bool;
48 /* *** THE GUTS OF THE OPERATION *** */
49 /* Override these with functional things in subclasses */
56 function set($key, $value, $exptime=0) {
61 function delete($key, $time=0) {
66 function lock($key, $timeout = 0) {
71 function unlock($key) {
76 /* *** Emulated functions *** */
77 /* Better performance can likely be got with custom written versions */
78 function get_multi($keys) {
80 foreach($keys as $key)
81 $out[$key] = $this->get($key);
85 function set_multi($hash, $exptime=0) {
86 foreach($hash as $key => $value)
87 $this->set($key, $value, $exptime);
90 function add($key, $value, $exptime=0) {
91 if( $this->get($key) == false ) {
92 $this->set($key, $value, $exptime);
97 function add_multi($hash, $exptime=0) {
98 foreach($hash as $key => $value)
99 $this->add($key, $value, $exptime);
102 function delete_multi($keys, $time=0) {
103 foreach($keys as $key)
104 $this->delete($key, $time);
107 function replace($key, $value, $exptime=0) {
108 if( $this->get($key) !== false )
109 $this->set($key, $value, $exptime);
112 function incr($key, $value=1) {
113 if ( !$this->lock($key) ) {
116 $value = intval($value);
117 if($value < 0) $value = 0;
120 if( ($n = $this->get($key)) !== false ) {
122 $this->set($key, $n); // exptime?
128 function decr($key, $value=1) {
129 if ( !$this->lock($key) ) {
132 $value = intval($value);
133 if($value < 0) $value = 0;
136 if( ($n = $this->get($key)) !== false ) {
139 $this->set($key, $m); // exptime?
145 function _debug($text) {
147 wfDebug("BagOStuff debug: $text\n");
153 * Functional versions!
157 class HashBagOStuff
extends BagOStuff
{
159 This is a test of the interface, mainly. It stores
160 things in an associative array, which is not going to
161 persist between program runs.
165 function HashBagOStuff() {
166 $this->bag
= array();
169 function _expire($key) {
170 $et = $this->bag
[$key][1];
171 if(($et == 0) ||
($et > time()))
178 if(!$this->bag
[$key])
180 if($this->_expire($key))
182 return $this->bag
[$key][0];
185 function set($key,$value,$exptime=0) {
186 if(($exptime != 0) && ($exptime < 3600*24*30))
187 $exptime = time() +
$exptime;
188 $this->bag
[$key] = array( $value, $exptime );
191 function delete($key,$time=0) {
192 if(!$this->bag
[$key])
194 unset($this->bag
[$key]);
200 CREATE TABLE objectcache (
201 keyname char(255) binary not null default '',
204 unique key (keyname),
214 abstract class SqlBagOStuff
extends BagOStuff
{
216 var $lastexpireall = 0;
218 function SqlBagOStuff($tablename = 'objectcache') {
219 $this->table
= $tablename;
223 /* expire old entries if any */
224 $this->garbageCollect();
226 $res = $this->_query(
227 "SELECT value,exptime FROM $0 WHERE keyname='$1'", $key);
229 $this->_debug("get: ** error: " . $this->_dberror($res) . " **");
232 if($row=$this->_fetchobject($res)) {
233 $this->_debug("get: retrieved data; exp time is " . $row->exptime
);
234 return $this->_unserialize($row->value
);
236 $this->_debug('get: no matching rows');
241 function set($key,$value,$exptime=0) {
242 $exptime = intval($exptime);
243 if($exptime < 0) $exptime = 0;
245 $exp = $this->_maxdatetime();
247 if($exptime < 3600*24*30)
249 $exp = $this->_fromunixtime($exptime);
251 $this->delete( $key );
252 $this->_doinsert($this->getTableName(), array(
254 'value' => $this->_blobencode($this->_serialize($value)),
260 function delete($key,$time=0) {
262 "DELETE FROM $0 WHERE keyname='$1'", $key );
266 function getTableName() {
270 function _query($sql) {
271 $reps = func_get_args();
272 $reps[0] = $this->getTableName();
274 for($i=0;$i<count($reps);$i++
) {
277 $i > 0 ?
$this->_strencode($reps[$i]) : $reps[$i],
280 $res = $this->_doquery($sql);
282 $this->_debug('query failed: ' . $this->_dberror($res));
287 function _strencode($str) {
288 /* Protect strings in SQL */
289 return str_replace( "'", "''", $str );
291 function _blobencode($str) {
295 abstract function _doinsert($table, $vals);
296 abstract function _doquery($sql);
298 function _freeresult($result) {
303 function _dberror($result) {
305 return 'unknown error';
308 abstract function _maxdatetime();
309 abstract function _fromunixtime($ts);
311 function garbageCollect() {
312 /* Ignore 99% of requests */
313 if ( !mt_rand( 0, 100 ) ) {
315 /* Avoid repeating the delete within a few seconds */
316 if ( $nowtime > ($this->lastexpireall +
1) ) {
317 $this->lastexpireall
= $nowtime;
323 function expireall() {
324 /* Remove any items that have expired */
325 $now = $this->_fromunixtime( time() );
326 $this->_query( "DELETE FROM $0 WHERE exptime < '$now'" );
329 function deleteall() {
330 /* Clear *all* items from cache table */
331 $this->_query( "DELETE FROM $0" );
335 * Serialize an object and, if possible, compress the representation.
336 * On typical message and page data, this can provide a 3X decrease
337 * in storage requirements.
342 function _serialize( &$data ) {
343 $serial = serialize( $data );
344 if( function_exists( 'gzdeflate' ) ) {
345 return gzdeflate( $serial );
352 * Unserialize and, if necessary, decompress an object.
353 * @param string $serial
356 function _unserialize( $serial ) {
357 if( function_exists( 'gzinflate' ) ) {
358 $decomp = @gzinflate
( $serial );
359 if( false !== $decomp ) {
363 $ret = unserialize( $serial );
372 class MediaWikiBagOStuff
extends SqlBagOStuff
{
373 var $tableInitialised = false;
375 function _doquery($sql) {
376 $dbw =& wfGetDB( DB_MASTER
);
377 return $dbw->query($sql, 'MediaWikiBagOStuff::_doquery');
379 function _doinsert($t, $v) {
380 $dbw =& wfGetDB( DB_MASTER
);
381 return $dbw->insert($t, $v, 'MediaWikiBagOStuff::_doinsert');
383 function _fetchobject($result) {
384 $dbw =& wfGetDB( DB_MASTER
);
385 return $dbw->fetchObject($result);
387 function _freeresult($result) {
388 $dbw =& wfGetDB( DB_MASTER
);
389 return $dbw->freeResult($result);
391 function _dberror($result) {
392 $dbw =& wfGetDB( DB_MASTER
);
393 return $dbw->lastError();
395 function _maxdatetime() {
396 $dbw =& wfGetDB(DB_MASTER
);
397 return $dbw->timestamp('9999-12-31 12:59:59');
399 function _fromunixtime($ts) {
400 $dbw =& wfGetDB(DB_MASTER
);
401 return $dbw->timestamp($ts);
403 function _strencode($s) {
404 $dbw =& wfGetDB( DB_MASTER
);
405 return $dbw->strencode($s);
407 function _blobencode($s) {
408 $dbw =& wfGetDB( DB_MASTER
);
409 return $dbw->encodeBlob($s);
411 function getTableName() {
412 if ( !$this->tableInitialised
) {
413 $dbw =& wfGetDB( DB_MASTER
);
414 /* This is actually a hack, we should be able
415 to use Language classes here... or not */
417 throw new MWException("Could not connect to database");
418 $this->table
= $dbw->tableName( $this->table
);
419 $this->tableInitialised
= true;
426 * This is a wrapper for Turck MMCache's shared memory functions.
428 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
429 * to use a weird custom serializer that randomly segfaults. So we wrap calls
430 * with serialize()/unserialize().
432 * The thing I noticed about the Turck serialized data was that unlike ordinary
433 * serialize(), it contained the names of methods, and judging by the amount of
434 * binary data, perhaps even the bytecode of the methods themselves. It may be
435 * that Turck's serializer is faster, so a possible future extension would be
436 * to use it for arrays but not for objects.
440 class TurckBagOStuff
extends BagOStuff
{
442 $val = mmcache_get( $key );
443 if ( is_string( $val ) ) {
444 $val = unserialize( $val );
449 function set($key, $value, $exptime=0) {
450 mmcache_put( $key, serialize( $value ), $exptime );
454 function delete($key, $time=0) {
459 function lock($key, $waitTimeout = 0 ) {
460 mmcache_lock( $key );
464 function unlock($key) {
465 mmcache_unlock( $key );
471 * This is a wrapper for APC's shared memory functions
476 class APCBagOStuff
extends BagOStuff
{
478 $val = apc_fetch($key);
482 function set($key, $value, $exptime=0) {
483 apc_store($key, $value, $exptime);
487 function delete($key) {
495 * This is a wrapper for eAccelerator's shared memory functions.
497 * This is basically identical to the Turck MMCache version,
498 * mostly because eAccelerator is based on Turck MMCache.
502 class eAccelBagOStuff
extends BagOStuff
{
504 $val = eaccelerator_get( $key );
505 if ( is_string( $val ) ) {
506 $val = unserialize( $val );
511 function set($key, $value, $exptime=0) {
512 eaccelerator_put( $key, serialize( $value ), $exptime );
516 function delete($key, $time=0) {
517 eaccelerator_rm( $key );
521 function lock($key, $waitTimeout = 0 ) {
522 eaccelerator_lock( $key );
526 function unlock($key) {
527 eaccelerator_unlock( $key );