* fixed ipblocks.ipb_by_text field, removed default blank not null (fixed install...
[mediawiki.git] / includes / objectcache / MemcachedClient.php
blob6e17a9eff9eb3c3892d3393cb5508657f30e1bfc
1 <?php
2 /**
3 * +---------------------------------------------------------------------------+
4 * | memcached client, PHP |
5 * +---------------------------------------------------------------------------+
6 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
7 * | All rights reserved. |
8 * | |
9 * | Redistribution and use in source and binary forms, with or without |
10 * | modification, are permitted provided that the following conditions |
11 * | are met: |
12 * | |
13 * | 1. Redistributions of source code must retain the above copyright |
14 * | notice, this list of conditions and the following disclaimer. |
15 * | 2. Redistributions in binary form must reproduce the above copyright |
16 * | notice, this list of conditions and the following disclaimer in the |
17 * | documentation and/or other materials provided with the distribution. |
18 * | |
19 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
20 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
21 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
22 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
23 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
24 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
25 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
26 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
27 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
28 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
29 * +---------------------------------------------------------------------------+
30 * | Author: Ryan T. Dean <rtdean@cytherianage.net> |
31 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
32 * | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
33 * | client logic under 2-clause BSD license. |
34 * +---------------------------------------------------------------------------+
36 * @file
37 * $TCAnet$
40 /**
41 * This is the PHP client for memcached - a distributed memory cache daemon.
42 * More information is available at http://www.danga.com/memcached/
44 * Usage example:
46 * require_once 'memcached.php';
48 * $mc = new MWMemcached(array(
49 * 'servers' => array('127.0.0.1:10000',
50 * array('192.0.0.1:10010', 2),
51 * '127.0.0.1:10020'),
52 * 'debug' => false,
53 * 'compress_threshold' => 10240,
54 * 'persistent' => true));
56 * $mc->add('key', array('some', 'array'));
57 * $mc->replace('key', 'some random string');
58 * $val = $mc->get('key');
60 * @author Ryan T. Dean <rtdean@cytherianage.net>
61 * @version 0.1.2
64 // {{{ requirements
65 // }}}
67 // {{{ class MWMemcached
68 /**
69 * memcached client class implemented using (p)fsockopen()
71 * @author Ryan T. Dean <rtdean@cytherianage.net>
72 * @ingroup Cache
74 class MWMemcached {
75 // {{{ properties
76 // {{{ public
78 // {{{ constants
79 // {{{ flags
81 /**
82 * Flag: indicates data is serialized
84 const SERIALIZED = 1;
86 /**
87 * Flag: indicates data is compressed
89 const COMPRESSED = 2;
91 // }}}
93 /**
94 * Minimum savings to store data compressed
96 const COMPRESSION_SAVINGS = 0.20;
98 // }}}
102 * Command statistics
104 * @var array
105 * @access public
107 var $stats;
109 // }}}
110 // {{{ private
113 * Cached Sockets that are connected
115 * @var array
116 * @access private
118 var $_cache_sock;
121 * Current debug status; 0 - none to 9 - profiling
123 * @var boolean
124 * @access private
126 var $_debug;
129 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
131 * @var array
132 * @access private
134 var $_host_dead;
137 * Is compression available?
139 * @var boolean
140 * @access private
142 var $_have_zlib;
145 * Do we want to use compression?
147 * @var boolean
148 * @access private
150 var $_compress_enable;
153 * At how many bytes should we compress?
155 * @var integer
156 * @access private
158 var $_compress_threshold;
161 * Are we using persistent links?
163 * @var boolean
164 * @access private
166 var $_persistent;
169 * If only using one server; contains ip:port to connect to
171 * @var string
172 * @access private
174 var $_single_sock;
177 * Array containing ip:port or array(ip:port, weight)
179 * @var array
180 * @access private
182 var $_servers;
185 * Our bit buckets
187 * @var array
188 * @access private
190 var $_buckets;
193 * Total # of bit buckets we have
195 * @var integer
196 * @access private
198 var $_bucketcount;
201 * # of total servers we have
203 * @var integer
204 * @access private
206 var $_active;
209 * Stream timeout in seconds. Applies for example to fread()
211 * @var integer
212 * @access private
214 var $_timeout_seconds;
217 * Stream timeout in microseconds
219 * @var integer
220 * @access private
222 var $_timeout_microseconds;
225 * Connect timeout in seconds
227 var $_connect_timeout;
230 * Number of connection attempts for each server
232 var $_connect_attempts;
234 // }}}
235 // }}}
236 // {{{ methods
237 // {{{ public functions
238 // {{{ memcached()
241 * Memcache initializer
243 * @param $args Array Associative array of settings
245 * @return mixed
247 public function __construct( $args ) {
248 $this->set_servers( isset( $args['servers'] ) ? $args['servers'] : array() );
249 $this->_debug = isset( $args['debug'] ) ? $args['debug'] : false;
250 $this->stats = array();
251 $this->_compress_threshold = isset( $args['compress_threshold'] ) ? $args['compress_threshold'] : 0;
252 $this->_persistent = isset( $args['persistent'] ) ? $args['persistent'] : false;
253 $this->_compress_enable = true;
254 $this->_have_zlib = function_exists( 'gzcompress' );
256 $this->_cache_sock = array();
257 $this->_host_dead = array();
259 $this->_timeout_seconds = 0;
260 $this->_timeout_microseconds = isset( $args['timeout'] ) ? $args['timeout'] : 100000;
262 $this->_connect_timeout = isset( $args['connect_timeout'] ) ? $args['connect_timeout'] : 0.1;
263 $this->_connect_attempts = 2;
266 // }}}
267 // {{{ add()
270 * Adds a key/value to the memcache server if one isn't already set with
271 * that key
273 * @param $key String: key to set with data
274 * @param $val Mixed: value to store
275 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
276 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
277 * longer must be the timestamp of the time at which the mapping should expire. It
278 * is safe to use timestamps in all cases, regardless of exipration
279 * eg: strtotime("+3 hour")
281 * @return Boolean
283 public function add( $key, $val, $exp = 0 ) {
284 return $this->_set( 'add', $key, $val, $exp );
287 // }}}
288 // {{{ decr()
291 * Decrease a value stored on the memcache server
293 * @param $key String: key to decrease
294 * @param $amt Integer: (optional) amount to decrease
296 * @return Mixed: FALSE on failure, value on success
298 public function decr( $key, $amt = 1 ) {
299 return $this->_incrdecr( 'decr', $key, $amt );
302 // }}}
303 // {{{ delete()
306 * Deletes a key from the server, optionally after $time
308 * @param $key String: key to delete
309 * @param $time Integer: (optional) how long to wait before deleting
311 * @return Boolean: TRUE on success, FALSE on failure
313 public function delete( $key, $time = 0 ) {
314 if ( !$this->_active ) {
315 return false;
318 $sock = $this->get_sock( $key );
319 if ( !is_resource( $sock ) ) {
320 return false;
323 $key = is_array( $key ) ? $key[1] : $key;
325 if ( isset( $this->stats['delete'] ) ) {
326 $this->stats['delete']++;
327 } else {
328 $this->stats['delete'] = 1;
330 $cmd = "delete $key $time\r\n";
331 if( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
332 $this->_dead_sock( $sock );
333 return false;
335 $res = trim( fgets( $sock ) );
337 if ( $this->_debug ) {
338 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
341 if ( $res == "DELETED" ) {
342 return true;
344 return false;
347 public function lock( $key, $timeout = 0 ) {
348 /* stub */
349 return true;
352 public function unlock( $key ) {
353 /* stub */
354 return true;
357 // }}}
358 // {{{ disconnect_all()
361 * Disconnects all connected sockets
363 public function disconnect_all() {
364 foreach ( $this->_cache_sock as $sock ) {
365 fclose( $sock );
368 $this->_cache_sock = array();
371 // }}}
372 // {{{ enable_compress()
375 * Enable / Disable compression
377 * @param $enable Boolean: TRUE to enable, FALSE to disable
379 public function enable_compress( $enable ) {
380 $this->_compress_enable = $enable;
383 // }}}
384 // {{{ forget_dead_hosts()
387 * Forget about all of the dead hosts
389 public function forget_dead_hosts() {
390 $this->_host_dead = array();
393 // }}}
394 // {{{ get()
397 * Retrieves the value associated with the key from the memcache server
399 * @param $key Mixed: key to retrieve
401 * @return Mixed
403 public function get( $key ) {
404 wfProfileIn( __METHOD__ );
406 if ( $this->_debug ) {
407 $this->_debugprint( "get($key)\n" );
410 if ( !$this->_active ) {
411 wfProfileOut( __METHOD__ );
412 return false;
415 $sock = $this->get_sock( $key );
417 if ( !is_resource( $sock ) ) {
418 wfProfileOut( __METHOD__ );
419 return false;
422 if ( isset( $this->stats['get'] ) ) {
423 $this->stats['get']++;
424 } else {
425 $this->stats['get'] = 1;
428 $cmd = "get $key\r\n";
429 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
430 $this->_dead_sock( $sock );
431 wfProfileOut( __METHOD__ );
432 return false;
435 $val = array();
436 $this->_load_items( $sock, $val );
438 if ( $this->_debug ) {
439 foreach ( $val as $k => $v ) {
440 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
444 $value = false;
445 if ( isset( $val[$key] ) ) {
446 $value = $val[$key];
448 wfProfileOut( __METHOD__ );
449 return $value;
452 // }}}
453 // {{{ get_multi()
456 * Get multiple keys from the server(s)
458 * @param $keys Array: keys to retrieve
460 * @return Array
462 public function get_multi( $keys ) {
463 if ( !$this->_active ) {
464 return false;
467 if ( isset( $this->stats['get_multi'] ) ) {
468 $this->stats['get_multi']++;
469 } else {
470 $this->stats['get_multi'] = 1;
472 $sock_keys = array();
474 foreach ( $keys as $key ) {
475 $sock = $this->get_sock( $key );
476 if ( !is_resource( $sock ) ) {
477 continue;
479 $key = is_array( $key ) ? $key[1] : $key;
480 if ( !isset( $sock_keys[$sock] ) ) {
481 $sock_keys[$sock] = array();
482 $socks[] = $sock;
484 $sock_keys[$sock][] = $key;
487 // Send out the requests
488 foreach ( $socks as $sock ) {
489 $cmd = 'get';
490 foreach ( $sock_keys[$sock] as $key ) {
491 $cmd .= ' ' . $key;
493 $cmd .= "\r\n";
495 if ( $this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
496 $gather[] = $sock;
497 } else {
498 $this->_dead_sock( $sock );
502 // Parse responses
503 $val = array();
504 foreach ( $gather as $sock ) {
505 $this->_load_items( $sock, $val );
508 if ( $this->_debug ) {
509 foreach ( $val as $k => $v ) {
510 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
514 return $val;
517 // }}}
518 // {{{ incr()
521 * Increments $key (optionally) by $amt
523 * @param $key String: key to increment
524 * @param $amt Integer: (optional) amount to increment
526 * @return Integer: null if the key does not exist yet (this does NOT
527 * create new mappings if the key does not exist). If the key does
528 * exist, this returns the new value for that key.
530 public function incr( $key, $amt = 1 ) {
531 return $this->_incrdecr( 'incr', $key, $amt );
534 // }}}
535 // {{{ replace()
538 * Overwrites an existing value for key; only works if key is already set
540 * @param $key String: key to set value as
541 * @param $value Mixed: value to store
542 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
543 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
544 * longer must be the timestamp of the time at which the mapping should expire. It
545 * is safe to use timestamps in all cases, regardless of exipration
546 * eg: strtotime("+3 hour")
548 * @return Boolean
550 public function replace( $key, $value, $exp = 0 ) {
551 return $this->_set( 'replace', $key, $value, $exp );
554 // }}}
555 // {{{ run_command()
558 * Passes through $cmd to the memcache server connected by $sock; returns
559 * output as an array (null array if no output)
561 * NOTE: due to a possible bug in how PHP reads while using fgets(), each
562 * line may not be terminated by a \r\n. More specifically, my testing
563 * has shown that, on FreeBSD at least, each line is terminated only
564 * with a \n. This is with the PHP flag auto_detect_line_endings set
565 * to falase (the default).
567 * @param $sock Resource: socket to send command on
568 * @param $cmd String: command to run
570 * @return Array: output array
572 public function run_command( $sock, $cmd ) {
573 if ( !is_resource( $sock ) ) {
574 return array();
577 if ( !$this->_safe_fwrite( $sock, $cmd, strlen( $cmd ) ) ) {
578 return array();
581 while ( true ) {
582 $res = fgets( $sock );
583 $ret[] = $res;
584 if ( preg_match( '/^END/', $res ) ) {
585 break;
587 if ( strlen( $res ) == 0 ) {
588 break;
591 return $ret;
594 // }}}
595 // {{{ set()
598 * Unconditionally sets a key to a given value in the memcache. Returns true
599 * if set successfully.
601 * @param $key String: key to set value as
602 * @param $value Mixed: value to set
603 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
604 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
605 * longer must be the timestamp of the time at which the mapping should expire. It
606 * is safe to use timestamps in all cases, regardless of exipration
607 * eg: strtotime("+3 hour")
609 * @return Boolean: TRUE on success
611 public function set( $key, $value, $exp = 0 ) {
612 return $this->_set( 'set', $key, $value, $exp );
615 // }}}
616 // {{{ set_compress_threshold()
619 * Sets the compression threshold
621 * @param $thresh Integer: threshold to compress if larger than
623 public function set_compress_threshold( $thresh ) {
624 $this->_compress_threshold = $thresh;
627 // }}}
628 // {{{ set_debug()
631 * Sets the debug flag
633 * @param $dbg Boolean: TRUE for debugging, FALSE otherwise
635 * @see MWMemcached::__construct
637 public function set_debug( $dbg ) {
638 $this->_debug = $dbg;
641 // }}}
642 // {{{ set_servers()
645 * Sets the server list to distribute key gets and puts between
647 * @param $list Array of servers to connect to
649 * @see MWMemcached::__construct()
651 public function set_servers( $list ) {
652 $this->_servers = $list;
653 $this->_active = count( $list );
654 $this->_buckets = null;
655 $this->_bucketcount = 0;
657 $this->_single_sock = null;
658 if ( $this->_active == 1 ) {
659 $this->_single_sock = $this->_servers[0];
664 * Sets the timeout for new connections
666 * @param $seconds Integer: number of seconds
667 * @param $microseconds Integer: number of microseconds
669 public function set_timeout( $seconds, $microseconds ) {
670 $this->_timeout_seconds = $seconds;
671 $this->_timeout_microseconds = $microseconds;
674 // }}}
675 // }}}
676 // {{{ private methods
677 // {{{ _close_sock()
680 * Close the specified socket
682 * @param $sock String: socket to close
684 * @access private
686 function _close_sock( $sock ) {
687 $host = array_search( $sock, $this->_cache_sock );
688 fclose( $this->_cache_sock[$host] );
689 unset( $this->_cache_sock[$host] );
692 // }}}
693 // {{{ _connect_sock()
696 * Connects $sock to $host, timing out after $timeout
698 * @param $sock Integer: socket to connect
699 * @param $host String: Host:IP to connect to
701 * @return boolean
702 * @access private
704 function _connect_sock( &$sock, $host ) {
705 list( $ip, $port ) = explode( ':', $host );
706 $sock = false;
707 $timeout = $this->_connect_timeout;
708 $errno = $errstr = null;
709 for( $i = 0; !$sock && $i < $this->_connect_attempts; $i++ ) {
710 wfSuppressWarnings();
711 if ( $this->_persistent == 1 ) {
712 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
713 } else {
714 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
716 wfRestoreWarnings();
718 if ( !$sock ) {
719 if ( $this->_debug ) {
720 $this->_debugprint( "Error connecting to $host: $errstr\n" );
722 return false;
725 // Initialise timeout
726 stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
728 return true;
731 // }}}
732 // {{{ _dead_sock()
735 * Marks a host as dead until 30-40 seconds in the future
737 * @param $sock String: socket to mark as dead
739 * @access private
741 function _dead_sock( $sock ) {
742 $host = array_search( $sock, $this->_cache_sock );
743 $this->_dead_host( $host );
746 function _dead_host( $host ) {
747 $parts = explode( ':', $host );
748 $ip = $parts[0];
749 $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
750 $this->_host_dead[$host] = $this->_host_dead[$ip];
751 unset( $this->_cache_sock[$host] );
754 // }}}
755 // {{{ get_sock()
758 * get_sock
760 * @param $key String: key to retrieve value for;
762 * @return Mixed: resource on success, false on failure
763 * @access private
765 function get_sock( $key ) {
766 if ( !$this->_active ) {
767 return false;
770 if ( $this->_single_sock !== null ) {
771 $this->_flush_read_buffer( $this->_single_sock );
772 return $this->sock_to_host( $this->_single_sock );
775 $hv = is_array( $key ) ? intval( $key[0] ) : $this->_hashfunc( $key );
777 if ( $this->_buckets === null ) {
778 foreach ( $this->_servers as $v ) {
779 if ( is_array( $v ) ) {
780 for( $i = 0; $i < $v[1]; $i++ ) {
781 $bu[] = $v[0];
783 } else {
784 $bu[] = $v;
787 $this->_buckets = $bu;
788 $this->_bucketcount = count( $bu );
791 $realkey = is_array( $key ) ? $key[1] : $key;
792 for( $tries = 0; $tries < 20; $tries++ ) {
793 $host = $this->_buckets[$hv % $this->_bucketcount];
794 $sock = $this->sock_to_host( $host );
795 if ( is_resource( $sock ) ) {
796 $this->_flush_read_buffer( $sock );
797 return $sock;
799 $hv = $this->_hashfunc( $hv . $realkey );
802 return false;
805 // }}}
806 // {{{ _hashfunc()
809 * Creates a hash integer based on the $key
811 * @param $key String: key to hash
813 * @return Integer: hash value
814 * @access private
816 function _hashfunc( $key ) {
817 # Hash function must on [0,0x7ffffff]
818 # We take the first 31 bits of the MD5 hash, which unlike the hash
819 # function used in a previous version of this client, works
820 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
823 // }}}
824 // {{{ _incrdecr()
827 * Perform increment/decriment on $key
829 * @param $cmd String: command to perform
830 * @param $key String: key to perform it on
831 * @param $amt Integer: amount to adjust
833 * @return Integer: new value of $key
834 * @access private
836 function _incrdecr( $cmd, $key, $amt = 1 ) {
837 if ( !$this->_active ) {
838 return null;
841 $sock = $this->get_sock( $key );
842 if ( !is_resource( $sock ) ) {
843 return null;
846 $key = is_array( $key ) ? $key[1] : $key;
847 if ( isset( $this->stats[$cmd] ) ) {
848 $this->stats[$cmd]++;
849 } else {
850 $this->stats[$cmd] = 1;
852 if ( !$this->_safe_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
853 return $this->_dead_sock( $sock );
856 $line = fgets( $sock );
857 $match = array();
858 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
859 return null;
861 return $match[1];
864 // }}}
865 // {{{ _load_items()
868 * Load items into $ret from $sock
870 * @param $sock Resource: socket to read from
871 * @param $ret Array: returned values
873 * @access private
875 function _load_items( $sock, &$ret ) {
876 while ( 1 ) {
877 $decl = fgets( $sock );
878 if ( $decl == "END\r\n" ) {
879 return true;
880 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)\r\n$/', $decl, $match ) ) {
881 list( $rkey, $flags, $len ) = array( $match[1], $match[2], $match[3] );
882 $bneed = $len + 2;
883 $offset = 0;
885 while ( $bneed > 0 ) {
886 $data = fread( $sock, $bneed );
887 $n = strlen( $data );
888 if ( $n == 0 ) {
889 break;
891 $offset += $n;
892 $bneed -= $n;
893 if ( isset( $ret[$rkey] ) ) {
894 $ret[$rkey] .= $data;
895 } else {
896 $ret[$rkey] = $data;
900 if ( $offset != $len + 2 ) {
901 // Something is borked!
902 if ( $this->_debug ) {
903 $this->_debugprint( sprintf( "Something is borked! key %s expecting %d got %d length\n", $rkey, $len + 2, $offset ) );
906 unset( $ret[$rkey] );
907 $this->_close_sock( $sock );
908 return false;
911 if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
912 $ret[$rkey] = gzuncompress( $ret[$rkey] );
915 $ret[$rkey] = rtrim( $ret[$rkey] );
917 if ( $flags & self::SERIALIZED ) {
918 $ret[$rkey] = unserialize( $ret[$rkey] );
921 } else {
922 $this->_debugprint( "Error parsing memcached response\n" );
923 return 0;
928 // }}}
929 // {{{ _set()
932 * Performs the requested storage operation to the memcache server
934 * @param $cmd String: command to perform
935 * @param $key String: key to act on
936 * @param $val Mixed: what we need to store
937 * @param $exp Integer: (optional) Expiration time. This can be a number of seconds
938 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
939 * longer must be the timestamp of the time at which the mapping should expire. It
940 * is safe to use timestamps in all cases, regardless of exipration
941 * eg: strtotime("+3 hour")
943 * @return Boolean
944 * @access private
946 function _set( $cmd, $key, $val, $exp ) {
947 if ( !$this->_active ) {
948 return false;
951 $sock = $this->get_sock( $key );
952 if ( !is_resource( $sock ) ) {
953 return false;
956 if ( isset( $this->stats[$cmd] ) ) {
957 $this->stats[$cmd]++;
958 } else {
959 $this->stats[$cmd] = 1;
962 // TTLs higher than 30 days will be detected as absolute TTLs
963 // (UNIX timestamps), and will result in the cache entry being
964 // discarded immediately because the expiry is in the past.
965 // Clamp expiries >30d at 30d, unless they're >=1e9 in which
966 // case they are likely to really be absolute (1e9 = 2011-09-09)
967 if ( $exp > 2592000 && $exp < 1000000000 ) {
968 $exp = 2592000;
971 $flags = 0;
973 if ( !is_scalar( $val ) ) {
974 $val = serialize( $val );
975 $flags |= self::SERIALIZED;
976 if ( $this->_debug ) {
977 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
981 $len = strlen( $val );
983 if ( $this->_have_zlib && $this->_compress_enable &&
984 $this->_compress_threshold && $len >= $this->_compress_threshold )
986 $c_val = gzcompress( $val, 9 );
987 $c_len = strlen( $c_val );
989 if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
990 if ( $this->_debug ) {
991 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
993 $val = $c_val;
994 $len = $c_len;
995 $flags |= self::COMPRESSED;
998 if ( !$this->_safe_fwrite( $sock, "$cmd $key $flags $exp $len\r\n$val\r\n" ) ) {
999 return $this->_dead_sock( $sock );
1002 $line = trim( fgets( $sock ) );
1004 if ( $this->_debug ) {
1005 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
1007 if ( $line == "STORED" ) {
1008 return true;
1010 return false;
1013 // }}}
1014 // {{{ sock_to_host()
1017 * Returns the socket for the host
1019 * @param $host String: Host:IP to get socket for
1021 * @return Mixed: IO Stream or false
1022 * @access private
1024 function sock_to_host( $host ) {
1025 if ( isset( $this->_cache_sock[$host] ) ) {
1026 return $this->_cache_sock[$host];
1029 $sock = null;
1030 $now = time();
1031 list( $ip, /* $port */) = explode( ':', $host );
1032 if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1033 isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1035 return null;
1038 if ( !$this->_connect_sock( $sock, $host ) ) {
1039 return $this->_dead_host( $host );
1042 // Do not buffer writes
1043 stream_set_write_buffer( $sock, 0 );
1045 $this->_cache_sock[$host] = $sock;
1047 return $this->_cache_sock[$host];
1050 function _debugprint( $str ) {
1051 print( $str );
1055 * Write to a stream, timing out after the correct amount of time
1057 * @return Boolean: false on failure, true on success
1060 function _safe_fwrite( $f, $buf, $len = false ) {
1061 stream_set_blocking( $f, 0 );
1063 if ( $len === false ) {
1064 wfDebug( "Writing " . strlen( $buf ) . " bytes\n" );
1065 $bytesWritten = fwrite( $f, $buf );
1066 } else {
1067 wfDebug( "Writing $len bytes\n" );
1068 $bytesWritten = fwrite( $f, $buf, $len );
1070 $n = stream_select( $r = null, $w = array( $f ), $e = null, 10, 0 );
1071 # $this->_timeout_seconds, $this->_timeout_microseconds );
1073 wfDebug( "stream_select returned $n\n" );
1074 stream_set_blocking( $f, 1 );
1075 return $n == 1;
1076 return $bytesWritten;
1080 * Original behaviour
1082 function _safe_fwrite( $f, $buf, $len = false ) {
1083 if ( $len === false ) {
1084 $bytesWritten = fwrite( $f, $buf );
1085 } else {
1086 $bytesWritten = fwrite( $f, $buf, $len );
1088 return $bytesWritten;
1092 * Flush the read buffer of a stream
1094 function _flush_read_buffer( $f ) {
1095 if ( !is_resource( $f ) ) {
1096 return;
1098 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1099 while ( $n == 1 && !feof( $f ) ) {
1100 fread( $f, 1024 );
1101 $n = stream_select( $r = array( $f ), $w = null, $e = null, 0, 0 );
1105 // }}}
1106 // }}}
1107 // }}}
1110 // vim: sts=3 sw=3 et
1112 // }}}
1114 class MemCachedClientforWiki extends MWMemcached {
1115 function _debugprint( $text ) {
1116 wfDebug( "memcached: $text" );