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
100 * Minimum savings to store data compressed
102 const COMPRESSION_SAVINGS
= 0.20;
118 * Cached Sockets that are connected
126 * Current debug status; 0 - none to 9 - profiling
134 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
142 * Is compression available?
150 * Do we want to use compression?
155 public $_compress_enable;
158 * At how many bytes should we compress?
163 public $_compress_threshold;
166 * Are we using persistent links?
174 * If only using one server; contains ip:port to connect to
179 public $_single_sock;
182 * Array containing ip:port or array(ip:port, weight)
198 * Total # of bit buckets we have
203 public $_bucketcount;
206 * # of total servers we have
214 * Stream timeout in seconds. Applies for example to fread()
219 public $_timeout_seconds;
222 * Stream timeout in microseconds
227 public $_timeout_microseconds;
230 * Connect timeout in seconds
232 public $_connect_timeout;
235 * Number of connection attempts for each server
237 public $_connect_attempts;
240 * @var LoggerInterface
247 // {{{ public functions
251 * Memcache initializer
253 * @param array $args Associative array of settings
257 public function __construct( $args ) {
258 $this->set_servers( isset( $args['servers'] ) ?
$args['servers'] : array() );
259 $this->_debug
= isset( $args['debug'] ) ?
$args['debug'] : false;
260 $this->stats
= array();
261 $this->_compress_threshold
= isset( $args['compress_threshold'] ) ?
$args['compress_threshold'] : 0;
262 $this->_persistent
= isset( $args['persistent'] ) ?
$args['persistent'] : false;
263 $this->_compress_enable
= true;
264 $this->_have_zlib
= function_exists( 'gzcompress' );
266 $this->_cache_sock
= array();
267 $this->_host_dead
= array();
269 $this->_timeout_seconds
= 0;
270 $this->_timeout_microseconds
= isset( $args['timeout'] ) ?
$args['timeout'] : 500000;
272 $this->_connect_timeout
= isset( $args['connect_timeout'] ) ?
$args['connect_timeout'] : 0.1;
273 $this->_connect_attempts
= 2;
275 $this->_logger
= isset( $args['logger'] ) ?
$args['logger'] : new NullLogger();
282 * Adds a key/value to the memcache server if one isn't already set with
285 * @param string $key Key to set with data
286 * @param mixed $val Value to store
287 * @param int $exp (optional) Expiration time. This can be a number of seconds
288 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
289 * longer must be the timestamp of the time at which the mapping should expire. It
290 * is safe to use timestamps in all cases, regardless of expiration
291 * eg: strtotime("+3 hour")
295 public function add( $key, $val, $exp = 0 ) {
296 return $this->_set( 'add', $key, $val, $exp );
303 * Decrease a value stored on the memcache server
305 * @param string $key Key to decrease
306 * @param int $amt (optional) amount to decrease
308 * @return mixed False on failure, value on success
310 public function decr( $key, $amt = 1 ) {
311 return $this->_incrdecr( 'decr', $key, $amt );
318 * Deletes a key from the server, optionally after $time
320 * @param string $key Key to delete
321 * @param int $time (optional) how long to wait before deleting
323 * @return bool True on success, false on failure
325 public function delete( $key, $time = 0 ) {
326 if ( !$this->_active
) {
330 $sock = $this->get_sock( $key );
331 if ( !is_resource( $sock ) ) {
335 $key = is_array( $key ) ?
$key[1] : $key;
337 if ( isset( $this->stats
['delete'] ) ) {
338 $this->stats
['delete']++
;
340 $this->stats
['delete'] = 1;
342 $cmd = "delete $key $time\r\n";
343 if ( !$this->_fwrite( $sock, $cmd ) ) {
346 $res = $this->_fgets( $sock );
348 if ( $this->_debug
) {
349 $this->_debugprint( sprintf( "MemCache: delete %s (%s)\n", $key, $res ) );
352 if ( $res == "DELETED" ||
$res == "NOT_FOUND" ) {
361 * @param int $timeout
364 public function lock( $key, $timeout = 0 ) {
373 public function unlock( $key ) {
379 // {{{ disconnect_all()
382 * Disconnects all connected sockets
384 public function disconnect_all() {
385 foreach ( $this->_cache_sock
as $sock ) {
389 $this->_cache_sock
= array();
393 // {{{ enable_compress()
396 * Enable / Disable compression
398 * @param bool $enable True to enable, false to disable
400 public function enable_compress( $enable ) {
401 $this->_compress_enable
= $enable;
405 // {{{ forget_dead_hosts()
408 * Forget about all of the dead hosts
410 public function forget_dead_hosts() {
411 $this->_host_dead
= array();
418 * Retrieves the value associated with the key from the memcache server
420 * @param array|string $key key to retrieve
421 * @param float $casToken [optional]
425 public function get( $key, &$casToken = null ) {
427 if ( $this->_debug
) {
428 $this->_debugprint( "get($key)\n" );
431 if ( !is_array( $key ) && strval( $key ) === '' ) {
432 $this->_debugprint( "Skipping key which equals to an empty string" );
436 if ( !$this->_active
) {
440 $sock = $this->get_sock( $key );
442 if ( !is_resource( $sock ) ) {
446 $key = is_array( $key ) ?
$key[1] : $key;
447 if ( isset( $this->stats
['get'] ) ) {
448 $this->stats
['get']++
;
450 $this->stats
['get'] = 1;
453 $cmd = "gets $key\r\n";
454 if ( !$this->_fwrite( $sock, $cmd ) ) {
459 $this->_load_items( $sock, $val, $casToken );
461 if ( $this->_debug
) {
462 foreach ( $val as $k => $v ) {
463 $this->_debugprint( sprintf( "MemCache: sock %s got %s\n", serialize( $sock ), $k ) );
468 if ( isset( $val[$key] ) ) {
478 * Get multiple keys from the server(s)
480 * @param array $keys Keys to retrieve
484 public function get_multi( $keys ) {
485 if ( !$this->_active
) {
489 if ( isset( $this->stats
['get_multi'] ) ) {
490 $this->stats
['get_multi']++
;
492 $this->stats
['get_multi'] = 1;
494 $sock_keys = array();
496 foreach ( $keys as $key ) {
497 $sock = $this->get_sock( $key );
498 if ( !is_resource( $sock ) ) {
501 $key = is_array( $key ) ?
$key[1] : $key;
502 if ( !isset( $sock_keys[$sock] ) ) {
503 $sock_keys[intval( $sock )] = array();
506 $sock_keys[intval( $sock )][] = $key;
510 // Send out the requests
511 foreach ( $socks as $sock ) {
513 foreach ( $sock_keys[intval( $sock )] as $key ) {
518 if ( $this->_fwrite( $sock, $cmd ) ) {
525 foreach ( $gather as $sock ) {
526 $this->_load_items( $sock, $val, $casToken );
529 if ( $this->_debug
) {
530 foreach ( $val as $k => $v ) {
531 $this->_debugprint( sprintf( "MemCache: got %s\n", $k ) );
542 * Increments $key (optionally) by $amt
544 * @param string $key Key to increment
545 * @param int $amt (optional) amount to increment
547 * @return int|null Null if the key does not exist yet (this does NOT
548 * create new mappings if the key does not exist). If the key does
549 * exist, this returns the new value for that key.
551 public function incr( $key, $amt = 1 ) {
552 return $this->_incrdecr( 'incr', $key, $amt );
559 * Overwrites an existing value for key; only works if key is already set
561 * @param string $key Key to set value as
562 * @param mixed $value Value to store
563 * @param int $exp (optional) Expiration time. This can be a number of seconds
564 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
565 * longer must be the timestamp of the time at which the mapping should expire. It
566 * is safe to use timestamps in all cases, regardless of exipration
567 * eg: strtotime("+3 hour")
571 public function replace( $key, $value, $exp = 0 ) {
572 return $this->_set( 'replace', $key, $value, $exp );
579 * Passes through $cmd to the memcache server connected by $sock; returns
580 * output as an array (null array if no output)
582 * @param Resource $sock Socket to send command on
583 * @param string $cmd Command to run
585 * @return array Output array
587 public function run_command( $sock, $cmd ) {
588 if ( !is_resource( $sock ) ) {
592 if ( !$this->_fwrite( $sock, $cmd ) ) {
598 $res = $this->_fgets( $sock );
600 if ( preg_match( '/^END/', $res ) ) {
603 if ( strlen( $res ) == 0 ) {
614 * Unconditionally sets a key to a given value in the memcache. Returns true
615 * if set successfully.
617 * @param string $key Key to set value as
618 * @param mixed $value Value to set
619 * @param int $exp (optional) Expiration time. This can be a number of seconds
620 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
621 * longer must be the timestamp of the time at which the mapping should expire. It
622 * is safe to use timestamps in all cases, regardless of exipration
623 * eg: strtotime("+3 hour")
625 * @return bool True on success
627 public function set( $key, $value, $exp = 0 ) {
628 return $this->_set( 'set', $key, $value, $exp );
635 * Sets a key to a given value in the memcache if the current value still corresponds
636 * to a known, given value. Returns true if set successfully.
638 * @param float $casToken Current known value
639 * @param string $key Key to set value as
640 * @param mixed $value Value to set
641 * @param int $exp (optional) Expiration time. This can be a number of seconds
642 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
643 * longer must be the timestamp of the time at which the mapping should expire. It
644 * is safe to use timestamps in all cases, regardless of exipration
645 * eg: strtotime("+3 hour")
647 * @return bool True on success
649 public function cas( $casToken, $key, $value, $exp = 0 ) {
650 return $this->_set( 'cas', $key, $value, $exp, $casToken );
654 // {{{ set_compress_threshold()
657 * Sets the compression threshold
659 * @param int $thresh Threshold to compress if larger than
661 public function set_compress_threshold( $thresh ) {
662 $this->_compress_threshold
= $thresh;
669 * Sets the debug flag
671 * @param bool $dbg True for debugging, false otherwise
673 * @see MWMemcached::__construct
675 public function set_debug( $dbg ) {
676 $this->_debug
= $dbg;
683 * Sets the server list to distribute key gets and puts between
685 * @param array $list Array of servers to connect to
687 * @see MWMemcached::__construct()
689 public function set_servers( $list ) {
690 $this->_servers
= $list;
691 $this->_active
= count( $list );
692 $this->_buckets
= null;
693 $this->_bucketcount
= 0;
695 $this->_single_sock
= null;
696 if ( $this->_active
== 1 ) {
697 $this->_single_sock
= $this->_servers
[0];
702 * Sets the timeout for new connections
704 * @param int $seconds Number of seconds
705 * @param int $microseconds Number of microseconds
707 public function set_timeout( $seconds, $microseconds ) {
708 $this->_timeout_seconds
= $seconds;
709 $this->_timeout_microseconds
= $microseconds;
714 // {{{ private methods
718 * Close the specified socket
720 * @param string $sock Socket to close
724 function _close_sock( $sock ) {
725 $host = array_search( $sock, $this->_cache_sock
);
726 fclose( $this->_cache_sock
[$host] );
727 unset( $this->_cache_sock
[$host] );
731 // {{{ _connect_sock()
734 * Connects $sock to $host, timing out after $timeout
736 * @param int $sock Socket to connect
737 * @param string $host Host:IP to connect to
742 function _connect_sock( &$sock, $host ) {
743 list( $ip, $port ) = preg_split( '/:(?=\d)/', $host );
745 $timeout = $this->_connect_timeout
;
746 $errno = $errstr = null;
747 for ( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
748 wfSuppressWarnings();
749 if ( $this->_persistent
== 1 ) {
750 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
752 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
757 $this->_error_log( "Error connecting to $host: $errstr\n" );
758 $this->_dead_host( $host );
762 // Initialise timeout
763 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
765 // If the connection was persistent, flush the read buffer in case there
766 // was a previous incomplete request on this connection
767 if ( $this->_persistent
) {
768 $this->_flush_read_buffer( $sock );
777 * Marks a host as dead until 30-40 seconds in the future
779 * @param string $sock Socket to mark as dead
783 function _dead_sock( $sock ) {
784 $host = array_search( $sock, $this->_cache_sock
);
785 $this->_dead_host( $host );
789 * @param string $host
791 function _dead_host( $host ) {
792 $parts = explode( ':', $host );
794 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
795 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
796 unset( $this->_cache_sock
[$host] );
805 * @param string $key Key to retrieve value for;
807 * @return Resource|bool Resource on success, false on failure
810 function get_sock( $key ) {
811 if ( !$this->_active
) {
815 if ( $this->_single_sock
!== null ) {
816 return $this->sock_to_host( $this->_single_sock
);
819 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
820 if ( $this->_buckets
=== null ) {
822 foreach ( $this->_servers
as $v ) {
823 if ( is_array( $v ) ) {
824 for ( $i = 0; $i < $v[1]; $i++
) {
831 $this->_buckets
= $bu;
832 $this->_bucketcount
= count( $bu );
835 $realkey = is_array( $key ) ?
$key[1] : $key;
836 for ( $tries = 0; $tries < 20; $tries++
) {
837 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
838 $sock = $this->sock_to_host( $host );
839 if ( is_resource( $sock ) ) {
842 $hv = $this->_hashfunc( $hv . $realkey );
852 * Creates a hash integer based on the $key
854 * @param string $key Key to hash
856 * @return int Hash value
859 function _hashfunc( $key ) {
860 # Hash function must be in [0,0x7ffffff]
861 # We take the first 31 bits of the MD5 hash, which unlike the hash
862 # function used in a previous version of this client, works
863 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
870 * Perform increment/decriment on $key
872 * @param string $cmd Command to perform
873 * @param string|array $key Key to perform it on
874 * @param int $amt Amount to adjust
876 * @return int New value of $key
879 function _incrdecr( $cmd, $key, $amt = 1 ) {
880 if ( !$this->_active
) {
884 $sock = $this->get_sock( $key );
885 if ( !is_resource( $sock ) ) {
889 $key = is_array( $key ) ?
$key[1] : $key;
890 if ( isset( $this->stats
[$cmd] ) ) {
891 $this->stats
[$cmd]++
;
893 $this->stats
[$cmd] = 1;
895 if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
899 $line = $this->_fgets( $sock );
901 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
911 * Load items into $ret from $sock
913 * @param Resource $sock Socket to read from
914 * @param array $ret returned values
915 * @param float $casToken [optional]
916 * @return bool True for success, false for failure
920 function _load_items( $sock, &$ret, &$casToken = null ) {
924 $decl = $this->_fgets( $sock );
926 if ( $decl === false ) {
928 * If nothing can be read, something is wrong because we know exactly when
929 * to stop reading (right after "END") and we return right after that.
932 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
934 * Read all data returned. This can be either one or multiple values.
935 * Save all that data (in an array) to be processed later: we'll first
936 * want to continue reading until "END" before doing anything else,
937 * to make sure that we don't leave our client in a state where it's
938 * output is not yet fully read.
944 $match[4], // casToken
945 $this->_fread( $sock, $match[3] +
2 ), // data
947 } elseif ( $decl == "END" ) {
948 if ( count( $results ) == 0 ) {
953 * All data has been read, time to process the data and build
954 * meaningful return values.
956 foreach ( $results as $vars ) {
957 list( $rkey, $flags, $len, $casToken, $data ) = $vars;
959 if ( $data === false ||
substr( $data, -2 ) !== "\r\n" ) {
960 $this->_handle_error( $sock,
961 'line ending missing from data block from $1' );
964 $data = substr( $data, 0, -2 );
967 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
968 $ret[$rkey] = gzuncompress( $ret[$rkey] );
972 * This unserialize is the exact reason that we only want to
973 * process data after having read until "END" (instead of doing
974 * this right away): "unserialize" can trigger outside code:
975 * in the event that $ret[$rkey] is a serialized object,
976 * unserializing it will trigger __wakeup() if present. If that
977 * function attempted to read from memcached (while we did not
978 * yet read "END"), these 2 calls would collide.
980 if ( $flags & self
::SERIALIZED
) {
981 $ret[$rkey] = unserialize( $ret[$rkey] );
987 $this->_handle_error( $sock, 'Error parsing response from $1' );
997 * Performs the requested storage operation to the memcache server
999 * @param string $cmd Command to perform
1000 * @param string $key Key to act on
1001 * @param mixed $val What we need to store
1002 * @param int $exp (optional) Expiration time. This can be a number of seconds
1003 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
1004 * longer must be the timestamp of the time at which the mapping should expire. It
1005 * is safe to use timestamps in all cases, regardless of exipration
1006 * eg: strtotime("+3 hour")
1007 * @param float $casToken [optional]
1012 function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1013 if ( !$this->_active
) {
1017 $sock = $this->get_sock( $key );
1018 if ( !is_resource( $sock ) ) {
1022 if ( isset( $this->stats
[$cmd] ) ) {
1023 $this->stats
[$cmd]++
;
1025 $this->stats
[$cmd] = 1;
1030 if ( !is_scalar( $val ) ) {
1031 $val = serialize( $val );
1032 $flags |
= self
::SERIALIZED
;
1033 if ( $this->_debug
) {
1034 $this->_debugprint( sprintf( "client: serializing data as it is not scalar\n" ) );
1038 $len = strlen( $val );
1040 if ( $this->_have_zlib
&& $this->_compress_enable
1041 && $this->_compress_threshold
&& $len >= $this->_compress_threshold
1043 $c_val = gzcompress( $val, 9 );
1044 $c_len = strlen( $c_val );
1046 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
1047 if ( $this->_debug
) {
1048 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes\n", $len, $c_len ) );
1052 $flags |
= self
::COMPRESSED
;
1056 $command = "$cmd $key $flags $exp $len";
1058 $command .= " $casToken";
1061 if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1065 $line = $this->_fgets( $sock );
1067 if ( $this->_debug
) {
1068 $this->_debugprint( sprintf( "%s %s (%s)\n", $cmd, $key, $line ) );
1070 if ( $line == "STORED" ) {
1077 // {{{ sock_to_host()
1080 * Returns the socket for the host
1082 * @param string $host Host:IP to get socket for
1084 * @return Resource|bool IO Stream or false
1087 function sock_to_host( $host ) {
1088 if ( isset( $this->_cache_sock
[$host] ) ) {
1089 return $this->_cache_sock
[$host];
1094 list( $ip, /* $port */) = explode( ':', $host );
1095 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
1096 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
1101 if ( !$this->_connect_sock( $sock, $host ) ) {
1105 // Do not buffer writes
1106 stream_set_write_buffer( $sock, 0 );
1108 $this->_cache_sock
[$host] = $sock;
1110 return $this->_cache_sock
[$host];
1114 * @param string $text
1116 function _debugprint( $text ) {
1117 $this->_logger
->debug( $text );
1121 * @param string $text
1123 function _error_log( $text ) {
1124 $this->_logger
->error( "Memcached error: $text" );
1128 * Write to a stream. If there is an error, mark the socket dead.
1130 * @param Resource $sock The socket
1131 * @param string $buf The string to write
1132 * @return bool True on success, false on failure
1134 function _fwrite( $sock, $buf ) {
1136 $bufSize = strlen( $buf );
1137 while ( $bytesWritten < $bufSize ) {
1138 $result = fwrite( $sock, $buf );
1139 $data = stream_get_meta_data( $sock );
1140 if ( $data['timed_out'] ) {
1141 $this->_handle_error( $sock, 'timeout writing to $1' );
1144 // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1145 if ( $result === false ||
$result === 0 ) {
1146 $this->_handle_error( $sock, 'error writing to $1' );
1149 $bytesWritten +
= $result;
1156 * Handle an I/O error. Mark the socket dead and log an error.
1158 * @param Resource $sock
1159 * @param string $msg
1161 function _handle_error( $sock, $msg ) {
1162 $peer = stream_socket_get_name( $sock, true /** remote **/ );
1163 if ( strval( $peer ) === '' ) {
1164 $peer = array_search( $sock, $this->_cache_sock
);
1165 if ( $peer === false ) {
1166 $peer = '[unknown host]';
1169 $msg = str_replace( '$1', $peer, $msg );
1170 $this->_error_log( "$msg\n" );
1171 $this->_dead_sock( $sock );
1175 * Read the specified number of bytes from a stream. If there is an error,
1176 * mark the socket dead.
1178 * @param Resource $sock The socket
1179 * @param int $len The number of bytes to read
1180 * @return string|bool The string on success, false on failure.
1182 function _fread( $sock, $len ) {
1184 while ( $len > 0 ) {
1185 $result = fread( $sock, $len );
1186 $data = stream_get_meta_data( $sock );
1187 if ( $data['timed_out'] ) {
1188 $this->_handle_error( $sock, 'timeout reading from $1' );
1191 if ( $result === false ) {
1192 $this->_handle_error( $sock, 'error reading buffer from $1' );
1195 if ( $result === '' ) {
1196 // This will happen if the remote end of the socket is shut down
1197 $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1200 $len -= strlen( $result );
1207 * Read a line from a stream. If there is an error, mark the socket dead.
1208 * The \r\n line ending is stripped from the response.
1210 * @param Resource $sock The socket
1211 * @return string|bool The string on success, false on failure
1213 function _fgets( $sock ) {
1214 $result = fgets( $sock );
1215 // fgets() may return a partial line if there is a select timeout after
1216 // a successful recv(), so we have to check for a timeout even if we
1217 // got a string response.
1218 $data = stream_get_meta_data( $sock );
1219 if ( $data['timed_out'] ) {
1220 $this->_handle_error( $sock, 'timeout reading line from $1' );
1223 if ( $result === false ) {
1224 $this->_handle_error( $sock, 'error reading line from $1' );
1227 if ( substr( $result, -2 ) === "\r\n" ) {
1228 $result = substr( $result, 0, -2 );
1229 } elseif ( substr( $result, -1 ) === "\n" ) {
1230 $result = substr( $result, 0, -1 );
1232 $this->_handle_error( $sock, 'line ending missing in response from $1' );
1239 * Flush the read buffer of a stream
1240 * @param Resource $f
1242 function _flush_read_buffer( $f ) {
1243 if ( !is_resource( $f ) ) {
1249 $n = stream_select( $r, $w, $e, 0, 0 );
1250 while ( $n == 1 && !feof( $f ) ) {
1255 $n = stream_select( $r, $w, $e, 0, 0 );
1266 class MemCachedClientforWiki
extends MWMemcached
{