Fixup some more wrong static usages
[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 * @defgroup Cache Cache
23 *
24 * @file
25 * @ingroup Cache
26 */
27
28 /**
29 * interface is intended to be more or less compatible with
30 * the PHP memcached client.
31 *
32 * backends for local hash array and SQL table included:
33 * <code>
34 * $bag = new HashBagOStuff();
35 * $bag = new SqlBagOStuff(); # connect to db first
36 * </code>
37 *
38 * @ingroup Cache
39 */
40 abstract class BagOStuff {
41 var $debugMode = false;
42
43 public function set_debug( $bool ) {
44 $this->debugMode = $bool;
45 }
46
47 /* *** THE GUTS OF THE OPERATION *** */
48 /* Override these with functional things in subclasses */
49
50 /**
51 * Get an item with the given key. Returns false if it does not exist.
52 * @param $key string
53 */
54 abstract public function get( $key );
55
56 /**
57 * Set an item.
58 * @param $key string
59 * @param $value mixed
60 * @param $exptime int Either an interval in seconds or a unix timestamp for expiry
61 */
62 abstract public function set( $key, $value, $exptime = 0 );
63
64 /*
65 * Delete an item.
66 * @param $key string
67 * @param $time int Amount of time to delay the operation (mostly memcached-specific)
68 */
69 abstract public function delete( $key, $time = 0 );
70
71 public function lock( $key, $timeout = 0 ) {
72 /* stub */
73 return true;
74 }
75
76 public function unlock( $key ) {
77 /* stub */
78 return true;
79 }
80
81 public function keys() {
82 /* stub */
83 return array();
84 }
85
86 /* *** Emulated functions *** */
87 /* Better performance can likely be got with custom written versions */
88 public function get_multi( $keys ) {
89 $out = array();
90
91 foreach ( $keys as $key ) {
92 $out[$key] = $this->get( $key );
93 }
94
95 return $out;
96 }
97
98 public function set_multi( $hash, $exptime = 0 ) {
99 foreach ( $hash as $key => $value ) {
100 $this->set( $key, $value, $exptime );
101 }
102 }
103
104 public function add( $key, $value, $exptime = 0 ) {
105 if ( !$this->get( $key ) ) {
106 $this->set( $key, $value, $exptime );
107
108 return true;
109 }
110 }
111
112 public function add_multi( $hash, $exptime = 0 ) {
113 foreach ( $hash as $key => $value ) {
114 $this->add( $key, $value, $exptime );
115 }
116 }
117
118 public function delete_multi( $keys, $time = 0 ) {
119 foreach ( $keys as $key ) {
120 $this->delete( $key, $time );
121 }
122 }
123
124 public function replace( $key, $value, $exptime = 0 ) {
125 if ( $this->get( $key ) !== false ) {
126 $this->set( $key, $value, $exptime );
127 }
128 }
129
130 public function incr( $key, $value = 1 ) {
131 if ( !$this->lock( $key ) ) {
132 return false;
133 }
134
135 $value = intval( $value );
136
137 $n = false;
138 if ( ( $n = $this->get( $key ) ) !== false ) {
139 $n += $value;
140 $this->set( $key, $n ); // exptime?
141 }
142 $this->unlock( $key );
143
144 return $n;
145 }
146
147 public function decr( $key, $value = 1 ) {
148 return $this->incr( $key, - $value );
149 }
150
151 public function debug( $text ) {
152 if ( $this->debugMode ) {
153 wfDebug( "BagOStuff debug: $text\n" );
154 }
155 }
156
157 /**
158 * Convert an optionally relative time to an absolute time
159 */
160 protected function convertExpiry( $exptime ) {
161 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
162 return time() + $exptime;
163 } else {
164 return $exptime;
165 }
166 }
167 }
168
169 /**
170 * Functional versions!
171 * This is a test of the interface, mainly. It stores things in an associative
172 * array, which is not going to persist between program runs.
173 *
174 * @ingroup Cache
175 */
176 class HashBagOStuff extends BagOStuff {
177 var $bag;
178
179 function __construct() {
180 $this->bag = array();
181 }
182
183 protected function expire( $key ) {
184 $et = $this->bag[$key][1];
185
186 if ( ( $et == 0 ) || ( $et > time() ) ) {
187 return false;
188 }
189
190 $this->delete( $key );
191
192 return true;
193 }
194
195 function get( $key ) {
196 if ( !isset( $this->bag[$key] ) ) {
197 return false;
198 }
199
200 if ( $this->expire( $key ) ) {
201 return false;
202 }
203
204 return $this->bag[$key][0];
205 }
206
207 function set( $key, $value, $exptime = 0 ) {
208 $this->bag[$key] = array( $value, $this->convertExpiry( $exptime ) );
209 }
210
211 function delete( $key, $time = 0 ) {
212 if ( !isset( $this->bag[$key] ) ) {
213 return false;
214 }
215
216 unset( $this->bag[$key] );
217
218 return true;
219 }
220
221 function keys() {
222 return array_keys( $this->bag );
223 }
224 }
225
226 /**
227 * Class to store objects in the database
228 *
229 * @ingroup Cache
230 */
231 class SqlBagOStuff extends BagOStuff {
232 var $lb, $db;
233 var $lastExpireAll = 0;
234
235 protected function getDB() {
236 global $wgDBtype;
237
238 if ( !isset( $this->db ) ) {
239 /* We must keep a separate connection to MySQL in order to avoid deadlocks
240 * However, SQLite has an opposite behaviour.
241 * @todo Investigate behaviour for other databases
242 */
243 if ( $wgDBtype == 'sqlite' ) {
244 $this->db = wfGetDB( DB_MASTER );
245 } else {
246 $this->lb = wfGetLBFactory()->newMainLB();
247 $this->db = $this->lb->getConnection( DB_MASTER );
248 $this->db->clearFlag( DBO_TRX );
249 }
250 }
251
252 return $this->db;
253 }
254
255 public function get( $key ) {
256 # expire old entries if any
257 $this->garbageCollect();
258 $db = $this->getDB();
259 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
260 array( 'keyname' => $key ), __METHOD__ );
261
262 if ( !$row ) {
263 $this->debug( 'get: no matching rows' );
264 return false;
265 }
266
267 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
268
269 if ( $this->isExpired( $row->exptime ) ) {
270 $this->debug( "get: key has expired, deleting" );
271 try {
272 $db->begin();
273 # Put the expiry time in the WHERE condition to avoid deleting a
274 # newly-inserted value
275 $db->delete( 'objectcache',
276 array(
277 'keyname' => $key,
278 'exptime' => $row->exptime
279 ), __METHOD__ );
280 $db->commit();
281 } catch ( DBQueryError $e ) {
282 $this->handleWriteError( $e );
283 }
284
285 return false;
286 }
287
288 return $this->unserialize( $db->decodeBlob( $row->value ) );
289 }
290
291 public function set( $key, $value, $exptime = 0 ) {
292 $db = $this->getDB();
293 $exptime = intval( $exptime );
294
295 if ( $exptime < 0 ) {
296 $exptime = 0;
297 }
298
299 if ( $exptime == 0 ) {
300 $encExpiry = $this->getMaxDateTime();
301 } else {
302 if ( $exptime < 3.16e8 ) { # ~10 years
303 $exptime += time();
304 }
305
306 $encExpiry = $db->timestamp( $exptime );
307 }
308 try {
309 $db->begin();
310 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
311 $db->insert( 'objectcache',
312 array(
313 'keyname' => $key,
314 'value' => $db->encodeBlob( $this->serialize( $value ) ),
315 'exptime' => $encExpiry
316 ), __METHOD__ );
317 $db->commit();
318 } catch ( DBQueryError $e ) {
319 $this->handleWriteError( $e );
320
321 return false;
322 }
323
324 return true;
325 }
326
327 public function delete( $key, $time = 0 ) {
328 $db = $this->getDB();
329
330 try {
331 $db->begin();
332 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
333 $db->commit();
334 } catch ( DBQueryError $e ) {
335 $this->handleWriteError( $e );
336
337 return false;
338 }
339
340 return true;
341 }
342
343 public function incr( $key, $step = 1 ) {
344 $db = $this->getDB();
345 $step = intval( $step );
346
347 try {
348 $db->begin();
349 $row = $db->selectRow( 'objectcache', array( 'value', 'exptime' ),
350 array( 'keyname' => $key ), __METHOD__, array( 'FOR UPDATE' ) );
351 if ( $row === false ) {
352 // Missing
353 $db->commit();
354
355 return false;
356 }
357 $db->delete( 'objectcache', array( 'keyname' => $key ), __METHOD__ );
358 if ( $this->isExpired( $row->exptime ) ) {
359 // Expired, do not reinsert
360 $db->commit();
361
362 return false;
363 }
364
365 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
366 $newValue = $oldValue + $step;
367 $db->insert( 'objectcache',
368 array(
369 'keyname' => $key,
370 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
371 'exptime' => $row->exptime
372 ), __METHOD__ );
373 $db->commit();
374 } catch ( DBQueryError $e ) {
375 $this->handleWriteError( $e );
376
377 return false;
378 }
379
380 return $newValue;
381 }
382
383 public function keys() {
384 $db = $this->getDB();
385 $res = $db->select( 'objectcache', array( 'keyname' ), false, __METHOD__ );
386 $result = array();
387
388 foreach ( $res as $row ) {
389 $result[] = $row->keyname;
390 }
391
392 return $result;
393 }
394
395 protected function isExpired( $exptime ) {
396 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
397 }
398
399 protected function getMaxDateTime() {
400 if ( time() > 0x7fffffff ) {
401 return $this->getDB()->timestamp( 1 << 62 );
402 } else {
403 return $this->getDB()->timestamp( 0x7fffffff );
404 }
405 }
406
407 protected function garbageCollect() {
408 /* Ignore 99% of requests */
409 if ( !mt_rand( 0, 100 ) ) {
410 $now = time();
411 /* Avoid repeating the delete within a few seconds */
412 if ( $now > ( $this->lastExpireAll + 1 ) ) {
413 $this->lastExpireAll = $now;
414 $this->expireAll();
415 }
416 }
417 }
418
419 public function expireAll() {
420 $db = $this->getDB();
421 $now = $db->timestamp();
422
423 try {
424 $db->begin();
425 $db->delete( 'objectcache', array( 'exptime < ' . $db->addQuotes( $now ) ), __METHOD__ );
426 $db->commit();
427 } catch ( DBQueryError $e ) {
428 $this->handleWriteError( $e );
429 }
430 }
431
432 public function deleteAll() {
433 $db = $this->getDB();
434
435 try {
436 $db->begin();
437 $db->delete( 'objectcache', '*', __METHOD__ );
438 $db->commit();
439 } catch ( DBQueryError $e ) {
440 $this->handleWriteError( $e );
441 }
442 }
443
444 /**
445 * Serialize an object and, if possible, compress the representation.
446 * On typical message and page data, this can provide a 3X decrease
447 * in storage requirements.
448 *
449 * @param $data mixed
450 * @return string
451 */
452 protected function serialize( &$data ) {
453 $serial = serialize( $data );
454
455 if ( function_exists( 'gzdeflate' ) ) {
456 return gzdeflate( $serial );
457 } else {
458 return $serial;
459 }
460 }
461
462 /**
463 * Unserialize and, if necessary, decompress an object.
464 * @param $serial string
465 * @return mixed
466 */
467 protected function unserialize( $serial ) {
468 if ( function_exists( 'gzinflate' ) ) {
469 $decomp = @gzinflate( $serial );
470
471 if ( false !== $decomp ) {
472 $serial = $decomp;
473 }
474 }
475
476 $ret = unserialize( $serial );
477
478 return $ret;
479 }
480
481 /**
482 * Handle a DBQueryError which occurred during a write operation.
483 * Ignore errors which are due to a read-only database, rethrow others.
484 */
485 protected function handleWriteError( $exception ) {
486 $db = $this->getDB();
487
488 if ( !$db->wasReadOnlyError() ) {
489 throw $exception;
490 }
491
492 try {
493 $db->rollback();
494 } catch ( DBQueryError $e ) {
495 }
496
497 wfDebug( __METHOD__ . ": ignoring query error\n" );
498 $db->ignoreErrors( false );
499 }
500 }
501
502 /**
503 * Backwards compatibility alias
504 */
505 class MediaWikiBagOStuff extends SqlBagOStuff { }
506
507 /**
508 * This is a wrapper for APC's shared memory functions
509 *
510 * @ingroup Cache
511 */
512 class APCBagOStuff extends BagOStuff {
513 public function get( $key ) {
514 $val = apc_fetch( $key );
515
516 if ( is_string( $val ) ) {
517 $val = unserialize( $val );
518 }
519
520 return $val;
521 }
522
523 public function set( $key, $value, $exptime = 0 ) {
524 apc_store( $key, serialize( $value ), $exptime );
525
526 return true;
527 }
528
529 public function delete( $key, $time = 0 ) {
530 apc_delete( $key );
531
532 return true;
533 }
534
535 public function keys() {
536 $info = apc_cache_info( 'user' );
537 $list = $info['cache_list'];
538 $keys = array();
539
540 foreach ( $list as $entry ) {
541 $keys[] = $entry['info'];
542 }
543
544 return $keys;
545 }
546 }
547
548 /**
549 * This is a wrapper for eAccelerator's shared memory functions.
550 *
551 * This is basically identical to the deceased Turck MMCache version,
552 * mostly because eAccelerator is based on Turck MMCache.
553 *
554 * @ingroup Cache
555 */
556 class eAccelBagOStuff extends BagOStuff {
557 public function get( $key ) {
558 $val = eaccelerator_get( $key );
559
560 if ( is_string( $val ) ) {
561 $val = unserialize( $val );
562 }
563
564 return $val;
565 }
566
567 public function set( $key, $value, $exptime = 0 ) {
568 eaccelerator_put( $key, serialize( $value ), $exptime );
569
570 return true;
571 }
572
573 public function delete( $key, $time = 0 ) {
574 eaccelerator_rm( $key );
575
576 return true;
577 }
578
579 public function lock( $key, $waitTimeout = 0 ) {
580 eaccelerator_lock( $key );
581
582 return true;
583 }
584
585 public function unlock( $key ) {
586 eaccelerator_unlock( $key );
587
588 return true;
589 }
590 }
591
592 /**
593 * Wrapper for XCache object caching functions; identical interface
594 * to the APC wrapper
595 *
596 * @ingroup Cache
597 */
598 class XCacheBagOStuff extends BagOStuff {
599 /**
600 * Get a value from the XCache object cache
601 *
602 * @param $key String: cache key
603 * @return mixed
604 */
605 public function get( $key ) {
606 $val = xcache_get( $key );
607
608 if ( is_string( $val ) ) {
609 $val = unserialize( $val );
610 }
611
612 return $val;
613 }
614
615 /**
616 * Store a value in the XCache object cache
617 *
618 * @param $key String: cache key
619 * @param $value Mixed: object to store
620 * @param $expire Int: expiration time
621 * @return bool
622 */
623 public function set( $key, $value, $expire = 0 ) {
624 xcache_set( $key, serialize( $value ), $expire );
625
626 return true;
627 }
628
629 /**
630 * Remove a value from the XCache object cache
631 *
632 * @param $key String: cache key
633 * @param $time Int: not used in this implementation
634 * @return bool
635 */
636 public function delete( $key, $time = 0 ) {
637 xcache_unset( $key );
638
639 return true;
640 }
641 }
642
643 /**
644 * Cache that uses DBA as a backend.
645 * Slow due to the need to constantly open and close the file to avoid holding
646 * writer locks. Intended for development use only, as a memcached workalike
647 * for systems that don't have it.
648 *
649 * @ingroup Cache
650 */
651 class DBABagOStuff extends BagOStuff {
652 var $mHandler, $mFile, $mReader, $mWriter, $mDisabled;
653
654 public function __construct( $dir = false ) {
655 global $wgDBAhandler;
656
657 if ( $dir === false ) {
658 global $wgTmpDirectory;
659 $dir = $wgTmpDirectory;
660 }
661
662 $this->mFile = "$dir/mw-cache-" . wfWikiID();
663 $this->mFile .= '.db';
664 wfDebug( __CLASS__ . ": using cache file {$this->mFile}\n" );
665 $this->mHandler = $wgDBAhandler;
666 }
667
668 /**
669 * Encode value and expiry for storage
670 */
671 function encode( $value, $expiry ) {
672 # Convert to absolute time
673 $expiry = $this->convertExpiry( $expiry );
674
675 return sprintf( '%010u', intval( $expiry ) ) . ' ' . serialize( $value );
676 }
677
678 /**
679 * @return list containing value first and expiry second
680 */
681 function decode( $blob ) {
682 if ( !is_string( $blob ) ) {
683 return array( null, 0 );
684 } else {
685 return array(
686 unserialize( substr( $blob, 11 ) ),
687 intval( substr( $blob, 0, 10 ) )
688 );
689 }
690 }
691
692 function getReader() {
693 if ( file_exists( $this->mFile ) ) {
694 $handle = dba_open( $this->mFile, 'rl', $this->mHandler );
695 } else {
696 $handle = $this->getWriter();
697 }
698
699 if ( !$handle ) {
700 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
701 }
702
703 return $handle;
704 }
705
706 function getWriter() {
707 $handle = dba_open( $this->mFile, 'cl', $this->mHandler );
708
709 if ( !$handle ) {
710 wfDebug( "Unable to open DBA cache file {$this->mFile}\n" );
711 }
712
713 return $handle;
714 }
715
716 function get( $key ) {
717 wfProfileIn( __METHOD__ );
718 wfDebug( __METHOD__ . "($key)\n" );
719
720 $handle = $this->getReader();
721 if ( !$handle ) {
722 return null;
723 }
724
725 $val = dba_fetch( $key, $handle );
726 list( $val, $expiry ) = $this->decode( $val );
727
728 # Must close ASAP because locks are held
729 dba_close( $handle );
730
731 if ( !is_null( $val ) && $expiry && $expiry < time() ) {
732 # Key is expired, delete it
733 $handle = $this->getWriter();
734 dba_delete( $key, $handle );
735 dba_close( $handle );
736 wfDebug( __METHOD__ . ": $key expired\n" );
737 $val = null;
738 }
739
740 wfProfileOut( __METHOD__ );
741 return $val;
742 }
743
744 function set( $key, $value, $exptime = 0 ) {
745 wfProfileIn( __METHOD__ );
746 wfDebug( __METHOD__ . "($key)\n" );
747
748 $blob = $this->encode( $value, $exptime );
749
750 $handle = $this->getWriter();
751 if ( !$handle ) {
752 return false;
753 }
754
755 $ret = dba_replace( $key, $blob, $handle );
756 dba_close( $handle );
757
758 wfProfileOut( __METHOD__ );
759 return $ret;
760 }
761
762 function delete( $key, $time = 0 ) {
763 wfProfileIn( __METHOD__ );
764 wfDebug( __METHOD__ . "($key)\n" );
765
766 $handle = $this->getWriter();
767 if ( !$handle ) {
768 return false;
769 }
770
771 $ret = dba_delete( $key, $handle );
772 dba_close( $handle );
773
774 wfProfileOut( __METHOD__ );
775 return $ret;
776 }
777
778 function add( $key, $value, $exptime = 0 ) {
779 wfProfileIn( __METHOD__ );
780
781 $blob = $this->encode( $value, $exptime );
782
783 $handle = $this->getWriter();
784
785 if ( !$handle ) {
786 return false;
787 }
788
789 $ret = dba_insert( $key, $blob, $handle );
790
791 # Insert failed, check to see if it failed due to an expired key
792 if ( !$ret ) {
793 list( $value, $expiry ) = $this->decode( dba_fetch( $key, $handle ) );
794
795 if ( $expiry < time() ) {
796 # Yes expired, delete and try again
797 dba_delete( $key, $handle );
798 $ret = dba_insert( $key, $blob, $handle );
799 # This time if it failed then it will be handled by the caller like any other race
800 }
801 }
802
803 dba_close( $handle );
804
805 wfProfileOut( __METHOD__ );
806 return $ret;
807 }
808
809 function keys() {
810 $reader = $this->getReader();
811 $k1 = dba_firstkey( $reader );
812
813 if ( !$k1 ) {
814 return array();
815 }
816
817 $result[] = $k1;
818
819 while ( $key = dba_nextkey( $reader ) ) {
820 $result[] = $key;
821 }
822
823 return $result;
824 }
825 }
826
827 /**
828 * Wrapper for WinCache object caching functions; identical interface
829 * to the APC wrapper
830 *
831 * @ingroup Cache
832 */
833 class WinCacheBagOStuff extends BagOStuff {
834
835 /**
836 * Get a value from the WinCache object cache
837 *
838 * @param $key String: cache key
839 * @return mixed
840 */
841 public function get( $key ) {
842 $val = wincache_ucache_get( $key );
843
844 if ( is_string( $val ) ) {
845 $val = unserialize( $val );
846 }
847
848 return $val;
849 }
850
851 /**
852 * Store a value in the WinCache object cache
853 *
854 * @param $key String: cache key
855 * @param $value Mixed: object to store
856 * @param $expire Int: expiration time
857 * @return bool
858 */
859 public function set( $key, $value, $expire = 0 ) {
860 wincache_ucache_set( $key, serialize( $value ), $expire );
861
862 return true;
863 }
864
865 /**
866 * Remove a value from the WinCache object cache
867 *
868 * @param $key String: cache key
869 * @param $time Int: not used in this implementation
870 * @return bool
871 */
872 public function delete( $key, $time = 0 ) {
873 wincache_ucache_delete( $key );
874
875 return true;
876 }
877
878 public function keys() {
879 $info = wincache_ucache_info();
880 $list = $info['ucache_entries'];
881 $keys = array();
882
883 foreach ( $list as $entry ) {
884 $keys[] = $entry['key_name'];
885 }
886
887 return $keys;
888 }
889 }