ab05ab2094881eea41ee3687ac1c1cbb18493f49
[lhc/web/wiklou.git] / includes / BagOStuff.php
1 <?php
2 #
3 # Copyright (C) 2003-2004 Brion Vibber <brion@pobox.com>
4 # http://www.mediawiki.org/
5 #
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.
10 #
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.
15 #
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
20 /**
21 *
22 * @package MediaWiki
23 */
24
25 /**
26 * Simple generic object store
27 *
28 * interface is intended to be more or less compatible with
29 * the PHP memcached client.
30 *
31 * backends for local hash array and SQL table included:
32 * $bag = new HashBagOStuff();
33 * $bag = new MysqlBagOStuff($tablename); # connect to db first
34 *
35 * @package MediaWiki
36 */
37 class BagOStuff {
38 var $debugmode;
39
40 function BagOStuff() {
41 $this->set_debug( false );
42 }
43
44 function set_debug($bool) {
45 $this->debugmode = $bool;
46 }
47
48 /* *** THE GUTS OF THE OPERATION *** */
49 /* Override these with functional things in subclasses */
50
51 function get($key) {
52 /* stub */
53 return false;
54 }
55
56 function set($key, $value, $exptime=0) {
57 /* stub */
58 return false;
59 }
60
61 function delete($key, $time=0) {
62 /* stub */
63 return false;
64 }
65
66 function lock($key, $timeout = 0) {
67 /* stub */
68 return true;
69 }
70
71 function unlock($key) {
72 /* stub */
73 return true;
74 }
75
76 /* *** Emulated functions *** */
77 /* Better performance can likely be got with custom written versions */
78 function get_multi($keys) {
79 $out = array();
80 foreach($keys as $key)
81 $out[$key] = $this->get($key);
82 return $out;
83 }
84
85 function set_multi($hash, $exptime=0) {
86 foreach($hash as $key => $value)
87 $this->set($key, $value, $exptime);
88 }
89
90 function add($key, $value, $exptime=0) {
91 if( $this->get($key) == false ) {
92 $this->set($key, $value, $exptime);
93 return true;
94 }
95 }
96
97 function add_multi($hash, $exptime=0) {
98 foreach($hash as $key => $value)
99 $this->add($key, $value, $exptime);
100 }
101
102 function delete_multi($keys, $time=0) {
103 foreach($keys as $key)
104 $this->delete($key, $time);
105 }
106
107 function replace($key, $value, $exptime=0) {
108 if( $this->get($key) !== false )
109 $this->set($key, $value, $exptime);
110 }
111
112 function incr($key, $value=1) {
113 if ( !$this->lock($key) ) {
114 return false;
115 }
116 $value = intval($value);
117 if($value < 0) $value = 0;
118
119 $n = false;
120 if( ($n = $this->get($key)) !== false ) {
121 $n += $value;
122 $this->set($key, $n); // exptime?
123 }
124 $this->unlock($key);
125 return $n;
126 }
127
128 function decr($key, $value=1) {
129 if ( !$this->lock($key) ) {
130 return false;
131 }
132 $value = intval($value);
133 if($value < 0) $value = 0;
134
135 $m = false;
136 if( ($n = $this->get($key)) !== false ) {
137 $m = $n - $value;
138 if($m < 0) $m = 0;
139 $this->set($key, $m); // exptime?
140 }
141 $this->unlock($key);
142 return $m;
143 }
144
145 function _debug($text) {
146 if($this->debugmode)
147 wfDebug("BagOStuff debug: $text\n");
148 }
149
150 /**
151 * Convert an optionally relative time to an absolute time
152 */
153 static function convertExpiry( $exptime ) {
154 if(($exptime != 0) && ($exptime < 3600*24*30)) {
155 return time() + $exptime;
156 } else {
157 return $exptime;
158 }
159 }
160 }
161
162
163 /**
164 * Functional versions!
165 * @todo document
166 * @package MediaWiki
167 */
168 class HashBagOStuff extends BagOStuff {
169 /*
170 This is a test of the interface, mainly. It stores
171 things in an associative array, which is not going to
172 persist between program runs.
173 */
174 var $bag;
175
176 function HashBagOStuff() {
177 $this->bag = array();
178 }
179
180 function _expire($key) {
181 $et = $this->bag[$key][1];
182 if(($et == 0) || ($et > time()))
183 return false;
184 $this->delete($key);
185 return true;
186 }
187
188 function get($key) {
189 if(!$this->bag[$key])
190 return false;
191 if($this->_expire($key))
192 return false;
193 return $this->bag[$key][0];
194 }
195
196 function set($key,$value,$exptime=0) {
197 $this->bag[$key] = array( $value, BagOStuff::convertExpiry( $exptime ) );
198 }
199
200 function delete($key,$time=0) {
201 if(!$this->bag[$key])
202 return false;
203 unset($this->bag[$key]);
204 return true;
205 }
206 }
207
208 /*
209 CREATE TABLE objectcache (
210 keyname char(255) binary not null default '',
211 value mediumblob,
212 exptime datetime,
213 unique key (keyname),
214 key (exptime)
215 );
216 */
217
218 /**
219 * @todo document
220 * @abstract
221 * @package MediaWiki
222 */
223 abstract class SqlBagOStuff extends BagOStuff {
224 var $table;
225 var $lastexpireall = 0;
226
227 function SqlBagOStuff($tablename = 'objectcache') {
228 $this->table = $tablename;
229 }
230
231 function get($key) {
232 /* expire old entries if any */
233 $this->garbageCollect();
234
235 $res = $this->_query(
236 "SELECT value,exptime FROM $0 WHERE keyname='$1'", $key);
237 if(!$res) {
238 $this->_debug("get: ** error: " . $this->_dberror($res) . " **");
239 return false;
240 }
241 if($row=$this->_fetchobject($res)) {
242 $this->_debug("get: retrieved data; exp time is " . $row->exptime);
243 if ( $row->exptime != $this->_maxdatetime() &&
244 wfTimestamp( TS_UNIX, $row->exptime ) < time() )
245 {
246 $this->_debug("get: key has expired, deleting");
247 $this->delete($key);
248 return false;
249 }
250 return $this->_unserialize($this->_blobdecode($row->value));
251 } else {
252 $this->_debug('get: no matching rows');
253 }
254 return false;
255 }
256
257 function set($key,$value,$exptime=0) {
258 $exptime = intval($exptime);
259 if($exptime < 0) $exptime = 0;
260 if($exptime == 0) {
261 $exp = $this->_maxdatetime();
262 } else {
263 if($exptime < 3.16e8) # ~10 years
264 $exptime += time();
265 $exp = $this->_fromunixtime($exptime);
266 }
267 $this->delete( $key );
268 $this->_doinsert($this->getTableName(), array(
269 'keyname' => $key,
270 'value' => $this->_blobencode($this->_serialize($value)),
271 'exptime' => $exp
272 ));
273 return true; /* ? */
274 }
275
276 function delete($key,$time=0) {
277 $this->_query(
278 "DELETE FROM $0 WHERE keyname='$1'", $key );
279 return true; /* ? */
280 }
281
282 function getTableName() {
283 return $this->table;
284 }
285
286 function _query($sql) {
287 $reps = func_get_args();
288 $reps[0] = $this->getTableName();
289 // ewwww
290 for($i=0;$i<count($reps);$i++) {
291 $sql = str_replace(
292 '$' . $i,
293 $i > 0 ? $this->_strencode($reps[$i]) : $reps[$i],
294 $sql);
295 }
296 $res = $this->_doquery($sql);
297 if($res == false) {
298 $this->_debug('query failed: ' . $this->_dberror($res));
299 }
300 return $res;
301 }
302
303 function _strencode($str) {
304 /* Protect strings in SQL */
305 return str_replace( "'", "''", $str );
306 }
307 function _blobencode($str) {
308 return $str;
309 }
310 function _blobdecode($str) {
311 return $str;
312 }
313
314 abstract function _doinsert($table, $vals);
315 abstract function _doquery($sql);
316
317 function _freeresult($result) {
318 /* stub */
319 return false;
320 }
321
322 function _dberror($result) {
323 /* stub */
324 return 'unknown error';
325 }
326
327 abstract function _maxdatetime();
328 abstract function _fromunixtime($ts);
329
330 function garbageCollect() {
331 /* Ignore 99% of requests */
332 if ( !mt_rand( 0, 100 ) ) {
333 $nowtime = time();
334 /* Avoid repeating the delete within a few seconds */
335 if ( $nowtime > ($this->lastexpireall + 1) ) {
336 $this->lastexpireall = $nowtime;
337 $this->expireall();
338 }
339 }
340 }
341
342 function expireall() {
343 /* Remove any items that have expired */
344 $now = $this->_fromunixtime( time() );
345 $this->_query( "DELETE FROM $0 WHERE exptime < '$now'" );
346 }
347
348 function deleteall() {
349 /* Clear *all* items from cache table */
350 $this->_query( "DELETE FROM $0" );
351 }
352
353 /**
354 * Serialize an object and, if possible, compress the representation.
355 * On typical message and page data, this can provide a 3X decrease
356 * in storage requirements.
357 *
358 * @param mixed $data
359 * @return string
360 */
361 function _serialize( &$data ) {
362 $serial = serialize( $data );
363 if( function_exists( 'gzdeflate' ) ) {
364 return gzdeflate( $serial );
365 } else {
366 return $serial;
367 }
368 }
369
370 /**
371 * Unserialize and, if necessary, decompress an object.
372 * @param string $serial
373 * @return mixed
374 */
375 function _unserialize( $serial ) {
376 if( function_exists( 'gzinflate' ) ) {
377 $decomp = @gzinflate( $serial );
378 if( false !== $decomp ) {
379 $serial = $decomp;
380 }
381 }
382 $ret = unserialize( $serial );
383 return $ret;
384 }
385 }
386
387 /**
388 * @todo document
389 * @package MediaWiki
390 */
391 class MediaWikiBagOStuff extends SqlBagOStuff {
392 var $tableInitialised = false;
393
394 function _doquery($sql) {
395 $dbw =& wfGetDB( DB_MASTER );
396 return $dbw->query($sql, 'MediaWikiBagOStuff::_doquery');
397 }
398 function _doinsert($t, $v) {
399 $dbw =& wfGetDB( DB_MASTER );
400 return $dbw->insert($t, $v, 'MediaWikiBagOStuff::_doinsert',
401 array( 'IGNORE' ) );
402 }
403 function _fetchobject($result) {
404 $dbw =& wfGetDB( DB_MASTER );
405 return $dbw->fetchObject($result);
406 }
407 function _freeresult($result) {
408 $dbw =& wfGetDB( DB_MASTER );
409 return $dbw->freeResult($result);
410 }
411 function _dberror($result) {
412 $dbw =& wfGetDB( DB_MASTER );
413 return $dbw->lastError();
414 }
415 function _maxdatetime() {
416 if ( time() > 0x7fffffff ) {
417 return $this->_fromunixtime( 1<<62 );
418 } else {
419 return $this->_fromunixtime( 0x7fffffff );
420 }
421 }
422 function _fromunixtime($ts) {
423 $dbw =& wfGetDB(DB_MASTER);
424 return $dbw->timestamp($ts);
425 }
426 function _strencode($s) {
427 $dbw =& wfGetDB( DB_MASTER );
428 return $dbw->strencode($s);
429 }
430 function _blobencode($s) {
431 $dbw =& wfGetDB( DB_MASTER );
432 return $dbw->encodeBlob($s);
433 }
434 function _blobdecode($s) {
435 $dbw =& wfGetDB( DB_MASTER );
436 return $dbw->decodeBlob($s);
437 }
438 function getTableName() {
439 if ( !$this->tableInitialised ) {
440 $dbw =& wfGetDB( DB_MASTER );
441 /* This is actually a hack, we should be able
442 to use Language classes here... or not */
443 if (!$dbw)
444 throw new MWException("Could not connect to database");
445 $this->table = $dbw->tableName( $this->table );
446 $this->tableInitialised = true;
447 }
448 return $this->table;
449 }
450 }
451
452 /**
453 * This is a wrapper for Turck MMCache's shared memory functions.
454 *
455 * You can store objects with mmcache_put() and mmcache_get(), but Turck seems
456 * to use a weird custom serializer that randomly segfaults. So we wrap calls
457 * with serialize()/unserialize().
458 *
459 * The thing I noticed about the Turck serialized data was that unlike ordinary
460 * serialize(), it contained the names of methods, and judging by the amount of
461 * binary data, perhaps even the bytecode of the methods themselves. It may be
462 * that Turck's serializer is faster, so a possible future extension would be
463 * to use it for arrays but not for objects.
464 *
465 * @package MediaWiki
466 */
467 class TurckBagOStuff extends BagOStuff {
468 function get($key) {
469 $val = mmcache_get( $key );
470 if ( is_string( $val ) ) {
471 $val = unserialize( $val );
472 }
473 return $val;
474 }
475
476 function set($key, $value, $exptime=0) {
477 mmcache_put( $key, serialize( $value ), $exptime );
478 return true;
479 }
480
481 function delete($key, $time=0) {
482 mmcache_rm( $key );
483 return true;
484 }
485
486 function lock($key, $waitTimeout = 0 ) {
487 mmcache_lock( $key );
488 return true;
489 }
490
491 function unlock($key) {
492 mmcache_unlock( $key );
493 return true;
494 }
495 }
496
497 /**
498 * This is a wrapper for APC's shared memory functions
499 *
500 * @package MediaWiki
501 */
502
503 class APCBagOStuff extends BagOStuff {
504 function get($key) {
505 $val = apc_fetch($key);
506 if ( is_string( $val ) ) {
507 $val = unserialize( $val );
508 }
509 return $val;
510 }
511
512 function set($key, $value, $exptime=0) {
513 apc_store($key, serialize($value), $exptime);
514 return true;
515 }
516
517 function delete($key, $time=0) {
518 apc_delete($key);
519 return true;
520 }
521 }
522
523
524 /**
525 * This is a wrapper for eAccelerator's shared memory functions.
526 *
527 * This is basically identical to the Turck MMCache version,
528 * mostly because eAccelerator is based on Turck MMCache.
529 *
530 * @package MediaWiki
531 */
532 class eAccelBagOStuff extends BagOStuff {
533 function get($key) {
534 $val = eaccelerator_get( $key );
535 if ( is_string( $val ) ) {
536 $val = unserialize( $val );
537 }
538 return $val;
539 }
540
541 function set($key, $value, $exptime=0) {
542 eaccelerator_put( $key, serialize( $value ), $exptime );
543 return true;
544 }
545
546 function delete($key, $time=0) {
547 eaccelerator_rm( $key );
548 return true;
549 }
550
551 function lock($key, $waitTimeout = 0 ) {
552 eaccelerator_lock( $key );
553 return true;
554 }
555
556 function unlock($key) {
557 eaccelerator_unlock( $key );
558 return true;
559 }
560 }
561
562 class DBABagOStuff extends BagOStuff {
563 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
564
565 function __construct( $handler = 'db3', $dir = false ) {
566 if ( $dir === false ) {
567 global $wgTmpDirectory;
568 $dir = $wgTmpDirectory;
569 }
570 $this->mFile = "$dir/mw-cache-" . wfWikiID();
571 $this->mFile .= '.db';
572 $this->mHandler = $handler;
573 }
574
575 /**
576 * Encode value and expiry for storage
577 */
578 function encode( $value, $expiry ) {
579 # Convert to absolute time
580 $expiry = BagOStuff::convertExpiry( $expiry );
581 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
582 }
583
584 /**
585 * @return list containing value first and expiry second
586 */
587 function decode( $blob ) {
588 if ( !is_string( $blob ) ) {
589 return array( null, 0 );
590 } else {
591 return array(
592 unserialize( substr( $blob, 11 ) ),
593 intval( substr( $blob, 0, 10 ) )
594 );
595 }
596 }
597
598 function getReader() {
599 if ( file_exists( $this->mFile ) ) {
600 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
601 } else {
602 $handle = $this->getWriter();
603 }
604 if ( !$handle ) {
605 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
606 }
607 return $handle;
608 }
609
610 function getWriter() {
611 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
612 if ( !$handle ) {
613 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
614 }
615 return $handle;
616 }
617
618 function get( $key ) {
619 wfProfileIn( __METHOD__ );
620 wfDebug( __METHOD__."($key)\n" );
621 $handle = $this->getReader();
622 if ( !$handle ) {
623 return null;
624 }
625 $val = dba_fetch( $key, $handle );
626 list( $val, $expiry ) = $this->decode( $val );
627 # Must close ASAP because locks are held
628 dba_close( $handle );
629
630 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
631 # Key is expired, delete it
632 $handle = $this->getWriter();
633 dba_delete( $key, $handle );
634 dba_close( $handle );
635 wfDebug( __METHOD__.": $key expired\n" );
636 $val = null;
637 }
638 wfProfileOut( __METHOD__ );
639 return $val;
640 }
641
642 function set( $key, $value, $exptime=0 ) {
643 wfProfileIn( __METHOD__ );
644 wfDebug( __METHOD__."($key)\n" );
645 $blob = $this->encode( $value, $exptime );
646 $handle = $this->getWriter();
647 if ( !$handle ) {
648 return false;
649 }
650 $ret = dba_replace( $key, $blob, $handle );
651 dba_close( $handle );
652 wfProfileOut( __METHOD__ );
653 return $ret;
654 }
655
656 function delete( $key, $time = 0 ) {
657 wfProfileIn( __METHOD__ );
658 $handle = $this->getWriter();
659 if ( !$handle ) {
660 return false;
661 }
662 $ret = dba_delete( $key, $handle );
663 dba_close( $handle );
664 wfProfileOut( __METHOD__ );
665 return $ret;
666 }
667
668 function add( $key, $value, $exptime = 0 ) {
669 wfProfileIn( __METHOD__ );
670 $blob = $this->encode( $value, $exptime );
671 $handle = $this->getWriter();
672 if ( !$handle ) {
673 return false;
674 }
675 $ret = dba_insert( $key, $blob, $handle );
676 # Insert failed, check to see if it failed due to an expired key
677 if ( !$ret ) {
678 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
679 if ( $expiry < time() ) {
680 # Yes expired, delete and try again
681 dba_delete( $key, $handle );
682 $ret = dba_insert( $key, $blob, $handle );
683 # This time if it failed then it will be handled by the caller like any other race
684 }
685 }
686
687 dba_close( $handle );
688 wfProfileOut( __METHOD__ );
689 return $ret;
690 }
691 }
692
693 ?>