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 a PHP client for memcached - a distributed memory cache daemon.
46 * More information is available at http://www.danga.com/memcached/
50 * $mc = new MemcachedClient(array(
53 * array( '192.0.0.1:10010', 2 ),
57 * 'compress_threshold' => 10240,
58 * 'persistent' => true
61 * $mc->add( 'key', array( 'some', 'array' ) );
62 * $mc->replace( 'key', 'some random string' );
63 * $val = $mc->get( 'key' );
65 * @author Ryan T. Dean <rtdean@cytherianage.net>
69 use Psr\Log\LoggerInterface
;
70 use Psr\Log\NullLogger
;
72 // {{{ class MemcachedClient
74 * memcached client class implemented using (p)fsockopen()
76 * @author Ryan T. Dean <rtdean@cytherianage.net>
79 class MemcachedClient
{
87 * Flag: indicates data is serialized
92 * Flag: indicates data is compressed
97 * Flag: indicates data is an integer
104 * Minimum savings to store data compressed
106 const COMPRESSION_SAVINGS
= 0.20;
122 * Cached Sockets that are connected
130 * Current debug status; 0 - none to 9 - profiling
138 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
146 * Is compression available?
154 * Do we want to use compression?
159 public $_compress_enable;
162 * At how many bytes should we compress?
167 public $_compress_threshold;
170 * Are we using persistent links?
178 * If only using one server; contains ip:port to connect to
183 public $_single_sock;
186 * Array containing ip:port or array(ip:port, weight)
202 * Total # of bit buckets we have
207 public $_bucketcount;
210 * # of total servers we have
218 * Stream timeout in seconds. Applies for example to fread()
223 public $_timeout_seconds;
226 * Stream timeout in microseconds
231 public $_timeout_microseconds;
234 * Connect timeout in seconds
236 public $_connect_timeout;
239 * Number of connection attempts for each server
241 public $_connect_attempts;
244 * @var LoggerInterface
251 // {{{ public functions
255 * Memcache initializer
257 * @param array $args Associative array of settings
261 public function __construct( $args ) {
262 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
263 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
264 $this->stats
= array();
265 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
266 $this->_persistent
= isset( $args['persistent'] ) ?
$args['persistent'] : false;
267 $this->_compress_enable
= true;
268 $this->_have_zlib
= function_exists( 'gzcompress' );
270 $this->_cache_sock
= array();
271 $this->_host_dead
= array();
273 $this->_timeout_seconds
= 0;
274 $this->_timeout_microseconds
= isset( $args['timeout'] ) ?
$args['timeout'] : 500000;
276 $this->_connect_timeout
= isset( $args['connect_timeout'] ) ?
$args['connect_timeout'] : 0.1;
277 $this->_connect_attempts
= 2;
279 $this->_logger
= isset( $args['logger'] ) ?
$args['logger'] : new NullLogger();
286 * Adds a key/value to the memcache server if one isn't already set with
289 * @param string $key Key to set with data
290 * @param mixed $val Value to store
291 * @param int $exp (optional) Expiration time. This can be a number of seconds
292 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
293 * longer must be the timestamp of the time at which the mapping should expire. It
294 * is safe to use timestamps in all cases, regardless of expiration
295 * eg: strtotime("+3 hour")
299 public function add( $key, $val, $exp = 0 ) {
300 return $this->_set( 'add', $key, $val, $exp );
307 * Decrease a value stored on the memcache server
309 * @param string $key Key to decrease
310 * @param int $amt (optional) amount to decrease
312 * @return mixed False on failure, value on success
314 public function decr( $key, $amt = 1 ) {
315 return $this->_incrdecr( 'decr', $key, $amt );
322 * Deletes a key from the server, optionally after $time
324 * @param string $key Key to delete
325 * @param int $time (optional) how long to wait before deleting
327 * @return bool True on success, false on failure
329 public function delete( $key, $time = 0 ) {
330 if ( !$this->_active
) {
334 $sock = $this->get_sock( $key );
335 if ( !is_resource( $sock ) ) {
339 $key = is_array( $key ) ?
$key[1] : $key;
341 if ( isset( $this->stats
['delete'] ) ) {
342 $this->stats
['delete']++
;
344 $this->stats
['delete'] = 1;
346 $cmd = "delete $key $time\r\n";
347 if ( !$this->_fwrite( $sock, $cmd ) ) {
350 $res = $this->_fgets( $sock );
352 if ( $this->_debug
) {
353 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
356 if ( $res == "DELETED" ||
$res == "NOT_FOUND" ) {
365 * @param int $timeout
368 public function lock( $key, $timeout = 0 ) {
377 public function unlock( $key ) {
383 // {{{ disconnect_all()
386 * Disconnects all connected sockets
388 public function disconnect_all() {
389 foreach ( $this->_cache_sock
as $sock ) {
393 $this->_cache_sock
= array();
397 // {{{ enable_compress()
400 * Enable / Disable compression
402 * @param bool $enable True to enable, false to disable
404 public function enable_compress( $enable ) {
405 $this->_compress_enable
= $enable;
409 // {{{ forget_dead_hosts()
412 * Forget about all of the dead hosts
414 public function forget_dead_hosts() {
415 $this->_host_dead
= array();
422 * Retrieves the value associated with the key from the memcache server
424 * @param array|string $key key to retrieve
425 * @param float $casToken [optional]
429 public function get( $key, &$casToken = null ) {
431 if ( $this->_debug
) {
432 $this->_debugprint( "get($key)\n" );
435 if ( !is_array( $key ) && strval( $key ) === '' ) {
436 $this->_debugprint( "Skipping key which equals to an empty string" );
440 if ( !$this->_active
) {
444 $sock = $this->get_sock( $key );
446 if ( !is_resource( $sock ) ) {
450 $key = is_array( $key ) ?
$key[1] : $key;
451 if ( isset( $this->stats
['get'] ) ) {
452 $this->stats
['get']++
;
454 $this->stats
['get'] = 1;
457 $cmd = "gets $key\r\n";
458 if ( !$this->_fwrite( $sock, $cmd ) ) {
463 $this->_load_items( $sock, $val, $casToken );
465 if ( $this->_debug
) {
466 foreach ( $val as $k => $v ) {
467 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
472 if ( isset( $val[$key] ) ) {
482 * Get multiple keys from the server(s)
484 * @param array $keys Keys to retrieve
488 public function get_multi( $keys ) {
489 if ( !$this->_active
) {
493 if ( isset( $this->stats
['get_multi'] ) ) {
494 $this->stats
['get_multi']++
;
496 $this->stats
['get_multi'] = 1;
498 $sock_keys = array();
500 foreach ( $keys as $key ) {
501 $sock = $this->get_sock( $key );
502 if ( !is_resource( $sock ) ) {
505 $key = is_array( $key ) ?
$key[1] : $key;
506 if ( !isset( $sock_keys[$sock] ) ) {
507 $sock_keys[intval( $sock )] = array();
510 $sock_keys[intval( $sock )][] = $key;
514 // Send out the requests
515 foreach ( $socks as $sock ) {
517 foreach ( $sock_keys[intval( $sock )] as $key ) {
522 if ( $this->_fwrite( $sock, $cmd ) ) {
529 foreach ( $gather as $sock ) {
530 $this->_load_items( $sock, $val, $casToken );
533 if ( $this->_debug
) {
534 foreach ( $val as $k => $v ) {
535 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
546 * Increments $key (optionally) by $amt
548 * @param string $key Key to increment
549 * @param int $amt (optional) amount to increment
551 * @return int|null Null if the key does not exist yet (this does NOT
552 * create new mappings if the key does not exist). If the key does
553 * exist, this returns the new value for that key.
555 public function incr( $key, $amt = 1 ) {
556 return $this->_incrdecr( 'incr', $key, $amt );
563 * Overwrites an existing value for key; only works if key is already set
565 * @param string $key Key to set value as
566 * @param mixed $value Value to store
567 * @param int $exp (optional) Expiration time. This can be a number of seconds
568 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
569 * longer must be the timestamp of the time at which the mapping should expire. It
570 * is safe to use timestamps in all cases, regardless of exipration
571 * eg: strtotime("+3 hour")
575 public function replace( $key, $value, $exp = 0 ) {
576 return $this->_set( 'replace', $key, $value, $exp );
583 * Passes through $cmd to the memcache server connected by $sock; returns
584 * output as an array (null array if no output)
586 * @param Resource $sock Socket to send command on
587 * @param string $cmd Command to run
589 * @return array Output array
591 public function run_command( $sock, $cmd ) {
592 if ( !is_resource( $sock ) ) {
596 if ( !$this->_fwrite( $sock, $cmd ) ) {
602 $res = $this->_fgets( $sock );
604 if ( preg_match( '/^END/', $res ) ) {
607 if ( strlen( $res ) == 0 ) {
618 * Unconditionally sets a key to a given value in the memcache. Returns true
619 * if set successfully.
621 * @param string $key Key to set value as
622 * @param mixed $value Value to set
623 * @param int $exp (optional) Expiration time. This can be a number of seconds
624 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
625 * longer must be the timestamp of the time at which the mapping should expire. It
626 * is safe to use timestamps in all cases, regardless of exipration
627 * eg: strtotime("+3 hour")
629 * @return bool True on success
631 public function set( $key, $value, $exp = 0 ) {
632 return $this->_set( 'set', $key, $value, $exp );
639 * Sets a key to a given value in the memcache if the current value still corresponds
640 * to a known, given value. Returns true if set successfully.
642 * @param float $casToken Current known value
643 * @param string $key Key to set value as
644 * @param mixed $value Value to set
645 * @param int $exp (optional) Expiration time. This can be a number of seconds
646 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
647 * longer must be the timestamp of the time at which the mapping should expire. It
648 * is safe to use timestamps in all cases, regardless of exipration
649 * eg: strtotime("+3 hour")
651 * @return bool True on success
653 public function cas( $casToken, $key, $value, $exp = 0 ) {
654 return $this->_set( 'cas', $key, $value, $exp, $casToken );
658 // {{{ set_compress_threshold()
661 * Set the compression threshold
663 * @param int $thresh Threshold to compress if larger than
665 public function set_compress_threshold( $thresh ) {
666 $this->_compress_threshold
= $thresh;
676 * @param bool $dbg True for debugging, false otherwise
678 public function set_debug( $dbg ) {
679 $this->_debug
= $dbg;
686 * Set the server list to distribute key gets and puts between
689 * @param array $list Array of servers to connect to
691 public function set_servers( $list ) {
692 $this->_servers
= $list;
693 $this->_active
= count( $list );
694 $this->_buckets
= null;
695 $this->_bucketcount
= 0;
697 $this->_single_sock
= null;
698 if ( $this->_active
== 1 ) {
699 $this->_single_sock
= $this->_servers
[0];
704 * Sets the timeout for new connections
706 * @param int $seconds Number of seconds
707 * @param int $microseconds Number of microseconds
709 public function set_timeout( $seconds, $microseconds ) {
710 $this->_timeout_seconds
= $seconds;
711 $this->_timeout_microseconds
= $microseconds;
716 // {{{ private methods
720 * Close the specified socket
722 * @param string $sock Socket to close
726 function _close_sock( $sock ) {
727 $host = array_search( $sock, $this->_cache_sock
);
728 fclose( $this->_cache_sock
[$host] );
729 unset( $this->_cache_sock
[$host] );
733 // {{{ _connect_sock()
736 * Connects $sock to $host, timing out after $timeout
738 * @param int $sock Socket to connect
739 * @param string $host Host:IP to connect to
744 function _connect_sock( &$sock, $host ) {
745 list( $ip, $port ) = preg_split( '/:(?=\d)/', $host );
747 $timeout = $this->_connect_timeout
;
748 $errno = $errstr = null;
749 for ( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
750 MediaWiki\
suppressWarnings();
751 if ( $this->_persistent
== 1 ) {
752 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
754 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
756 MediaWiki\restoreWarnings
();
759 $this->_error_log( "Error connecting to $host: $errstr\n" );
760 $this->_dead_host( $host );
764 // Initialise timeout
765 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
767 // If the connection was persistent, flush the read buffer in case there
768 // was a previous incomplete request on this connection
769 if ( $this->_persistent
) {
770 $this->_flush_read_buffer( $sock );
779 * Marks a host as dead until 30-40 seconds in the future
781 * @param string $sock Socket to mark as dead
785 function _dead_sock( $sock ) {
786 $host = array_search( $sock, $this->_cache_sock
);
787 $this->_dead_host( $host );
791 * @param string $host
793 function _dead_host( $host ) {
794 $parts = explode( ':', $host );
796 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
797 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
798 unset( $this->_cache_sock
[$host] );
807 * @param string $key Key to retrieve value for;
809 * @return Resource|bool Resource on success, false on failure
812 function get_sock( $key ) {
813 if ( !$this->_active
) {
817 if ( $this->_single_sock
!== null ) {
818 return $this->sock_to_host( $this->_single_sock
);
821 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
822 if ( $this->_buckets
=== null ) {
824 foreach ( $this->_servers
as $v ) {
825 if ( is_array( $v ) ) {
826 for ( $i = 0; $i < $v[1]; $i++
) {
833 $this->_buckets
= $bu;
834 $this->_bucketcount
= count( $bu );
837 $realkey = is_array( $key ) ?
$key[1] : $key;
838 for ( $tries = 0; $tries < 20; $tries++
) {
839 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
840 $sock = $this->sock_to_host( $host );
841 if ( is_resource( $sock ) ) {
844 $hv = $this->_hashfunc( $hv . $realkey );
854 * Creates a hash integer based on the $key
856 * @param string $key Key to hash
858 * @return int Hash value
861 function _hashfunc( $key ) {
862 # Hash function must be in [0,0x7ffffff]
863 # We take the first 31 bits of the MD5 hash, which unlike the hash
864 # function used in a previous version of this client, works
865 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
872 * Perform increment/decriment on $key
874 * @param string $cmd Command to perform
875 * @param string|array $key Key to perform it on
876 * @param int $amt Amount to adjust
878 * @return int New value of $key
881 function _incrdecr( $cmd, $key, $amt = 1 ) {
882 if ( !$this->_active
) {
886 $sock = $this->get_sock( $key );
887 if ( !is_resource( $sock ) ) {
891 $key = is_array( $key ) ?
$key[1] : $key;
892 if ( isset( $this->stats
[$cmd] ) ) {
893 $this->stats
[$cmd]++
;
895 $this->stats
[$cmd] = 1;
897 if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
901 $line = $this->_fgets( $sock );
903 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
913 * Load items into $ret from $sock
915 * @param Resource $sock Socket to read from
916 * @param array $ret returned values
917 * @param float $casToken [optional]
918 * @return bool True for success, false for failure
922 function _load_items( $sock, &$ret, &$casToken = null ) {
926 $decl = $this->_fgets( $sock );
928 if ( $decl === false ) {
930 * If nothing can be read, something is wrong because we know exactly when
931 * to stop reading (right after "END") and we return right after that.
934 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
936 * Read all data returned. This can be either one or multiple values.
937 * Save all that data (in an array) to be processed later: we'll first
938 * want to continue reading until "END" before doing anything else,
939 * to make sure that we don't leave our client in a state where it's
940 * output is not yet fully read.
946 $match[4], // casToken
947 $this->_fread( $sock, $match[3] +
2 ), // data
949 } elseif ( $decl == "END" ) {
950 if ( count( $results ) == 0 ) {
955 * All data has been read, time to process the data and build
956 * meaningful return values.
958 foreach ( $results as $vars ) {
959 list( $rkey, $flags, $len, $casToken, $data ) = $vars;
961 if ( $data === false ||
substr( $data, -2 ) !== "\r\n" ) {
962 $this->_handle_error( $sock,
963 'line ending missing from data block from $1' );
966 $data = substr( $data, 0, -2 );
969 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
970 $ret[$rkey] = gzuncompress( $ret[$rkey] );
974 * This unserialize is the exact reason that we only want to
975 * process data after having read until "END" (instead of doing
976 * this right away): "unserialize" can trigger outside code:
977 * in the event that $ret[$rkey] is a serialized object,
978 * unserializing it will trigger __wakeup() if present. If that
979 * function attempted to read from memcached (while we did not
980 * yet read "END"), these 2 calls would collide.
982 if ( $flags & self
::SERIALIZED
) {
983 $ret[$rkey] = unserialize( $ret[$rkey] );
984 } elseif ( $flags & self
::INTVAL
) {
985 $ret[$rkey] = intval( $ret[$rkey] );
991 $this->_handle_error( $sock, 'Error parsing response from $1' );
1001 * Performs the requested storage operation to the memcache server
1003 * @param string $cmd Command to perform
1004 * @param string $key Key to act on
1005 * @param mixed $val What we need to store
1006 * @param int $exp (optional) Expiration time. This can be a number of seconds
1007 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
1008 * longer must be the timestamp of the time at which the mapping should expire. It
1009 * is safe to use timestamps in all cases, regardless of exipration
1010 * eg: strtotime("+3 hour")
1011 * @param float $casToken [optional]
1016 function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1017 if ( !$this->_active
) {
1021 $sock = $this->get_sock( $key );
1022 if ( !is_resource( $sock ) ) {
1026 if ( isset( $this->stats
[$cmd] ) ) {
1027 $this->stats
[$cmd]++
;
1029 $this->stats
[$cmd] = 1;
1034 if ( is_int( $val ) ) {
1035 $flags |
= self
::INTVAL
;
1036 } elseif ( !is_scalar( $val ) ) {
1037 $val = serialize( $val );
1038 $flags |
= self
::SERIALIZED
;
1039 if ( $this->_debug
) {
1040 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
1044 $len = strlen( $val );
1046 if ( $this->_have_zlib
&& $this->_compress_enable
1047 && $this->_compress_threshold
&& $len >= $this->_compress_threshold
1049 $c_val = gzcompress( $val, 9 );
1050 $c_len = strlen( $c_val );
1052 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
1053 if ( $this->_debug
) {
1054 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
1058 $flags |
= self
::COMPRESSED
;
1062 $command = "$cmd $key $flags $exp $len";
1064 $command .= " $casToken";
1067 if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1071 $line = $this->_fgets( $sock );
1073 if ( $this->_debug
) {
1074 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
1076 if ( $line == "STORED" ) {
1083 // {{{ sock_to_host()
1086 * Returns the socket for the host
1088 * @param string $host Host:IP to get socket for
1090 * @return Resource|bool IO Stream or false
1093 function sock_to_host( $host ) {
1094 if ( isset( $this->_cache_sock
[$host] ) ) {
1095 return $this->_cache_sock
[$host];
1100 list( $ip, /* $port */) = explode( ':', $host );
1101 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
1102 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
1107 if ( !$this->_connect_sock( $sock, $host ) ) {
1111 // Do not buffer writes
1112 stream_set_write_buffer( $sock, 0 );
1114 $this->_cache_sock
[$host] = $sock;
1116 return $this->_cache_sock
[$host];
1120 * @param string $text
1122 function _debugprint( $text ) {
1123 $this->_logger
->debug( $text );
1127 * @param string $text
1129 function _error_log( $text ) {
1130 $this->_logger
->error( "Memcached error: $text" );
1134 * Write to a stream. If there is an error, mark the socket dead.
1136 * @param Resource $sock The socket
1137 * @param string $buf The string to write
1138 * @return bool True on success, false on failure
1140 function _fwrite( $sock, $buf ) {
1142 $bufSize = strlen( $buf );
1143 while ( $bytesWritten < $bufSize ) {
1144 $result = fwrite( $sock, $buf );
1145 $data = stream_get_meta_data( $sock );
1146 if ( $data['timed_out'] ) {
1147 $this->_handle_error( $sock, 'timeout writing to $1' );
1150 // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1151 if ( $result === false ||
$result === 0 ) {
1152 $this->_handle_error( $sock, 'error writing to $1' );
1155 $bytesWritten +
= $result;
1162 * Handle an I/O error. Mark the socket dead and log an error.
1164 * @param Resource $sock
1165 * @param string $msg
1167 function _handle_error( $sock, $msg ) {
1168 $peer = stream_socket_get_name( $sock, true /** remote **/ );
1169 if ( strval( $peer ) === '' ) {
1170 $peer = array_search( $sock, $this->_cache_sock
);
1171 if ( $peer === false ) {
1172 $peer = '[unknown host]';
1175 $msg = str_replace( '$1', $peer, $msg );
1176 $this->_error_log( "$msg\n" );
1177 $this->_dead_sock( $sock );
1181 * Read the specified number of bytes from a stream. If there is an error,
1182 * mark the socket dead.
1184 * @param Resource $sock The socket
1185 * @param int $len The number of bytes to read
1186 * @return string|bool The string on success, false on failure.
1188 function _fread( $sock, $len ) {
1190 while ( $len > 0 ) {
1191 $result = fread( $sock, $len );
1192 $data = stream_get_meta_data( $sock );
1193 if ( $data['timed_out'] ) {
1194 $this->_handle_error( $sock, 'timeout reading from $1' );
1197 if ( $result === false ) {
1198 $this->_handle_error( $sock, 'error reading buffer from $1' );
1201 if ( $result === '' ) {
1202 // This will happen if the remote end of the socket is shut down
1203 $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1206 $len -= strlen( $result );
1213 * Read a line from a stream. If there is an error, mark the socket dead.
1214 * The \r\n line ending is stripped from the response.
1216 * @param Resource $sock The socket
1217 * @return string|bool The string on success, false on failure
1219 function _fgets( $sock ) {
1220 $result = fgets( $sock );
1221 // fgets() may return a partial line if there is a select timeout after
1222 // a successful recv(), so we have to check for a timeout even if we
1223 // got a string response.
1224 $data = stream_get_meta_data( $sock );
1225 if ( $data['timed_out'] ) {
1226 $this->_handle_error( $sock, 'timeout reading line from $1' );
1229 if ( $result === false ) {
1230 $this->_handle_error( $sock, 'error reading line from $1' );
1233 if ( substr( $result, -2 ) === "\r\n" ) {
1234 $result = substr( $result, 0, -2 );
1235 } elseif ( substr( $result, -1 ) === "\n" ) {
1236 $result = substr( $result, 0, -1 );
1238 $this->_handle_error( $sock, 'line ending missing in response from $1' );
1245 * Flush the read buffer of a stream
1246 * @param Resource $f
1248 function _flush_read_buffer( $f ) {
1249 if ( !is_resource( $f ) ) {
1255 $n = stream_select( $r, $w, $e, 0, 0 );
1256 while ( $n == 1 && !feof( $f ) ) {
1261 $n = stream_select( $r, $w, $e, 0, 0 );