2 // @codingStandardsIgnoreFile It's an external lib and it isn't. Let's not bother.
4 * Memcached client for PHP.
6 * +---------------------------------------------------------------------------+
7 * | memcached client, PHP |
8 * +---------------------------------------------------------------------------+
9 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
10 * | All rights reserved. |
12 * | Redistribution and use in source and binary forms, with or without |
13 * | modification, are permitted provided that the following conditions |
16 * | 1. Redistributions of source code must retain the above copyright |
17 * | notice, this list of conditions and the following disclaimer. |
18 * | 2. Redistributions in binary form must reproduce the above copyright |
19 * | notice, this list of conditions and the following disclaimer in the |
20 * | documentation and/or other materials provided with the distribution. |
22 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
23 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
24 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
25 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
26 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
27 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
28 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
29 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
30 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
31 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
32 * +---------------------------------------------------------------------------+
33 * | Author: Ryan T. Dean <rtdean@cytherianage.net> |
34 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
35 * | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
36 * | client logic under 2-clause BSD license. |
37 * +---------------------------------------------------------------------------+
44 * This is the PHP client for memcached - a distributed memory cache daemon.
45 * More information is available at http://www.danga.com/memcached/
49 * require_once 'memcached.php';
51 * $mc = new MWMemcached(array(
52 * 'servers' => array('127.0.0.1:10000',
53 * array('192.0.0.1:10010', 2),
56 * 'compress_threshold' => 10240,
57 * 'persistent' => true));
59 * $mc->add( 'key', array( 'some', 'array' ) );
60 * $mc->replace( 'key', 'some random string' );
61 * $val = $mc->get( 'key' );
63 * @author Ryan T. Dean <rtdean@cytherianage.net>
67 use Psr\Log\LoggerInterface
;
68 use Psr\Log\NullLogger
;
73 // {{{ class MWMemcached
75 * memcached client class implemented using (p)fsockopen()
77 * @author Ryan T. Dean <rtdean@cytherianage.net>
88 * Flag: indicates data is serialized
93 * Flag: indicates data is compressed
98 * Flag: indicates data is an integer
105 * Minimum savings to store data compressed
107 const COMPRESSION_SAVINGS
= 0.20;
123 * Cached Sockets that are connected
131 * Current debug status; 0 - none to 9 - profiling
139 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
147 * Is compression available?
155 * Do we want to use compression?
160 public $_compress_enable;
163 * At how many bytes should we compress?
168 public $_compress_threshold;
171 * Are we using persistent links?
179 * If only using one server; contains ip:port to connect to
184 public $_single_sock;
187 * Array containing ip:port or array(ip:port, weight)
203 * Total # of bit buckets we have
208 public $_bucketcount;
211 * # of total servers we have
219 * Stream timeout in seconds. Applies for example to fread()
224 public $_timeout_seconds;
227 * Stream timeout in microseconds
232 public $_timeout_microseconds;
235 * Connect timeout in seconds
237 public $_connect_timeout;
240 * Number of connection attempts for each server
242 public $_connect_attempts;
245 * @var LoggerInterface
252 // {{{ public functions
256 * Memcache initializer
258 * @param array $args Associative array of settings
262 public function __construct( $args ) {
263 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
264 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
265 $this->stats
= array();
266 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
267 $this->_persistent
= isset( $args['persistent'] ) ?
$args['persistent'] : false;
268 $this->_compress_enable
= true;
269 $this->_have_zlib
= function_exists( 'gzcompress' );
271 $this->_cache_sock
= array();
272 $this->_host_dead
= array();
274 $this->_timeout_seconds
= 0;
275 $this->_timeout_microseconds
= isset( $args['timeout'] ) ?
$args['timeout'] : 500000;
277 $this->_connect_timeout
= isset( $args['connect_timeout'] ) ?
$args['connect_timeout'] : 0.1;
278 $this->_connect_attempts
= 2;
280 $this->_logger
= isset( $args['logger'] ) ?
$args['logger'] : new NullLogger();
287 * Adds a key/value to the memcache server if one isn't already set with
290 * @param string $key Key to set with data
291 * @param mixed $val Value to store
292 * @param int $exp (optional) Expiration time. This can be a number of seconds
293 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
294 * longer must be the timestamp of the time at which the mapping should expire. It
295 * is safe to use timestamps in all cases, regardless of expiration
296 * eg: strtotime("+3 hour")
300 public function add( $key, $val, $exp = 0 ) {
301 return $this->_set( 'add', $key, $val, $exp );
308 * Decrease a value stored on the memcache server
310 * @param string $key Key to decrease
311 * @param int $amt (optional) amount to decrease
313 * @return mixed False on failure, value on success
315 public function decr( $key, $amt = 1 ) {
316 return $this->_incrdecr( 'decr', $key, $amt );
323 * Deletes a key from the server, optionally after $time
325 * @param string $key Key to delete
326 * @param int $time (optional) how long to wait before deleting
328 * @return bool True on success, false on failure
330 public function delete( $key, $time = 0 ) {
331 if ( !$this->_active
) {
335 $sock = $this->get_sock( $key );
336 if ( !is_resource( $sock ) ) {
340 $key = is_array( $key ) ?
$key[1] : $key;
342 if ( isset( $this->stats
['delete'] ) ) {
343 $this->stats
['delete']++
;
345 $this->stats
['delete'] = 1;
347 $cmd = "delete $key $time\r\n";
348 if ( !$this->_fwrite( $sock, $cmd ) ) {
351 $res = $this->_fgets( $sock );
353 if ( $this->_debug
) {
354 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
357 if ( $res == "DELETED" ||
$res == "NOT_FOUND" ) {
366 * @param int $timeout
369 public function lock( $key, $timeout = 0 ) {
378 public function unlock( $key ) {
384 // {{{ disconnect_all()
387 * Disconnects all connected sockets
389 public function disconnect_all() {
390 foreach ( $this->_cache_sock
as $sock ) {
394 $this->_cache_sock
= array();
398 // {{{ enable_compress()
401 * Enable / Disable compression
403 * @param bool $enable True to enable, false to disable
405 public function enable_compress( $enable ) {
406 $this->_compress_enable
= $enable;
410 // {{{ forget_dead_hosts()
413 * Forget about all of the dead hosts
415 public function forget_dead_hosts() {
416 $this->_host_dead
= array();
423 * Retrieves the value associated with the key from the memcache server
425 * @param array|string $key key to retrieve
426 * @param float $casToken [optional]
430 public function get( $key, &$casToken = null ) {
432 if ( $this->_debug
) {
433 $this->_debugprint( "get($key)\n" );
436 if ( !is_array( $key ) && strval( $key ) === '' ) {
437 $this->_debugprint( "Skipping key which equals to an empty string" );
441 if ( !$this->_active
) {
445 $sock = $this->get_sock( $key );
447 if ( !is_resource( $sock ) ) {
451 $key = is_array( $key ) ?
$key[1] : $key;
452 if ( isset( $this->stats
['get'] ) ) {
453 $this->stats
['get']++
;
455 $this->stats
['get'] = 1;
458 $cmd = "gets $key\r\n";
459 if ( !$this->_fwrite( $sock, $cmd ) ) {
464 $this->_load_items( $sock, $val, $casToken );
466 if ( $this->_debug
) {
467 foreach ( $val as $k => $v ) {
468 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
473 if ( isset( $val[$key] ) ) {
483 * Get multiple keys from the server(s)
485 * @param array $keys Keys to retrieve
489 public function get_multi( $keys ) {
490 if ( !$this->_active
) {
494 if ( isset( $this->stats
['get_multi'] ) ) {
495 $this->stats
['get_multi']++
;
497 $this->stats
['get_multi'] = 1;
499 $sock_keys = array();
501 foreach ( $keys as $key ) {
502 $sock = $this->get_sock( $key );
503 if ( !is_resource( $sock ) ) {
506 $key = is_array( $key ) ?
$key[1] : $key;
507 if ( !isset( $sock_keys[$sock] ) ) {
508 $sock_keys[intval( $sock )] = array();
511 $sock_keys[intval( $sock )][] = $key;
515 // Send out the requests
516 foreach ( $socks as $sock ) {
518 foreach ( $sock_keys[intval( $sock )] as $key ) {
523 if ( $this->_fwrite( $sock, $cmd ) ) {
530 foreach ( $gather as $sock ) {
531 $this->_load_items( $sock, $val, $casToken );
534 if ( $this->_debug
) {
535 foreach ( $val as $k => $v ) {
536 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
547 * Increments $key (optionally) by $amt
549 * @param string $key Key to increment
550 * @param int $amt (optional) amount to increment
552 * @return int|null Null if the key does not exist yet (this does NOT
553 * create new mappings if the key does not exist). If the key does
554 * exist, this returns the new value for that key.
556 public function incr( $key, $amt = 1 ) {
557 return $this->_incrdecr( 'incr', $key, $amt );
564 * Overwrites an existing value for key; only works if key is already set
566 * @param string $key Key to set value as
567 * @param mixed $value Value to store
568 * @param int $exp (optional) Expiration time. This can be a number of seconds
569 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
570 * longer must be the timestamp of the time at which the mapping should expire. It
571 * is safe to use timestamps in all cases, regardless of exipration
572 * eg: strtotime("+3 hour")
576 public function replace( $key, $value, $exp = 0 ) {
577 return $this->_set( 'replace', $key, $value, $exp );
584 * Passes through $cmd to the memcache server connected by $sock; returns
585 * output as an array (null array if no output)
587 * @param Resource $sock Socket to send command on
588 * @param string $cmd Command to run
590 * @return array Output array
592 public function run_command( $sock, $cmd ) {
593 if ( !is_resource( $sock ) ) {
597 if ( !$this->_fwrite( $sock, $cmd ) ) {
603 $res = $this->_fgets( $sock );
605 if ( preg_match( '/^END/', $res ) ) {
608 if ( strlen( $res ) == 0 ) {
619 * Unconditionally sets a key to a given value in the memcache. Returns true
620 * if set successfully.
622 * @param string $key Key to set value as
623 * @param mixed $value Value to set
624 * @param int $exp (optional) Expiration time. This can be a number of seconds
625 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
626 * longer must be the timestamp of the time at which the mapping should expire. It
627 * is safe to use timestamps in all cases, regardless of exipration
628 * eg: strtotime("+3 hour")
630 * @return bool True on success
632 public function set( $key, $value, $exp = 0 ) {
633 return $this->_set( 'set', $key, $value, $exp );
640 * Sets a key to a given value in the memcache if the current value still corresponds
641 * to a known, given value. Returns true if set successfully.
643 * @param float $casToken Current known value
644 * @param string $key Key to set value as
645 * @param mixed $value Value to set
646 * @param int $exp (optional) Expiration time. This can be a number of seconds
647 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
648 * longer must be the timestamp of the time at which the mapping should expire. It
649 * is safe to use timestamps in all cases, regardless of exipration
650 * eg: strtotime("+3 hour")
652 * @return bool True on success
654 public function cas( $casToken, $key, $value, $exp = 0 ) {
655 return $this->_set( 'cas', $key, $value, $exp, $casToken );
659 // {{{ set_compress_threshold()
662 * Sets the compression threshold
664 * @param int $thresh Threshold to compress if larger than
666 public function set_compress_threshold( $thresh ) {
667 $this->_compress_threshold
= $thresh;
674 * Sets the debug flag
676 * @param bool $dbg True for debugging, false otherwise
678 * @see MWMemcached::__construct
680 public function set_debug( $dbg ) {
681 $this->_debug
= $dbg;
688 * Sets the server list to distribute key gets and puts between
690 * @param array $list Array of servers to connect to
692 * @see MWMemcached::__construct()
694 public function set_servers( $list ) {
695 $this->_servers
= $list;
696 $this->_active
= count( $list );
697 $this->_buckets
= null;
698 $this->_bucketcount
= 0;
700 $this->_single_sock
= null;
701 if ( $this->_active
== 1 ) {
702 $this->_single_sock
= $this->_servers
[0];
707 * Sets the timeout for new connections
709 * @param int $seconds Number of seconds
710 * @param int $microseconds Number of microseconds
712 public function set_timeout( $seconds, $microseconds ) {
713 $this->_timeout_seconds
= $seconds;
714 $this->_timeout_microseconds
= $microseconds;
719 // {{{ private methods
723 * Close the specified socket
725 * @param string $sock Socket to close
729 function _close_sock( $sock ) {
730 $host = array_search( $sock, $this->_cache_sock
);
731 fclose( $this->_cache_sock
[$host] );
732 unset( $this->_cache_sock
[$host] );
736 // {{{ _connect_sock()
739 * Connects $sock to $host, timing out after $timeout
741 * @param int $sock Socket to connect
742 * @param string $host Host:IP to connect to
747 function _connect_sock( &$sock, $host ) {
748 list( $ip, $port ) = preg_split( '/:(?=\d)/', $host );
750 $timeout = $this->_connect_timeout
;
751 $errno = $errstr = null;
752 for ( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
753 MediaWiki\
suppressWarnings();
754 if ( $this->_persistent
== 1 ) {
755 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
757 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
759 MediaWiki\restoreWarnings
();
762 $this->_error_log( "Error connecting to $host: $errstr\n" );
763 $this->_dead_host( $host );
767 // Initialise timeout
768 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
770 // If the connection was persistent, flush the read buffer in case there
771 // was a previous incomplete request on this connection
772 if ( $this->_persistent
) {
773 $this->_flush_read_buffer( $sock );
782 * Marks a host as dead until 30-40 seconds in the future
784 * @param string $sock Socket to mark as dead
788 function _dead_sock( $sock ) {
789 $host = array_search( $sock, $this->_cache_sock
);
790 $this->_dead_host( $host );
794 * @param string $host
796 function _dead_host( $host ) {
797 $parts = explode( ':', $host );
799 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
800 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
801 unset( $this->_cache_sock
[$host] );
810 * @param string $key Key to retrieve value for;
812 * @return Resource|bool Resource on success, false on failure
815 function get_sock( $key ) {
816 if ( !$this->_active
) {
820 if ( $this->_single_sock
!== null ) {
821 return $this->sock_to_host( $this->_single_sock
);
824 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
825 if ( $this->_buckets
=== null ) {
827 foreach ( $this->_servers
as $v ) {
828 if ( is_array( $v ) ) {
829 for ( $i = 0; $i < $v[1]; $i++
) {
836 $this->_buckets
= $bu;
837 $this->_bucketcount
= count( $bu );
840 $realkey = is_array( $key ) ?
$key[1] : $key;
841 for ( $tries = 0; $tries < 20; $tries++
) {
842 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
843 $sock = $this->sock_to_host( $host );
844 if ( is_resource( $sock ) ) {
847 $hv = $this->_hashfunc( $hv . $realkey );
857 * Creates a hash integer based on the $key
859 * @param string $key Key to hash
861 * @return int Hash value
864 function _hashfunc( $key ) {
865 # Hash function must be in [0,0x7ffffff]
866 # We take the first 31 bits of the MD5 hash, which unlike the hash
867 # function used in a previous version of this client, works
868 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
875 * Perform increment/decriment on $key
877 * @param string $cmd Command to perform
878 * @param string|array $key Key to perform it on
879 * @param int $amt Amount to adjust
881 * @return int New value of $key
884 function _incrdecr( $cmd, $key, $amt = 1 ) {
885 if ( !$this->_active
) {
889 $sock = $this->get_sock( $key );
890 if ( !is_resource( $sock ) ) {
894 $key = is_array( $key ) ?
$key[1] : $key;
895 if ( isset( $this->stats
[$cmd] ) ) {
896 $this->stats
[$cmd]++
;
898 $this->stats
[$cmd] = 1;
900 if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
904 $line = $this->_fgets( $sock );
906 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
916 * Load items into $ret from $sock
918 * @param Resource $sock Socket to read from
919 * @param array $ret returned values
920 * @param float $casToken [optional]
921 * @return bool True for success, false for failure
925 function _load_items( $sock, &$ret, &$casToken = null ) {
929 $decl = $this->_fgets( $sock );
931 if ( $decl === false ) {
933 * If nothing can be read, something is wrong because we know exactly when
934 * to stop reading (right after "END") and we return right after that.
937 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
939 * Read all data returned. This can be either one or multiple values.
940 * Save all that data (in an array) to be processed later: we'll first
941 * want to continue reading until "END" before doing anything else,
942 * to make sure that we don't leave our client in a state where it's
943 * output is not yet fully read.
949 $match[4], // casToken
950 $this->_fread( $sock, $match[3] +
2 ), // data
952 } elseif ( $decl == "END" ) {
953 if ( count( $results ) == 0 ) {
958 * All data has been read, time to process the data and build
959 * meaningful return values.
961 foreach ( $results as $vars ) {
962 list( $rkey, $flags, $len, $casToken, $data ) = $vars;
964 if ( $data === false ||
substr( $data, -2 ) !== "\r\n" ) {
965 $this->_handle_error( $sock,
966 'line ending missing from data block from $1' );
969 $data = substr( $data, 0, -2 );
972 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
973 $ret[$rkey] = gzuncompress( $ret[$rkey] );
977 * This unserialize is the exact reason that we only want to
978 * process data after having read until "END" (instead of doing
979 * this right away): "unserialize" can trigger outside code:
980 * in the event that $ret[$rkey] is a serialized object,
981 * unserializing it will trigger __wakeup() if present. If that
982 * function attempted to read from memcached (while we did not
983 * yet read "END"), these 2 calls would collide.
985 if ( $flags & self
::SERIALIZED
) {
986 $ret[$rkey] = unserialize( $ret[$rkey] );
987 } elseif ( $flags & self
::INTVAL
) {
988 $ret[$rkey] = intval( $ret[$rkey] );
994 $this->_handle_error( $sock, 'Error parsing response from $1' );
1004 * Performs the requested storage operation to the memcache server
1006 * @param string $cmd Command to perform
1007 * @param string $key Key to act on
1008 * @param mixed $val What we need to store
1009 * @param int $exp (optional) Expiration time. This can be a number of seconds
1010 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
1011 * longer must be the timestamp of the time at which the mapping should expire. It
1012 * is safe to use timestamps in all cases, regardless of exipration
1013 * eg: strtotime("+3 hour")
1014 * @param float $casToken [optional]
1019 function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1020 if ( !$this->_active
) {
1024 $sock = $this->get_sock( $key );
1025 if ( !is_resource( $sock ) ) {
1029 if ( isset( $this->stats
[$cmd] ) ) {
1030 $this->stats
[$cmd]++
;
1032 $this->stats
[$cmd] = 1;
1037 if ( is_int( $val ) ) {
1038 $flags |
= self
::INTVAL
;
1039 } elseif ( !is_scalar( $val ) ) {
1040 $val = serialize( $val );
1041 $flags |
= self
::SERIALIZED
;
1042 if ( $this->_debug
) {
1043 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
1047 $len = strlen( $val );
1049 if ( $this->_have_zlib
&& $this->_compress_enable
1050 && $this->_compress_threshold
&& $len >= $this->_compress_threshold
1052 $c_val = gzcompress( $val, 9 );
1053 $c_len = strlen( $c_val );
1055 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
1056 if ( $this->_debug
) {
1057 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
1061 $flags |
= self
::COMPRESSED
;
1065 $command = "$cmd $key $flags $exp $len";
1067 $command .= " $casToken";
1070 if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1074 $line = $this->_fgets( $sock );
1076 if ( $this->_debug
) {
1077 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
1079 if ( $line == "STORED" ) {
1086 // {{{ sock_to_host()
1089 * Returns the socket for the host
1091 * @param string $host Host:IP to get socket for
1093 * @return Resource|bool IO Stream or false
1096 function sock_to_host( $host ) {
1097 if ( isset( $this->_cache_sock
[$host] ) ) {
1098 return $this->_cache_sock
[$host];
1103 list( $ip, /* $port */) = explode( ':', $host );
1104 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
1105 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
1110 if ( !$this->_connect_sock( $sock, $host ) ) {
1114 // Do not buffer writes
1115 stream_set_write_buffer( $sock, 0 );
1117 $this->_cache_sock
[$host] = $sock;
1119 return $this->_cache_sock
[$host];
1123 * @param string $text
1125 function _debugprint( $text ) {
1126 $this->_logger
->debug( $text );
1130 * @param string $text
1132 function _error_log( $text ) {
1133 $this->_logger
->error( "Memcached error: $text" );
1137 * Write to a stream. If there is an error, mark the socket dead.
1139 * @param Resource $sock The socket
1140 * @param string $buf The string to write
1141 * @return bool True on success, false on failure
1143 function _fwrite( $sock, $buf ) {
1145 $bufSize = strlen( $buf );
1146 while ( $bytesWritten < $bufSize ) {
1147 $result = fwrite( $sock, $buf );
1148 $data = stream_get_meta_data( $sock );
1149 if ( $data['timed_out'] ) {
1150 $this->_handle_error( $sock, 'timeout writing to $1' );
1153 // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1154 if ( $result === false ||
$result === 0 ) {
1155 $this->_handle_error( $sock, 'error writing to $1' );
1158 $bytesWritten +
= $result;
1165 * Handle an I/O error. Mark the socket dead and log an error.
1167 * @param Resource $sock
1168 * @param string $msg
1170 function _handle_error( $sock, $msg ) {
1171 $peer = stream_socket_get_name( $sock, true /** remote **/ );
1172 if ( strval( $peer ) === '' ) {
1173 $peer = array_search( $sock, $this->_cache_sock
);
1174 if ( $peer === false ) {
1175 $peer = '[unknown host]';
1178 $msg = str_replace( '$1', $peer, $msg );
1179 $this->_error_log( "$msg\n" );
1180 $this->_dead_sock( $sock );
1184 * Read the specified number of bytes from a stream. If there is an error,
1185 * mark the socket dead.
1187 * @param Resource $sock The socket
1188 * @param int $len The number of bytes to read
1189 * @return string|bool The string on success, false on failure.
1191 function _fread( $sock, $len ) {
1193 while ( $len > 0 ) {
1194 $result = fread( $sock, $len );
1195 $data = stream_get_meta_data( $sock );
1196 if ( $data['timed_out'] ) {
1197 $this->_handle_error( $sock, 'timeout reading from $1' );
1200 if ( $result === false ) {
1201 $this->_handle_error( $sock, 'error reading buffer from $1' );
1204 if ( $result === '' ) {
1205 // This will happen if the remote end of the socket is shut down
1206 $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1209 $len -= strlen( $result );
1216 * Read a line from a stream. If there is an error, mark the socket dead.
1217 * The \r\n line ending is stripped from the response.
1219 * @param Resource $sock The socket
1220 * @return string|bool The string on success, false on failure
1222 function _fgets( $sock ) {
1223 $result = fgets( $sock );
1224 // fgets() may return a partial line if there is a select timeout after
1225 // a successful recv(), so we have to check for a timeout even if we
1226 // got a string response.
1227 $data = stream_get_meta_data( $sock );
1228 if ( $data['timed_out'] ) {
1229 $this->_handle_error( $sock, 'timeout reading line from $1' );
1232 if ( $result === false ) {
1233 $this->_handle_error( $sock, 'error reading line from $1' );
1236 if ( substr( $result, -2 ) === "\r\n" ) {
1237 $result = substr( $result, 0, -2 );
1238 } elseif ( substr( $result, -1 ) === "\n" ) {
1239 $result = substr( $result, 0, -1 );
1241 $this->_handle_error( $sock, 'line ending missing in response from $1' );
1248 * Flush the read buffer of a stream
1249 * @param Resource $f
1251 function _flush_read_buffer( $f ) {
1252 if ( !is_resource( $f ) ) {
1258 $n = stream_select( $r, $w, $e, 0, 0 );
1259 while ( $n == 1 && !feof( $f ) ) {
1264 $n = stream_select( $r, $w, $e, 0, 0 );
1275 class MemCachedClientforWiki
extends MWMemcached
{