Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 402
0.00% covered (danger)
0.00%
0 / 38
CRAP
0.00% covered (danger)
0.00%
0 / 1
MemcachedClient
0.00% covered (danger)
0.00%
0 / 402
0.00% covered (danger)
0.00%
0 / 38
27390
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 serialize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 unserialize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 decr
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 delete
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
90
 touch
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 disconnect_all
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 enable_compress
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 forget_dead_hosts
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
210
 get_multi
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
210
 incr
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 replace
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 run_command
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 set
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 cas
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_compress_threshold
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_debug
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_servers
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 set_timeout
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 _close_sock
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 _connect_sock
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
72
 _dead_sock
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 _dead_host
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 get_sock
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 _hashfunc
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 _incrdecr
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
72
 _load_items
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
156
 _set
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
420
 sock_to_host
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
72
 _debugprint
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 _error_log
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 _fwrite
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 _handle_error
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 _fread
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
 _fgets
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 _flush_read_buffer
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2// phpcs:ignoreFile -- It's an external lib and it isn't. Let's not bother.
3
4// NO_NAMESPACE
5
6/**
7 * Memcached client for PHP.
8 *
9 * +---------------------------------------------------------------------------+
10 * | memcached client, PHP                                                     |
11 * +---------------------------------------------------------------------------+
12 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net>                 |
13 * | All rights reserved.                                                      |
14 * |                                                                           |
15 * | Redistribution and use in source and binary forms, with or without        |
16 * | modification, are permitted provided that the following conditions        |
17 * | are met:                                                                  |
18 * |                                                                           |
19 * | 1. Redistributions of source code must retain the above copyright         |
20 * |    notice, this list of conditions and the following disclaimer.          |
21 * | 2. Redistributions in binary form must reproduce the above copyright      |
22 * |    notice, this list of conditions and the following disclaimer in the    |
23 * |    documentation and/or other materials provided with the distribution.   |
24 * |                                                                           |
25 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR      |
26 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
27 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.   |
28 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,          |
29 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT  |
30 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
31 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY     |
32 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT       |
33 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF  |
34 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.         |
35 * +---------------------------------------------------------------------------+
36 * | Author: Ryan T. Dean <rtdean@cytherianage.net>                            |
37 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick.      |
38 * |   Permission granted by Brad Fitzpatrick for relicense of ported Perl     |
39 * |   client logic under 2-clause BSD license.                                |
40 * +---------------------------------------------------------------------------+
41 *
42 * @file
43 * $TCAnet$
44 */
45
46/**
47 * This is a PHP client for memcached - a distributed memory cache daemon.
48 *
49 * More information is available at http://www.danga.com/memcached/
50 *
51 * Usage example:
52 *
53 *     $mc = new MemcachedClient(array(
54 *         'servers' => array(
55 *             '127.0.0.1:10000',
56 *             array( '192.0.0.1:10010', 2 ),
57 *             '127.0.0.1:10020'
58 *         ),
59 *         'debug'   => false,
60 *         'compress_threshold' => 10240,
61 *         'persistent' => true
62 *     ));
63 *
64 *     $mc->add( 'key', array( 'some', 'array' ) );
65 *     $mc->replace( 'key', 'some random string' );
66 *     $val = $mc->get( 'key' );
67 *
68 * @author Ryan T. Dean <rtdean@cytherianage.net>
69 * @version 0.1.2
70 */
71
72use Psr\Log\LoggerInterface;
73use Psr\Log\NullLogger;
74use Wikimedia\IPUtils;
75use Wikimedia\ObjectCache\BagOStuff;
76
77/**
78 * memcached client class implemented using (p)fsockopen()
79 *
80 * @author  Ryan T. Dean <rtdean@cytherianage.net>
81 * @ingroup Cache
82 */
83class MemcachedClient {
84    // {{{ properties
85    // {{{ public
86
87    // {{{ constants
88    // {{{ flags
89
90    /**
91     * Flag: indicates data is serialized
92     */
93    const SERIALIZED = 1;
94
95    /**
96     * Flag: indicates data is compressed
97     */
98    const COMPRESSED = 2;
99
100    /**
101     * Flag: indicates data is an integer
102     */
103    const INTVAL = 4;
104
105    // }}}
106
107    /**
108     * Minimum savings to store data compressed
109     */
110    const COMPRESSION_SAVINGS = 0.20;
111
112    // }}}
113
114    /**
115     * Command statistics
116     *
117     * @var array
118     * @access public
119     */
120    public $stats;
121
122    // }}}
123    // {{{ private
124
125    /**
126     * Cached Sockets that are connected
127     *
128     * @var array
129     * @access private
130     */
131    public $_cache_sock;
132
133    /**
134     * Current debug status; 0 - none to 9 - profiling
135     *
136     * @var bool
137     * @access private
138     */
139    public $_debug;
140
141    /**
142     * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
143     *
144     * @var array
145     * @access private
146     */
147    public $_host_dead;
148
149    /**
150     * Is compression available?
151     *
152     * @var bool
153     * @access private
154     */
155    public $_have_zlib;
156
157    /**
158     * Do we want to use compression?
159     *
160     * @var bool
161     * @access private
162     */
163    public $_compress_enable;
164
165    /**
166     * At how many bytes should we compress?
167     *
168     * @var int
169     * @access private
170     */
171    public $_compress_threshold;
172
173    /**
174     * Are we using persistent links?
175     *
176     * @var bool
177     * @access private
178     */
179    public $_persistent;
180
181    /**
182     * If only using one server; contains ip:port to connect to
183     *
184     * @var string
185     * @access private
186     */
187    public $_single_sock;
188
189    /**
190     * Array containing ip:port or array(ip:port, weight)
191     *
192     * @var array
193     * @access private
194     */
195    public $_servers;
196
197    /**
198     * Our bit buckets
199     *
200     * @var array
201     * @access private
202     */
203    public $_buckets;
204
205    /**
206     * Total # of bit buckets we have
207     *
208     * @var int
209     * @access private
210     */
211    public $_bucketcount;
212
213    /**
214     * # of total servers we have
215     *
216     * @var int
217     * @access private
218     */
219    public $_active;
220
221    /**
222     * Stream timeout in seconds. Applies for example to fread()
223     *
224     * @var int
225     * @access private
226     */
227    public $_timeout_seconds;
228
229    /**
230     * Stream timeout in microseconds
231     *
232     * @var int
233     * @access private
234     */
235    public $_timeout_microseconds;
236
237    /**
238     * Connect timeout in seconds
239     */
240    public $_connect_timeout;
241
242    /**
243     * Number of connection attempts for each server
244     */
245    public $_connect_attempts;
246
247    /** @var int BagOStuff:ERR_* constant of the last cache command */
248    public $_last_cmd_status = BagOStuff::ERR_NONE;
249
250    /**
251     * @var LoggerInterface
252     */
253    private $_logger;
254
255
256    // }}}
257    // }}}
258    // {{{ methods
259    // {{{ public functions
260    // {{{ memcached()
261
262    /**
263     * Memcache initializer
264     *
265     * @param array $args Associative array of settings
266     */
267    public function __construct( $args ) {
268        $this->set_servers( $args['servers'] ?? array() );
269        $this->_debug = $args['debug'] ?? false;
270        $this->stats = array();
271        $this->_compress_threshold = $args['compress_threshold'] ?? 0;
272        $this->_persistent = $args['persistent'] ?? false;
273        $this->_compress_enable = true;
274        $this->_have_zlib = function_exists( 'gzcompress' );
275
276        $this->_cache_sock = array();
277        $this->_host_dead = array();
278
279        $this->_timeout_seconds = 0;
280        $this->_timeout_microseconds = $args['timeout'] ?? 500_000;
281
282        $this->_connect_timeout = $args['connect_timeout'] ?? 0.1;
283        $this->_connect_attempts = 2;
284
285        $this->_logger = $args['logger'] ?? new NullLogger();
286    }
287
288    // }}}
289
290    /**
291     * @param mixed $value
292     * @return string|integer
293     */
294    public function serialize( $value ) {
295        return serialize( $value );
296    }
297
298    /**
299     * @param string $value
300     * @return mixed
301     */
302    public function unserialize( $value ) {
303        return unserialize( $value );
304    }
305
306    // {{{ add()
307
308    /**
309     * Adds a key/value to the memcache server if one isn't already set with
310     * that key
311     *
312     * @param string $key Key to set with data
313     * @param mixed $val Value to store
314     * @param int $exp (optional) Expiration time. This can be a number of seconds
315     * to cache for (up to 30 days inclusive).  Any timespans of 30 days + 1 second or
316     * longer must be the timestamp of the time at which the mapping should expire. It
317     * is safe to use timestamps in all cases, regardless of expiration
318     * eg: strtotime("+3 hour")
319     *
320     * @return bool
321     */
322    public function add( $key, $val, $exp = 0 ) {
323        $this->_last_cmd_status = BagOStuff::ERR_NONE;
324
325        return $this->_set( 'add', $key, $val, $exp );
326    }
327
328    // }}}
329    // {{{ decr()
330
331    /**
332     * Decrease a value stored on the memcache server
333     *
334     * @param string $key Key to decrease
335     * @param int $amt (optional) amount to decrease
336     *
337     * @return mixed False on failure, value on success
338     */
339    public function decr( $key, $amt = 1 ) {
340        $this->_last_cmd_status = BagOStuff::ERR_NONE;
341
342        return $this->_incrdecr( 'decr', $key, $amt );
343    }
344
345    // }}}
346    // {{{ delete()
347
348    /**
349     * Deletes a key from the server, optionally after $time
350     *
351     * @param string $key Key to delete
352     * @param int $time (optional) how long to wait before deleting
353     *
354     * @return bool True on success, false on failure
355     */
356    public function delete( $key, $time = 0 ) {
357        $this->_last_cmd_status = BagOStuff::ERR_NONE;
358
359        if ( !$this->_active ) {
360            return false;
361        }
362
363        $sock = $this->get_sock( $key );
364        if ( !$sock ) {
365            return false;
366        }
367
368        $key = is_array( $key ) ? $key[1] : $key;
369
370        if ( isset( $this->stats['delete'] ) ) {
371            $this->stats['delete']++;
372        } else {
373            $this->stats['delete'] = 1;
374        }
375        $cmd = "delete $key $time\r\n";
376        if ( !$this->_fwrite( $sock, $cmd ) ) {
377            return false;
378        }
379        $res = $this->_fgets( $sock );
380
381        if ( $this->_debug ) {
382            $this->_debugprint( sprintf( "MemCache: delete %s (%s)", $key, $res ) );
383        }
384
385        if ( $res == "DELETED" || $res == "NOT_FOUND" ) {
386            return true;
387        }
388
389        $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
390
391        return false;
392    }
393
394    /**
395     * Changes the TTL on a key from the server to $time
396     *
397     * @param string $key
398     * @param int $time TTL in seconds
399     *
400     * @return bool True on success, false on failure
401     */
402    public function touch( $key, $time = 0 ) {
403        $this->_last_cmd_status = BagOStuff::ERR_NONE;
404
405        if ( !$this->_active ) {
406            return false;
407        }
408
409        $sock = $this->get_sock( $key );
410        if ( !$sock ) {
411            return false;
412        }
413
414        $key = is_array( $key ) ? $key[1] : $key;
415
416        if ( isset( $this->stats['touch'] ) ) {
417            $this->stats['touch']++;
418        } else {
419            $this->stats['touch'] = 1;
420        }
421        $cmd = "touch $key $time\r\n";
422        if ( !$this->_fwrite( $sock, $cmd ) ) {
423            return false;
424        }
425        $res = $this->_fgets( $sock );
426
427        if ( $this->_debug ) {
428            $this->_debugprint( sprintf( "MemCache: touch %s (%s)", $key, $res ) );
429        }
430
431        if ( $res == "TOUCHED" ) {
432            return true;
433        }
434
435        return false;
436    }
437
438    // }}}
439    // {{{ disconnect_all()
440
441    /**
442     * Disconnects all connected sockets
443     */
444    public function disconnect_all() {
445        foreach ( $this->_cache_sock as $sock ) {
446            fclose( $sock );
447        }
448
449        $this->_cache_sock = array();
450    }
451
452    // }}}
453    // {{{ enable_compress()
454
455    /**
456     * Enable / Disable compression
457     *
458     * @param bool $enable True to enable, false to disable
459     */
460    public function enable_compress( $enable ) {
461        $this->_compress_enable = $enable;
462    }
463
464    // }}}
465    // {{{ forget_dead_hosts()
466
467    /**
468     * Forget about all of the dead hosts
469     */
470    public function forget_dead_hosts() {
471        $this->_host_dead = array();
472    }
473
474    // }}}
475    // {{{ get()
476
477    /**
478     * Retrieves the value associated with the key from the memcache server
479     *
480     * @param array|string $key key to retrieve
481     * @param float $casToken [optional]
482     *
483     * @return mixed
484     */
485    public function get( $key, &$casToken = null ) {
486        $getToken = ( func_num_args() >= 2 );
487
488        $this->_last_cmd_status = BagOStuff::ERR_NONE;
489
490        if ( $this->_debug ) {
491            $this->_debugprint( "get($key)" );
492        }
493
494        if ( !is_array( $key ) && strval( $key ) === '' ) {
495            $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
496            $this->_debugprint( "Skipping key which equals to an empty string" );
497            return false;
498        }
499
500        if ( !$this->_active ) {
501            $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
502
503            return false;
504        }
505
506        $sock = $this->get_sock( $key );
507
508        if ( !$sock ) {
509            $this->_last_cmd_status = BagOStuff::ERR_UNREACHABLE;
510
511            return false;
512        }
513
514        $key = is_array( $key ) ? $key[1] : $key;
515        if ( isset( $this->stats['get'] ) ) {
516            $this->stats['get']++;
517        } else {
518            $this->stats['get'] = 1;
519        }
520
521        $cmd = $getToken ? "gets" : "get";
522        $cmd .= " $key\r\n";
523        if ( !$this->_fwrite( $sock, $cmd ) ) {
524            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
525
526            return false;
527        }
528
529        $val = array();
530        if ( !$this->_load_items( $sock, $val, $casToken ) ) {
531            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
532        }
533
534        if ( $this->_debug ) {
535            foreach ( $val as $k => $v ) {
536                $this->_debugprint(
537                    sprintf( "MemCache: sock %s got %s", $this->serialize( $sock ), $k ) );
538            }
539        }
540
541        $value = false;
542        if ( isset( $val[$key] ) ) {
543            $value = $val[$key];
544        }
545        return $value;
546    }
547
548    // }}}
549    // {{{ get_multi()
550
551    /**
552     * Get multiple keys from the server(s)
553     *
554     * @param array $keys Keys to retrieve
555     *
556     * @return array
557     */
558    public function get_multi( $keys ) {
559        $this->_last_cmd_status = BagOStuff::ERR_NONE;
560
561        if ( !$this->_active ) {
562            $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
563
564            return array();
565        }
566
567        if ( isset( $this->stats['get_multi'] ) ) {
568            $this->stats['get_multi']++;
569        } else {
570            $this->stats['get_multi'] = 1;
571        }
572        $sock_keys = array();
573        $socks = array();
574        foreach ( $keys as $key ) {
575            $sock = $this->get_sock( $key );
576            if ( !$sock ) {
577                $this->_last_cmd_status = BagOStuff::ERR_UNREACHABLE;
578                continue;
579            }
580            $key = is_array( $key ) ? $key[1] : $key;
581            $sockValue = intval( $sock );
582
583            if ( !isset( $sock_keys[$sockValue] ) ) {
584                $sock_keys[$sockValue] = array();
585                $socks[] = $sock;
586            }
587            $sock_keys[$sockValue][] = $key;
588        }
589
590        $gather = array();
591        // Send out the requests
592        foreach ( $socks as $sock ) {
593            $cmd = 'get';
594            foreach ( $sock_keys[intval( $sock )] as $key ) {
595                $cmd .= ' ' . $key;
596            }
597            $cmd .= "\r\n";
598
599            if ( $this->_fwrite( $sock, $cmd ) ) {
600                $gather[] = $sock;
601            } else {
602                $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
603            }
604        }
605
606        // Parse responses
607        $val = array();
608        foreach ( $gather as $sock ) {
609            if ( !$this->_load_items( $sock, $val ) ) {
610                $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
611            }
612        }
613
614        if ( $this->_debug ) {
615            foreach ( $val as $k => $v ) {
616                $this->_debugprint( sprintf( "MemCache: got %s", $k ) );
617            }
618        }
619
620        return $val;
621    }
622
623    // }}}
624    // {{{ incr()
625
626    /**
627     * Increments $key (optionally) by $amt
628     *
629     * @param string $key Key to increment
630     * @param int $amt (optional) amount to increment
631     *
632     * @return int|null Null if the key does not exist yet (this does NOT
633     * create new mappings if the key does not exist). If the key does
634     * exist, this returns the new value for that key.
635     */
636    public function incr( $key, $amt = 1 ) {
637        return $this->_incrdecr( 'incr', $key, $amt );
638    }
639
640    // }}}
641    // {{{ replace()
642
643    /**
644     * Overwrites an existing value for key; only works if key is already set
645     *
646     * @param string $key Key to set value as
647     * @param mixed $value Value to store
648     * @param int $exp (optional) Expiration time. This can be a number of seconds
649     * to cache for (up to 30 days inclusive).  Any timespans of 30 days + 1 second or
650     * longer must be the timestamp of the time at which the mapping should expire. It
651     * is safe to use timestamps in all cases, regardless of expiration
652     * eg: strtotime("+3 hour")
653     *
654     * @return bool
655     */
656    public function replace( $key, $value, $exp = 0 ) {
657        return $this->_set( 'replace', $key, $value, $exp );
658    }
659
660    // }}}
661    // {{{ run_command()
662
663    /**
664     * Passes through $cmd to the memcache server connected by $sock; returns
665     * output as an array (null array if no output)
666     *
667     * @param Resource $sock Socket to send command on
668     * @param string $cmd Command to run
669     *
670     * @return array Output array
671     */
672    public function run_command( $sock, $cmd ) {
673        if ( !$sock ) {
674            return array();
675        }
676
677        if ( !$this->_fwrite( $sock, $cmd ) ) {
678            return array();
679        }
680
681        $ret = array();
682        while ( true ) {
683            $res = $this->_fgets( $sock );
684            $ret[] = $res;
685            if ( preg_match( '/^END/', $res ) ) {
686                break;
687            }
688            if ( strlen( $res ) == 0 ) {
689                break;
690            }
691        }
692        return $ret;
693    }
694
695    // }}}
696    // {{{ set()
697
698    /**
699     * Unconditionally sets a key to a given value in the memcache.  Returns true
700     * if set successfully.
701     *
702     * @param string $key Key to set value as
703     * @param mixed $value Value to set
704     * @param int $exp (optional) Expiration time. This can be a number of seconds
705     * to cache for (up to 30 days inclusive).  Any timespans of 30 days + 1 second or
706     * longer must be the timestamp of the time at which the mapping should expire. It
707     * is safe to use timestamps in all cases, regardless of expiration
708     * eg: strtotime("+3 hour")
709     *
710     * @return bool True on success
711     */
712    public function set( $key, $value, $exp = 0 ) {
713        return $this->_set( 'set', $key, $value, $exp );
714    }
715
716    // }}}
717    // {{{ cas()
718
719    /**
720     * Sets a key to a given value in the memcache if the current value still corresponds
721     * to a known, given value.  Returns true if set successfully.
722     *
723     * @param float $casToken Current known value
724     * @param string $key Key to set value as
725     * @param mixed $value Value to set
726     * @param int $exp (optional) Expiration time. This can be a number of seconds
727     * to cache for (up to 30 days inclusive).  Any timespans of 30 days + 1 second or
728     * longer must be the timestamp of the time at which the mapping should expire. It
729     * is safe to use timestamps in all cases, regardless of expiration
730     * eg: strtotime("+3 hour")
731     *
732     * @return bool True on success
733     */
734    public function cas( $casToken, $key, $value, $exp = 0 ) {
735        return $this->_set( 'cas', $key, $value, $exp, $casToken );
736    }
737
738    // }}}
739    // {{{ set_compress_threshold()
740
741    /**
742     * Set the compression threshold
743     *
744     * @param int $thresh Threshold to compress if larger than
745     */
746    public function set_compress_threshold( $thresh ) {
747        $this->_compress_threshold = $thresh;
748    }
749
750    // }}}
751    // {{{ set_debug()
752
753    /**
754     * Set the debug flag
755     *
756     * @see __construct()
757     * @param bool $dbg True for debugging, false otherwise
758     */
759    public function set_debug( $dbg ) {
760        $this->_debug = $dbg;
761    }
762
763    // }}}
764    // {{{ set_servers()
765
766    /**
767     * Set the server list to distribute key gets and puts between
768     *
769     * @see __construct()
770     * @param array $list Array of servers to connect to
771     */
772    public function set_servers( $list ) {
773        $this->_servers = $list;
774        $this->_active = count( $list );
775        $this->_buckets = null;
776        $this->_bucketcount = 0;
777
778        $this->_single_sock = null;
779        if ( $this->_active == 1 ) {
780            $this->_single_sock = $this->_servers[0];
781        }
782    }
783
784    /**
785     * Sets the timeout for new connections
786     *
787     * @param int $seconds Number of seconds
788     * @param int $microseconds Number of microseconds
789     */
790    public function set_timeout( $seconds, $microseconds ) {
791        $this->_timeout_seconds = $seconds;
792        $this->_timeout_microseconds = $microseconds;
793    }
794
795    // }}}
796    // }}}
797    // {{{ private methods
798    // {{{ _close_sock()
799
800    /**
801     * Close the specified socket
802     *
803     * @param string $sock Socket to close
804     *
805     * @access private
806     */
807    function _close_sock( $sock ) {
808        $host = array_search( $sock, $this->_cache_sock );
809        fclose( $this->_cache_sock[$host] );
810        unset( $this->_cache_sock[$host] );
811    }
812
813    // }}}
814    // {{{ _connect_sock()
815
816    /**
817     * Connects $sock to $host, timing out after $timeout
818     *
819     * @param int $sock Socket to connect
820     * @param string $host Host:IP to connect to
821     *
822     * @return bool
823     * @access private
824     */
825    function _connect_sock( &$sock, $host ) {
826        $port = null;
827        $hostAndPort = IPUtils::splitHostAndPort( $host );
828        if ( $hostAndPort ) {
829            $ip = $hostAndPort[0];
830            if ( $hostAndPort[1] ) {
831                $port = $hostAndPort[1];
832            }
833        } else {
834            $ip = $host;
835        }
836        $sock = false;
837        $timeout = $this->_connect_timeout;
838        $errno = $errstr = null;
839        for ( $i = 0; !$sock && $i < $this->_connect_attempts; $i++ ) {
840            // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
841            if ( $this->_persistent == 1 ) {
842                $sock = @pfsockopen( $ip, $port, $errno, $errstr, $timeout );
843            } else {
844                $sock = @fsockopen( $ip, $port, $errno, $errstr, $timeout );
845            }
846        }
847        if ( !$sock ) {
848            $this->_error_log( "Error connecting to $host$errstr" );
849            $this->_dead_host( $host );
850            return false;
851        }
852
853        // Initialise timeout
854        stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
855
856        // If the connection was persistent, flush the read buffer in case there
857        // was a previous incomplete request on this connection
858        if ( $this->_persistent ) {
859            $this->_flush_read_buffer( $sock );
860        }
861        return true;
862    }
863
864    // }}}
865    // {{{ _dead_sock()
866
867    /**
868     * Marks a host as dead until 30-40 seconds in the future
869     *
870     * @param string $sock Socket to mark as dead
871     *
872     * @access private
873     */
874    function _dead_sock( $sock ) {
875        $host = array_search( $sock, $this->_cache_sock );
876        $this->_dead_host( $host );
877    }
878
879    /**
880     * @param string $host
881     */
882    function _dead_host( $host ) {
883        $hostAndPort = IPUtils::splitHostAndPort( $host );
884        if ( $hostAndPort ) {
885            $ip = $hostAndPort[0];
886        } else {
887            $ip = $host;
888        }
889        $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
890        $this->_host_dead[$host] = $this->_host_dead[$ip];
891        unset( $this->_cache_sock[$host] );
892    }
893
894    // }}}
895    // {{{ get_sock()
896
897    /**
898     * get_sock
899     *
900     * @param string $key Key to retrieve value for;
901     *
902     * @return Resource|bool Resource on success, false on failure
903     * @access private
904     */
905    function get_sock( $key ) {
906        if ( !$this->_active ) {
907            return false;
908        }
909
910        if ( $this->_single_sock !== null ) {
911            return $this->sock_to_host( $this->_single_sock );
912        }
913
914        $hv = is_array( $key ) ? intval( $key[0] ) : $this->_hashfunc( $key );
915        if ( $this->_buckets === null ) {
916            $bu = array();
917            foreach ( $this->_servers as $v ) {
918                if ( is_array( $v ) ) {
919                    for ( $i = 0; $i < $v[1]; $i++ ) {
920                        $bu[] = $v[0];
921                    }
922                } else {
923                    $bu[] = $v;
924                }
925            }
926            $this->_buckets = $bu;
927            $this->_bucketcount = count( $bu );
928        }
929
930        $realkey = is_array( $key ) ? $key[1] : $key;
931        for ( $tries = 0; $tries < 20; $tries++ ) {
932            $host = $this->_buckets[$hv % $this->_bucketcount];
933            $sock = $this->sock_to_host( $host );
934            if ( $sock ) {
935                return $sock;
936            }
937            $hv = $this->_hashfunc( $hv . $realkey );
938        }
939
940        return false;
941    }
942
943    // }}}
944    // {{{ _hashfunc()
945
946    /**
947     * Creates a hash integer based on the $key
948     *
949     * @param string $key Key to hash
950     *
951     * @return int Hash value
952     * @access private
953     */
954    function _hashfunc( $key ) {
955        # Hash function must be in [0,0x7ffffff]
956        # We take the first 31 bits of the MD5 hash, which unlike the hash
957        # function used in a previous version of this client, works
958        return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
959    }
960
961    // }}}
962    // {{{ _incrdecr()
963
964    /**
965     * Perform increment/decrement on $key
966     *
967     * @param string $cmd Command to perform
968     * @param string|array $key Key to perform it on
969     * @param int $amt Amount to adjust
970     *
971     * @return int New value of $key
972     * @access private
973     */
974    function _incrdecr( $cmd, $key, $amt = 1 ) {
975        $this->_last_cmd_status = BagOStuff::ERR_NONE;
976
977        if ( !$this->_active ) {
978            $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
979
980            return null;
981        }
982
983        $sock = $this->get_sock( $key );
984        if ( !$sock ) {
985            $this->_last_cmd_status = BagOStuff::ERR_UNREACHABLE;
986
987            return null;
988        }
989
990        $key = is_array( $key ) ? $key[1] : $key;
991        if ( isset( $this->stats[$cmd] ) ) {
992            $this->stats[$cmd]++;
993        } else {
994            $this->stats[$cmd] = 1;
995        }
996        if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
997            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
998
999            return null;
1000        }
1001
1002        $line = $this->_fgets( $sock );
1003        if ( $this->_debug ) {
1004            $this->_debugprint( "$cmd($key): $line" );
1005        }
1006
1007        $match = array();
1008        if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
1009            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
1010
1011            return null;
1012        }
1013
1014        return (int)$match[1];
1015    }
1016
1017    // }}}
1018    // {{{ _load_items()
1019
1020    /**
1021     * Load items into $ret from $sock
1022     *
1023     * @param Resource $sock Socket to read from
1024     * @param array $ret returned values
1025     * @param float $casToken [optional]
1026     * @return bool True for success, false for failure
1027     *
1028     * @access private
1029     */
1030    function _load_items( $sock, &$ret, &$casToken = null ) {
1031        $results = array();
1032
1033        while ( 1 ) {
1034            $decl = $this->_fgets( $sock );
1035
1036            if ( $decl === false ) {
1037                /*
1038                 * If nothing can be read, something is wrong because we know exactly when
1039                 * to stop reading (right after "END") and we return right after that.
1040                 */
1041                return false;
1042            } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+)(?: (\d+))?$/', $decl, $match ) ) {
1043                /*
1044                 * Read all data returned. This can be either one or multiple values.
1045                 * Save all that data (in an array) to be processed later: we'll first
1046                 * want to continue reading until "END" before doing anything else,
1047                 * to make sure that we don't leave our client in a state where it's
1048                 * output is not yet fully read.
1049                 */
1050                $results[] = array(
1051                    $match[1], // rkey
1052                    $match[2], // flags
1053                    $match[3], // len
1054                    $match[4] ?? null, // casToken (appears with "gets" but not "get")
1055                    $this->_fread( $sock, $match[3] + 2 ), // data
1056                );
1057            } elseif ( $decl == "END" ) {
1058                /**
1059                 * All data has been read, time to process the data and build
1060                 * meaningful return values.
1061                 */
1062                foreach ( $results as [ $rkey, $flags, /* length */, $casToken, $data ] ) {
1063                    if ( $data === false || !str_ends_with( $data, "\r\n" ) ) {
1064                        $this->_handle_error( $sock,
1065                            'line ending missing from data block from $1' );
1066                        return false;
1067                    }
1068                    $data = substr( $data, 0, -2 );
1069                    $ret[$rkey] = $data;
1070
1071                    if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
1072                        $ret[$rkey] = gzuncompress( $ret[$rkey] );
1073                    }
1074
1075                    /*
1076                     * This unserialize is the exact reason that we only want to
1077                     * process data after having read until "END" (instead of doing
1078                     * this right away): "unserialize" can trigger outside code:
1079                     * in the event that $ret[$rkey] is a serialized object,
1080                     * unserializing it will trigger __wakeup() if present. If that
1081                     * function attempted to read from memcached (while we did not
1082                     * yet read "END"), these 2 calls would collide.
1083                     */
1084                    if ( $flags & self::SERIALIZED ) {
1085                        $ret[$rkey] = $this->unserialize( $ret[$rkey] );
1086                    } elseif ( $flags & self::INTVAL ) {
1087                        $ret[$rkey] = intval( $ret[$rkey] );
1088                    }
1089                }
1090
1091                return true;
1092            } else {
1093                $this->_handle_error( $sock, 'Error parsing response from $1' );
1094                return false;
1095            }
1096        }
1097    }
1098
1099    // }}}
1100    // {{{ _set()
1101
1102    /**
1103     * Performs the requested storage operation to the memcache server
1104     *
1105     * @param string $cmd Command to perform
1106     * @param string $key Key to act on
1107     * @param mixed $val What we need to store
1108     * @param int $exp (optional) Expiration time. This can be a number of seconds
1109     * to cache for (up to 30 days inclusive).  Any timespans of 30 days + 1 second or
1110     * longer must be the timestamp of the time at which the mapping should expire. It
1111     * is safe to use timestamps in all cases, regardless of expiration
1112     * eg: strtotime("+3 hour")
1113     * @param float $casToken [optional]
1114     *
1115     * @return bool
1116     * @access private
1117     */
1118    function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1119        $this->_last_cmd_status = BagOStuff::ERR_NONE;
1120
1121        if ( !$this->_active ) {
1122            $this->_last_cmd_status = BagOStuff::ERR_UNEXPECTED;
1123
1124            return false;
1125        }
1126
1127        $sock = $this->get_sock( $key );
1128        if ( !$sock ) {
1129            $this->_last_cmd_status = BagOStuff::ERR_UNREACHABLE;
1130
1131            return false;
1132        }
1133
1134        if ( isset( $this->stats[$cmd] ) ) {
1135            $this->stats[$cmd]++;
1136        } else {
1137            $this->stats[$cmd] = 1;
1138        }
1139
1140        $flags = 0;
1141
1142        if ( is_int( $val ) ) {
1143            $flags |= self::INTVAL;
1144        } elseif ( !is_scalar( $val ) ) {
1145            $val = $this->serialize( $val );
1146            $flags |= self::SERIALIZED;
1147            if ( $this->_debug ) {
1148                $this->_debugprint( "client: serializing data as it is not scalar" );
1149            }
1150        }
1151
1152        $len = strlen( $val );
1153
1154        if ( $this->_have_zlib && $this->_compress_enable
1155            && $this->_compress_threshold && $len >= $this->_compress_threshold
1156        ) {
1157            $c_val = gzcompress( $val, 9 );
1158            $c_len = strlen( $c_val );
1159
1160            if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
1161                if ( $this->_debug ) {
1162                    $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes", $len, $c_len ) );
1163                }
1164                $val = $c_val;
1165                $len = $c_len;
1166                $flags |= self::COMPRESSED;
1167            }
1168        }
1169
1170        $command = "$cmd $key $flags $exp $len";
1171        if ( $casToken ) {
1172            $command .= " $casToken";
1173        }
1174
1175        if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1176            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
1177
1178            return false;
1179        }
1180
1181        $line = $this->_fgets( $sock );
1182        if ( $this->_debug ) {
1183            $this->_debugprint( sprintf( "%s %s (%s)", $cmd, $key, $line ) );
1184        }
1185
1186        if ( $line === "STORED" ) {
1187            return true;
1188        } elseif ( $line === "NOT_STORED" && $cmd === "set" ) {
1189            // "Not stored" is always used as the mcrouter response with AllAsyncRoute
1190            return true;
1191        }
1192
1193        if ( $line === false ) {
1194            $this->_last_cmd_status = BagOStuff::ERR_NO_RESPONSE;
1195        }
1196
1197        return false;
1198    }
1199
1200    // }}}
1201    // {{{ sock_to_host()
1202
1203    /**
1204     * Returns the socket for the host
1205     *
1206     * @param string $host Host:IP to get socket for
1207     *
1208     * @return Resource|bool IO Stream or false
1209     * @access private
1210     */
1211    function sock_to_host( $host ) {
1212        if ( isset( $this->_cache_sock[$host] ) ) {
1213            return $this->_cache_sock[$host];
1214        }
1215
1216        $sock = null;
1217        $now = time();
1218        $hostAndPort = IPUtils::splitHostAndPort( $host );
1219        if ( $hostAndPort ) {
1220            $ip = $hostAndPort[0];
1221        } else {
1222            $ip = $host;
1223        }
1224        if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1225            isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1226        ) {
1227            return null;
1228        }
1229
1230        if ( !$this->_connect_sock( $sock, $host ) ) {
1231            return null;
1232        }
1233
1234        // Do not buffer writes
1235        stream_set_write_buffer( $sock, 0 );
1236
1237        $this->_cache_sock[$host] = $sock;
1238
1239        return $this->_cache_sock[$host];
1240    }
1241
1242    /**
1243     * @param string $text
1244     */
1245    function _debugprint( $text ) {
1246        $this->_logger->debug( $text );
1247    }
1248
1249    /**
1250     * @param string $text
1251     */
1252    function _error_log( $text ) {
1253        $this->_logger->error( "Memcached error: $text" );
1254    }
1255
1256    /**
1257     * Write to a stream. If there is an error, mark the socket dead.
1258     *
1259     * @param Resource $sock The socket
1260     * @param string $buf The string to write
1261     * @return bool True on success, false on failure
1262     */
1263    function _fwrite( $sock, $buf ) {
1264        $bytesWritten = 0;
1265        $bufSize = strlen( $buf );
1266        while ( $bytesWritten < $bufSize ) {
1267            $result = fwrite( $sock, $buf );
1268            $data = stream_get_meta_data( $sock );
1269            if ( $data['timed_out'] ) {
1270                $this->_handle_error( $sock, 'timeout writing to $1' );
1271                return false;
1272            }
1273            // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1274            if ( $result === false || $result === 0 ) {
1275                $this->_handle_error( $sock, 'error writing to $1' );
1276                return false;
1277            }
1278            $bytesWritten += $result;
1279        }
1280
1281        return true;
1282    }
1283
1284    /**
1285     * Handle an I/O error. Mark the socket dead and log an error.
1286     *
1287     * @param Resource $sock
1288     * @param string $msg
1289     */
1290    function _handle_error( $sock, $msg ) {
1291        $peer = stream_socket_get_name( $sock, true /** remote **/ );
1292        if ( strval( $peer ) === '' ) {
1293            $peer = array_search( $sock, $this->_cache_sock );
1294            if ( $peer === false ) {
1295                $peer = '[unknown host]';
1296            }
1297        }
1298        $msg = str_replace( '$1', $peer, $msg );
1299        $this->_error_log( "$msg" );
1300        $this->_dead_sock( $sock );
1301    }
1302
1303    /**
1304     * Read the specified number of bytes from a stream. If there is an error,
1305     * mark the socket dead.
1306     *
1307     * @param Resource $sock The socket
1308     * @param int $len The number of bytes to read
1309     * @return string|bool The string on success, false on failure.
1310     */
1311    function _fread( $sock, $len ) {
1312        $buf = '';
1313        while ( $len > 0 ) {
1314            $result = fread( $sock, $len );
1315            $data = stream_get_meta_data( $sock );
1316            if ( $data['timed_out'] ) {
1317                $this->_handle_error( $sock, 'timeout reading from $1' );
1318                return false;
1319            }
1320            if ( $result === false ) {
1321                $this->_handle_error( $sock, 'error reading buffer from $1' );
1322                return false;
1323            }
1324            if ( $result === '' ) {
1325                // This will happen if the remote end of the socket is shut down
1326                $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1327                return false;
1328            }
1329            $len -= strlen( $result );
1330            $buf .= $result;
1331        }
1332        return $buf;
1333    }
1334
1335    /**
1336     * Read a line from a stream. If there is an error, mark the socket dead.
1337     * The \r\n line ending is stripped from the response.
1338     *
1339     * @param Resource $sock The socket
1340     * @return string|bool The string on success, false on failure
1341     */
1342    function _fgets( $sock ) {
1343        $result = fgets( $sock );
1344        // fgets() may return a partial line if there is a select timeout after
1345        // a successful recv(), so we have to check for a timeout even if we
1346        // got a string response.
1347        $data = stream_get_meta_data( $sock );
1348        if ( $data['timed_out'] ) {
1349            $this->_handle_error( $sock, 'timeout reading line from $1' );
1350            return false;
1351        }
1352        if ( $result === false ) {
1353            $this->_handle_error( $sock, 'error reading line from $1' );
1354            return false;
1355        }
1356        if ( str_ends_with( $result, "\r\n" ) ) {
1357            $result = substr( $result, 0, -2 );
1358        } elseif ( str_ends_with( $result, "\n" ) ) {
1359            $result = substr( $result, 0, -1 );
1360        } else {
1361            $this->_handle_error( $sock, 'line ending missing in response from $1' );
1362            return false;
1363        }
1364        return $result;
1365    }
1366
1367    /**
1368     * Flush the read buffer of a stream
1369     * @param Resource $f
1370     */
1371    function _flush_read_buffer( $f ) {
1372        if ( !$f ) {
1373            return;
1374        }
1375        $r = array( $f );
1376        $w = null;
1377        $e = null;
1378        $n = stream_select( $r, $w, $e, 0, 0 );
1379        while ( $n == 1 && !feof( $f ) ) {
1380            fread( $f, 1024 );
1381            $r = array( $f );
1382            $w = null;
1383            $e = null;
1384            $n = stream_select( $r, $w, $e, 0, 0 );
1385        }
1386    }
1387
1388    // }}}
1389    // }}}
1390    // }}}
1391}