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