package.xml0000664000175000017500000001364212211042406013035 0ustar nicolasnicolas redis pecl.php.net PHP extension for interfacing with Redis This extension provides an API for communicating with Redis servers. Nicolas Favre-Felix nff n.favrefelix@gmail.com yes Michael Grunder mgrunder michael.grunder@gmail.com yes 2013-09-02 2.2.4 2.2.4 stable stable PHP ** ** Features / Improvements ** * Randomized reconnect delay for RedisArray @mobli This feature adds an optional parameter when constructing a RedisArray object such that a random delay will be introduced if reconnections are made, mitigating any 'thundering herd' type problems. * Lazy connections to RedisArray servers @mobli By default, RedisArray will attempt to connect to each server you pass in the ring on construction. This feature lets you specify that you would rather have RedisArray only attempt a connection when it needs to get data from a particular node (throughput/performance improvement). * Allow LONG and STRING keys in MGET/MSET * Extended SET options for Redis >= 2.6.12 * Persistent connections and UNIX SOCKET support for RedisArray * Allow aggregates for ZUNION/ZINTER without weights @mheijkoop * Support for SLOWLOG command * Reworked MGET algorithm to run in linear time regardless of key count. * Reworked ZINTERSTORE/ZUNIONSTORE algorithm to run in linear time ** ** Bug fixes ** * C99 Compliance (or rather lack thereof) fix @mobli * Added ZEND_ACC_CTOR and ZEND_ACC_DTOR @euskadi31 * Stop throwing and clearing an exception on connect failure @matmoi * Fix a false positive unit test failure having to do with TTL returns 5.2.0 6.0.0 6.0.0 1.4.0b1 redis stable stable 2.2.4 2.2.4 2013-09-01 ** ** Features / Improvements ** * Randomized reconnect delay for RedisArray @mobli This feature adds an optional parameter when constructing a RedisArray object such that a random delay will be introduced if reconnections are made, mitigating any 'thundering herd' type problems. * Lazy connections to RedisArray servers @mobli By default, RedisArray will attempt to connect to each server you pass in the ring on construction. This feature lets you specify that you would rather have RedisArray only attempt a connection when it needs to get data from a particular node (throughput/performance improvement). * Allow LONG and STRING keys in MGET/MSET * Extended SET options for Redis >= 2.6.12 * Persistent connections and UNIX SOCKET support for RedisArray * Allow aggregates for ZUNION/ZINTER without weights @mheijkoop * Support for SLOWLOG command * Reworked MGET algorithm to run in linear time regardless of key count. * Reworked ZINTERSTORE/ZUNIONSTORE algorithm to run in linear time ** ** Bug fixes ** * C99 Compliance (or rather lack thereof) fix @mobli * Added ZEND_ACC_CTOR and ZEND_ACC_DTOR @euskadi31 * Stop throwing and clearing an exception on connect failure @matmoi * Fix a false positive unit test failure having to do with TTL returns stable stable 2.2.3 2.2.3 2013-04-29 First release to PECL redis-2.2.4/README.markdown0000664000175000017500000025072212211042406015172 0ustar nicolasnicolas# PhpRedis The phpredis extension provides an API for communicating with the [Redis](http://redis.io/) key-value store. It is released under the [PHP License, version 3.01](http://www.php.net/license/3_01.txt). This code has been developed and maintained by Owlient from November 2009 to March 2011. You can send comments, patches, questions [here on github](https://github.com/nicolasff/phpredis/issues) or to n.favrefelix@gmail.com ([@yowgi](http://twitter.com/yowgi)). # Table of contents ----- 1. [Installing/Configuring](#installingconfiguring) * [Installation](#installation) * [Installation on OSX](#installation-on-osx) * [Building on Windows](#building-on-windows) * [PHP Session handler](#php-session-handler) * [Distributed Redis Array](#distributed-redis-array) 1. [Classes and methods](#classes-and-methods) * [Usage](#usage) * [Connection](#connection) * [Server](#server) * [Keys and strings](#keys-and-strings) * [Hashes](#hashes) * [Lists](#lists) * [Sets](#sets) * [Sorted sets](#sorted-sets) * [Pub/sub](#pubsub) * [Transactions](#transactions) * [Scripting](#scripting) * [Introspection](#introspection) ----- # Installing/Configuring ----- Everything you should need to install PhpRedis on your system. ## Installation ~~~ phpize ./configure [--enable-redis-igbinary] make && make install ~~~ If you would like phpredis to serialize your data using the igbinary library, run configure with `--enable-redis-igbinary`. `make install` copies `redis.so` to an appropriate location, but you still need to enable the module in the PHP config file. To do so, either edit your php.ini or add a redis.ini file in `/etc/php5/conf.d` with the following contents: `extension=redis.so`. You can generate a debian package for PHP5, accessible from Apache 2 by running `./mkdeb-apache2.sh` or with `dpkg-buildpackage` or `svn-buildpackage`. This extension exports a single class, [Redis](#class-redis) (and [RedisException](#class-redisexception) used in case of errors). Check out https://github.com/ukko/phpredis-phpdoc for a PHP stub that you can use in your IDE for code completion. ## Installation on OSX If the install fails on OSX, type the following commands in your shell before trying again: ~~~ MACOSX_DEPLOYMENT_TARGET=10.6 CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch i386 -arch x86_64 -bind_at_load" export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET ~~~ If that still fails and you are running Zend Server CE, try this right before "make": `./configure CFLAGS="-arch i386"`. Taken from [Compiling phpredis on Zend Server CE/OSX ](http://www.tumblr.com/tagged/phpredis). See also: [Install Redis & PHP Extension PHPRedis with Macports](http://www.lecloud.net/post/3378834922/install-redis-php-extension-phpredis-with-macports). ## PHP Session handler phpredis can be used to store PHP sessions. To do this, configure `session.save_handler` and `session.save_path` in your php.ini to tell phpredis where to store the sessions: ~~~ session.save_handler = redis session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2" ~~~ `session.save_path` can have a simple `host:port` format too, but you need to provide the `tcp://` scheme if you want to use the parameters. The following parameters are available: * weight (integer): the weight of a host is used in comparison with the others in order to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, *host1* stores 20% of all the sessions (1/(1+2+2)) while *host2* and *host3* each store 40% (2/1+2+2). The target host is determined once and for all at the start of the session, and doesn't change. The default weight is 1. * timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds). * persistent (integer, should be 1 or 0): defines if a persistent connection should be used. **(experimental setting)** * prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored. The key is composed of the prefix followed by the session ID. * auth (string, empty by default): used to authenticate with the server prior to sending commands. * database (integer): selects a different database. Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime". You can change it with [`ini_set()`](http://php.net/ini_set). The session handler requires a version of Redis with the `SETEX` command (at least 2.0). phpredis can also connect to a unix domain socket: `session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0`. ## Building on Windows See [instructions from @char101](https://github.com/nicolasff/phpredis/issues/213#issuecomment-11361242) on how to build phpredis on Windows. ## Distributed Redis Array See [dedicated page](https://github.com/nicolasff/phpredis/blob/master/arrays.markdown#readme). # Classes and methods ----- ## Usage 1. [Class Redis](#class-redis) 1. [Class RedisException](#class-redisexception) 1. [Predefined constants](#predefined-constants) ### Class Redis ----- _**Description**_: Creates a Redis client ##### *Example* ~~~ $redis = new Redis(); ~~~ ### Class RedisException ----- phpredis throws a [RedisException](#class-redisexception) object if it can't reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return `FALSE`. ### Predefined constants ----- _**Description**_: Available Redis Constants Redis data types, as returned by [type](#type) ~~~ Redis::REDIS_STRING - String Redis::REDIS_SET - Set Redis::REDIS_LIST - List Redis::REDIS_ZSET - Sorted set Redis::REDIS_HASH - Hash Redis::REDIS_NOT_FOUND - Not found / other ~~~ @TODO: OPT_SERIALIZER, AFTER, BEFORE,... ## Connection 1. [connect, open](#connect-open) - Connect to a server 1. [pconnect, popen](#pconnect-popen) - Connect to a server (persistent) 1. [auth](#auth) - Authenticate to the server 1. [select](#select) - Change the selected database for the current connection 1. [close](#close) - Close the connection 1. [setOption](#setoption) - Set client option 1. [getOption](#getoption) - Get client option 1. [ping](#ping) - Ping the server 1. [echo](#echo) - Echo the given string ### connect, open ----- _**Description**_: Connects to a Redis instance. ##### *Parameters* *host*: string. can be a host, or the path to a unix domain socket *port*: int, optional *timeout*: float, value in seconds (optional, default is 0 meaning unlimited) *reserved*: should be NULL if retry_interval is specified *retry_interval*: int, value in milliseconds (optional) ##### *Return value* *BOOL*: `TRUE` on success, `FALSE` on error. ##### *Example* ~~~ $redis->connect('127.0.0.1', 6379); $redis->connect('127.0.0.1'); // port 6379 by default $redis->connect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout. $redis->connect('/tmp/redis.sock'); // unix domain socket. $redis->connect('127.0.0.1', 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts. ~~~ ### pconnect, popen ----- _**Description**_: Connects to a Redis instance or reuse a connection already established with `pconnect`/`popen`. The connection will not be closed on `close` or end of request until the php process ends. So be patient on to many open FD's (specially on redis server side) when using persistent connections on many servers connecting to one redis server. Also more than one persistent connection can be made identified by either host + port + timeout or host + persistent_id or unix socket + timeout. This feature is not available in threaded versions. `pconnect` and `popen` then working like their non persistent equivalents. ##### *Parameters* *host*: string. can be a host, or the path to a unix domain socket *port*: int, optional *timeout*: float, value in seconds (optional, default is 0 meaning unlimited) *persistent_id*: string. identity for the requested persistent connection *retry_interval*: int, value in milliseconds (optional) ##### *Return value* *BOOL*: `TRUE` on success, `FALSE` on error. ##### *Example* ~~~ $redis->pconnect('127.0.0.1', 6379); $redis->pconnect('127.0.0.1'); // port 6379 by default - same connection like before. $redis->pconnect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout and would be another connection than the two before. $redis->pconnect('127.0.0.1', 6379, 2.5, 'x'); // x is sent as persistent_id and would be another connection the the three before. $redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before. ~~~ ### auth ----- _**Description**_: Authenticate the connection using a password. *Warning*: The password is sent in plain-text over the network. ##### *Parameters* *STRING*: password ##### *Return value* *BOOL*: `TRUE` if the connection is authenticated, `FALSE` otherwise. ##### *Example* ~~~ $redis->auth('foobared'); ~~~ ### select ----- _**Description**_: Change the selected database for the current connection. ##### *Parameters* *INTEGER*: dbindex, the database number to switch to. ##### *Return value* `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* See method for example: [move](#move) ### close ----- _**Description**_: Disconnects from the Redis instance, except when `pconnect` is used. ### setOption ----- _**Description**_: Set client option. ##### *Parameters* *parameter name* *parameter value* ##### *Return value* *BOOL*: `TRUE` on success, `FALSE` on error. ##### *Example* ~~~ $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // don't serialize data $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // use igBinary serialize/unserialize $redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys ~~~ ### getOption ----- _**Description**_: Get client option. ##### *Parameters* *parameter name* ##### *Return value* Parameter value. ##### *Example* ~~~ $redis->getOption(Redis::OPT_SERIALIZER); // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY. ~~~ ### ping ----- _**Description**_: Check the current connection status ##### *Parameters* (none) ##### *Return value* *STRING*: `+PONG` on success. Throws a [RedisException](#class-redisexception) object on connectivity error, as described above. ### echo ----- _**Description**_: Sends a string to Redis, which replies with the same string ##### *Parameters* *STRING*: The message to send. ##### *Return value* *STRING*: the same message. ## Server 1. [bgrewriteaof](#bgrewriteaof) - Asynchronously rewrite the append-only file 1. [bgsave](#bgsave) - Asynchronously save the dataset to disk (in background) 1. [config](#config) - Get or Set the Redis server configuration parameters 1. [dbSize](#dbsize) - Return the number of keys in selected database 1. [flushAll](#flushall) - Remove all keys from all databases 1. [flushDB](#flushdb) - Remove all keys from the current database 1. [info](#info) - Get information and statistics about the server 1. [lastSave](#lastsave) - Get the timestamp of the last disk save 1. [resetStat](#resetstat) - Reset the stats returned by [info](#info) method. 1. [save](#save) - Synchronously save the dataset to disk (wait to complete) 1. [slaveof](#slaveof) - Make the server a slave of another instance, or promote it to master 1. [time](#time) - Return the current server time 1. [slowlog](#slowlog) - Access the Redis slowlog entries ### bgrewriteaof ----- _**Description**_: Start the background rewrite of AOF (Append-Only File) ##### *Parameters* None. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->bgrewriteaof(); ~~~ ### bgsave ----- _**Description**_: Asynchronously save the dataset to disk (in background) ##### *Parameters* None. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. If a save is already running, this command will fail and return `FALSE`. ##### *Example* ~~~ $redis->bgSave(); ~~~ ### config ----- _**Description**_: Get or Set the Redis server configuration parameters. ##### *Parameters* *operation* (string) either `GET` or `SET` *key* string for `SET`, glob-pattern for `GET`. See http://redis.io/commands/config-get for examples. *value* optional string (only for `SET`) ##### *Return value* *Associative array* for `GET`, key -> value *bool* for `SET` ##### *Examples* ~~~ $redis->config("GET", "*max-*-entries*"); $redis->config("SET", "dir", "/var/run/redis/dumps/"); ~~~ ### dbSize ----- _**Description**_: Return the number of keys in selected database. ##### *Parameters* None. ##### *Return value* *INTEGER*: DB size, in number of keys. ##### *Example* ~~~ $count = $redis->dbSize(); echo "Redis has $count keys\n"; ~~~ ### flushAll ----- _**Description**_: Remove all keys from all databases. ##### *Parameters* None. ##### *Return value* *BOOL*: Always `TRUE`. ##### *Example* ~~~ $redis->flushAll(); ~~~ ### flushDB ----- _**Description**_: Remove all keys from the current database. ##### *Parameters* None. ##### *Return value* *BOOL*: Always `TRUE`. ##### *Example* ~~~ $redis->flushDB(); ~~~ ### info ----- _**Description**_: Get information and statistics about the server Returns an associative array that provides information about the server. Passing no arguments to INFO will call the standard REDIS INFO command, which returns information such as the following: * redis_version * arch_bits * uptime_in_seconds * uptime_in_days * connected_clients * connected_slaves * used_memory * changes_since_last_save * bgsave_in_progress * last_save_time * total_connections_received * total_commands_processed * role You can pass a variety of options to INFO ([per the Redis documentation](http://redis.io/commands/info)), which will modify what is returned. ##### *Parameters* *option*: The option to provide redis (e.g. "COMMANDSTATS", "CPU") ##### *Example* ~~~ $redis->info(); /* standard redis INFO command */ $redis->info("COMMANDSTATS"); /* Information on the commands that have been run (>=2.6 only) $redis->info("CPU"); /* just CPU information from Redis INFO */ ~~~ ### lastSave ----- _**Description**_: Returns the timestamp of the last disk save. ##### *Parameters* None. ##### *Return value* *INT*: timestamp. ##### *Example* ~~~ $redis->lastSave(); ~~~ ### resetStat ----- _**Description**_: Reset the stats returned by [info](#info) method. These are the counters that are reset: * Keyspace hits * Keyspace misses * Number of commands processed * Number of connections received * Number of expired keys ##### *Parameters* None. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->resetStat(); ~~~ ### save ----- _**Description**_: Synchronously save the dataset to disk (wait to complete) ##### *Parameters* None. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. If a save is already running, this command will fail and return `FALSE`. ##### *Example* ~~~ $redis->save(); ~~~ ### slaveof ----- _**Description**_: Changes the slave status ##### *Parameters* Either host (string) and port (int), or no parameter to stop being a slave. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->slaveof('10.0.1.7', 6379); /* ... */ $redis->slaveof(); ~~~ ### time ----- _**Description**_: Return the current server time. ##### *Parameters* (none) ##### *Return value* If successfull, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds. ##### *Examples* ~~~ $redis->time(); ~~~ ### slowlog ----- _**Description**_: Access the Redis slowlog ##### *Parameters* *Operation* (string): This can be either `GET`, `LEN`, or `RESET` *Length* (integer), optional: If executing a `SLOWLOG GET` command, you can pass an optional length. ##### ##### *Return value* The return value of SLOWLOG will depend on which operation was performed. SLOWLOG GET: Array of slowlog entries, as provided by Redis SLOGLOG LEN: Integer, the length of the slowlog SLOWLOG RESET: Boolean, depending on success ##### ##### *Examples* ~~~ // Get ten slowlog entries $redis->slowlog('get', 10); // Get the default number of slowlog entries $redis->slowlog('get'); // Reset our slowlog $redis->slowlog('reset'); // Retrieve slowlog length $redis->slowlog('len'); ~~~ ## Keys and Strings ### Strings ----- * [append](#append) - Append a value to a key * [bitcount](#bitcount) - Count set bits in a string * [bitop](#bitop) - Perform bitwise operations between strings * [decr, decrBy](#decr-decrby) - Decrement the value of a key * [get](#get) - Get the value of a key * [getBit](#getbit) - Returns the bit value at offset in the string value stored at key * [getRange](#getrange) - Get a substring of the string stored at a key * [getSet](#getset) - Set the string value of a key and return its old value * [incr, incrBy](#incr-incrby) - Increment the value of a key * [incrByFloat](#incrbyfloat) - Increment the float value of a key by the given amount * [mGet, getMultiple](#mget-getmultiple) - Get the values of all the given keys * [mSet, mSetNX](#mset-msetnx) - Set multiple keys to multiple values * [set](#set) - Set the string value of a key * [setBit](#setbit) - Sets or clears the bit at offset in the string value stored at key * [setex, psetex](#setex-psetex) - Set the value and expiration of a key * [setnx](#setnx) - Set the value of a key, only if the key does not exist * [setRange](#setrange) - Overwrite part of a string at key starting at the specified offset * [strlen](#strlen) - Get the length of the value stored in a key ### Keys ----- * [del, delete](#del-delete) - Delete a key * [dump](#dump) - Return a serialized version of the value stored at the specified key. * [exists](#exists) - Determine if a key exists * [expire, setTimeout, pexpire](#expire-settimeout-pexpire) - Set a key's time to live in seconds * [expireAt, pexpireAt](#expireat-pexpireat) - Set the expiration for a key as a UNIX timestamp * [keys, getKeys](#keys-getkeys) - Find all keys matching the given pattern * [migrate](#migrate) - Atomically transfer a key from a Redis instance to another one * [move](#move) - Move a key to another database * [object](#object) - Inspect the internals of Redis objects * [persist](#persist) - Remove the expiration from a key * [randomKey](#randomkey) - Return a random key from the keyspace * [rename, renameKey](#rename-renamekey) - Rename a key * [renameNx](#renamenx) - Rename a key, only if the new key does not exist * [type](#type) - Determine the type stored at key * [sort](#sort) - Sort the elements in a list, set or sorted set * [ttl, pttl](#ttl-pttl) - Get the time to live for a key * [restore](#restore) - Create a key using the provided serialized value, previously obtained with [dump](#dump). ----- ### get ----- _**Description**_: Get the value related to the specified key ##### *Parameters* *key* ##### *Return value* *String* or *Bool*: If key didn't exist, `FALSE` is returned. Otherwise, the value related to this key is returned. ##### *Examples* ~~~ $redis->get('key'); ~~~ ### set ----- _**Description**_: Set the string value in argument as value of the key. If you're using Redis >= 2.6.12, you can pass extended options as explained below ##### *Parameters* *Key* *Value* *Timeout or Options Array* (optional). If you pass an integer, phpredis will redirect to SETEX, and will try to use Redis >= 2.6.12 extended options if you pass an array with valid values ##### *Return value* *Bool* `TRUE` if the command is successful. ##### *Examples* ~~~ // Simple key -> value set $redis->set('key', 'value'); // Will redirect, and actually make an SETEX call $redis->set('key','value', 10); // Will set the key, if it doesn't exist, with a ttl of 10 seconds $redis->set('key', 'value', Array('nx', 'ex'=>10); // Will set a key, if it does exist, with a ttl of 1000 miliseconds $redis->set('key', 'value', Array('xx', 'px'=>1000); ~~~ ### setex, psetex ----- _**Description**_: Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds. ##### *Parameters* *Key* *TTL* *Value* ##### *Return value* *Bool* `TRUE` if the command is successful. ##### *Examples* ~~~ $redis->setex('key', 3600, 'value'); // sets key → value, with 1h TTL. $redis->psetex('key', 100, 'value'); // sets key → value, with 0.1 sec TTL. ~~~ ### setnx ----- _**Description**_: Set the string value in argument as value of the key if the key doesn't already exist in the database. ##### *Parameters* *key* *value* ##### *Return value* *Bool* `TRUE` in case of success, `FALSE` in case of failure. ##### *Examples* ~~~ $redis->setnx('key', 'value'); /* return TRUE */ $redis->setnx('key', 'value'); /* return FALSE */ ~~~ ### del, delete ----- _**Description**_: Remove specified keys. ##### *Parameters* An array of keys, or an undefined number of parameters, each a key: *key1* *key2* *key3* ... *keyN* ##### *Return value* *Long* Number of keys deleted. ##### *Examples* ~~~ $redis->set('key1', 'val1'); $redis->set('key2', 'val2'); $redis->set('key3', 'val3'); $redis->set('key4', 'val4'); $redis->delete('key1', 'key2'); /* return 2 */ $redis->delete(array('key3', 'key4')); /* return 2 */ ~~~ ### exists ----- _**Description**_: Verify if the specified key exists. ##### *Parameters* *key* ##### *Return value* *BOOL*: If the key exists, return `TRUE`, otherwise return `FALSE`. ##### *Examples* ~~~ $redis->set('key', 'value'); $redis->exists('key'); /* TRUE */ $redis->exists('NonExistingKey'); /* FALSE */ ~~~ ### incr, incrBy ----- _**Description**_: Increment the number stored at key by one. If the second argument is filled, it will be used as the integer value of the increment. ##### *Parameters* *key* *value*: value that will be added to key (only for incrBy) ##### *Return value* *INT* the new value ##### *Examples* ~~~ $redis->incr('key1'); /* key1 didn't exists, set to 0 before the increment */ /* and now has the value 1 */ $redis->incr('key1'); /* 2 */ $redis->incr('key1'); /* 3 */ $redis->incr('key1'); /* 4 */ $redis->incrBy('key1', 10); /* 14 */ ~~~ ### incrByFloat ----- _**Description**_: Increment the key with floating point precision. ##### *Parameters* *key* *value*: (float) value that will be added to the key ##### *Return value* *FLOAT* the new value ##### *Examples* ~~~ $redis->incrByFloat('key1', 1.5); /* key1 didn't exist, so it will now be 1.5 */ $redis->incrByFloat('key1', 1.5); /* 3 */ $redis->incrByFloat('key1', -1.5); /* 1.5 */ $redis->incrByFloat('key1', 2.5); /* 3.5 */ ~~~ ### decr, decrBy ----- _**Description**_: Decrement the number stored at key by one. If the second argument is filled, it will be used as the integer value of the decrement. ##### *Parameters* *key* *value*: value that will be substracted to key (only for decrBy) ##### *Return value* *INT* the new value ##### *Examples* ~~~ $redis->decr('key1'); /* key1 didn't exists, set to 0 before the increment */ /* and now has the value -1 */ $redis->decr('key1'); /* -2 */ $redis->decr('key1'); /* -3 */ $redis->decrBy('key1', 10); /* -13 */ ~~~ ### mGet, getMultiple ----- _**Description**_: Get the values of all the specified keys. If one or more keys dont exist, the array will contain `FALSE` at the position of the key. ##### *Parameters* *Array*: Array containing the list of the keys ##### *Return value* *Array*: Array containing the values related to keys in argument ##### *Examples* ~~~ $redis->set('key1', 'value1'); $redis->set('key2', 'value2'); $redis->set('key3', 'value3'); $redis->mGet(array('key1', 'key2', 'key3')); /* array('value1', 'value2', 'value3'); $redis->mGet(array('key0', 'key1', 'key5')); /* array(`FALSE`, 'value2', `FALSE`); ~~~ ### getSet ----- _**Description**_: Sets a value and returns the previous entry at that key. ##### *Parameters* *Key*: key *STRING*: value ##### *Return value* A string, the previous value located at this key. ##### *Example* ~~~ $redis->set('x', '42'); $exValue = $redis->getSet('x', 'lol'); // return '42', replaces x by 'lol' $newValue = $redis->get('x')' // return 'lol' ~~~ ### randomKey ----- _**Description**_: Returns a random key. ##### *Parameters* None. ##### *Return value* *STRING*: an existing key in redis. ##### *Example* ~~~ $key = $redis->randomKey(); $surprise = $redis->get($key); // who knows what's in there. ~~~ ### move ----- _**Description**_: Moves a key to a different database. ##### *Parameters* *Key*: key, the key to move. *INTEGER*: dbindex, the database number to move the key to. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->select(0); // switch to DB 0 $redis->set('x', '42'); // write 42 to x $redis->move('x', 1); // move to DB 1 $redis->select(1); // switch to DB 1 $redis->get('x'); // will return 42 ~~~ ### rename, renameKey ----- _**Description**_: Renames a key. ##### *Parameters* *STRING*: srckey, the key to rename. *STRING*: dstkey, the new name for the key. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->set('x', '42'); $redis->rename('x', 'y'); $redis->get('y'); // → 42 $redis->get('x'); // → `FALSE` ~~~ ### renameNx ----- _**Description**_: Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx. ### expire, setTimeout, pexpire ----- _**Description**_: Sets an expiration date (a timeout) on an item. pexpire requires a TTL in milliseconds. ##### *Parameters* *Key*: key. The key that will disappear. *Integer*: ttl. The key's remaining Time To Live, in seconds. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->set('x', '42'); $redis->setTimeout('x', 3); // x will disappear in 3 seconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired. ~~~ ### expireAt, pexpireAt ----- _**Description**_: Sets an expiration date (a timestamp) on an item. pexpireAt requires a timestamp in milliseconds. ##### *Parameters* *Key*: key. The key that will disappear. *Integer*: Unix timestamp. The key's date of death, in seconds from Epoch time. ##### *Return value* *BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->set('x', '42'); $now = time(NULL); // current timestamp $redis->expireAt('x', $now + 3); // x will disappear in 3 seconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired. ~~~ ### keys, getKeys ----- _**Description**_: Returns the keys that match a certain pattern. ##### *Parameters* *STRING*: pattern, using '*' as a wildcard. ##### *Return value* *Array of STRING*: The keys that match a certain pattern. ##### *Example* ~~~ $allKeys = $redis->keys('*'); // all keys will match this. $keyWithUserPrefix = $redis->keys('user*'); ~~~ ### object ----- _**Description**_: Describes the object pointed to by a key. ##### *Parameters* The information to retrieve (string) and the key (string). Info can be one of the following: * "encoding" * "refcount" * "idletime" ##### *Return value* *STRING* for "encoding", *LONG* for "refcount" and "idletime", `FALSE` if the key doesn't exist. ##### *Example* ~~~ $redis->object("encoding", "l"); // → ziplist $redis->object("refcount", "l"); // → 1 $redis->object("idletime", "l"); // → 400 (in seconds, with a precision of 10 seconds). ~~~ ### type ----- _**Description**_: Returns the type of data pointed by a given key. ##### *Parameters* *Key*: key ##### *Return value* Depending on the type of the data pointed by the key, this method will return the following value: string: Redis::REDIS_STRING set: Redis::REDIS_SET list: Redis::REDIS_LIST zset: Redis::REDIS_ZSET hash: Redis::REDIS_HASH other: Redis::REDIS_NOT_FOUND ##### *Example* ~~~ $redis->type('key'); ~~~ ### append ----- _**Description**_: Append specified string to the string stored in specified key. ##### *Parameters* *Key* *Value* ##### *Return value* *INTEGER*: Size of the value after the append ##### *Example* ~~~ $redis->set('key', 'value1'); $redis->append('key', 'value2'); /* 12 */ $redis->get('key'); /* 'value1value2' */ ~~~ ### getRange ----- _**Description**_: Return a substring of a larger string *Note*: substr also supported but deprecated in redis. ##### *Parameters* *key* *start* *end* ##### *Return value* *STRING*: the substring ##### *Example* ~~~ $redis->set('key', 'string value'); $redis->getRange('key', 0, 5); /* 'string' */ $redis->getRange('key', -5, -1); /* 'value' */ ~~~ ### setRange ----- _**Description**_: Changes a substring of a larger string. ##### *Parameters* *key* *offset* *value* ##### *Return value* *STRING*: the length of the string after it was modified. ##### *Example* ~~~ $redis->set('key', 'Hello world'); $redis->setRange('key', 6, "redis"); /* returns 11 */ $redis->get('key'); /* "Hello redis" */ ~~~ ### strlen ----- _**Description**_: Get the length of a string value. ##### *Parameters* *key* ##### *Return value* *INTEGER* ##### *Example* ~~~ $redis->set('key', 'value'); $redis->strlen('key'); /* 5 */ ~~~ ### getBit ----- _**Description**_: Return a single bit out of a larger string ##### *Parameters* *key* *offset* ##### *Return value* *LONG*: the bit value (0 or 1) ##### *Example* ~~~ $redis->set('key', "\x7f"); // this is 0111 1111 $redis->getBit('key', 0); /* 0 */ $redis->getBit('key', 1); /* 1 */ ~~~ ### setBit ----- _**Description**_: Changes a single bit of a string. ##### *Parameters* *key* *offset* *value*: bool or int (1 or 0) ##### *Return value* *LONG*: 0 or 1, the value of the bit before it was set. ##### *Example* ~~~ $redis->set('key', "*"); // ord("*") = 42 = 0x2f = "0010 1010" $redis->setBit('key', 5, 1); /* returns 0 */ $redis->setBit('key', 7, 1); /* returns 0 */ $redis->get('key'); /* chr(0x2f) = "/" = b("0010 1111") */ ~~~ ### bitop ----- _**Description**_: Bitwise operation on multiple keys. ##### *Parameters* *operation*: either "AND", "OR", "NOT", "XOR" *ret_key*: return key *key1* *key2...* ##### *Return value* *LONG*: The size of the string stored in the destination key. ### bitcount ----- _**Description**_: Count bits in a string. ##### *Parameters* *key* ##### *Return value* *LONG*: The number of bits set to 1 in the value behind the input key. ### sort ----- _**Description**_: Sort the elements in a list, set or sorted set. ##### *Parameters* *Key*: key *Options*: array(key => value, ...) - optional, with the following keys and values: ~~~ 'by' => 'some_pattern_*', 'limit' => array(0, 1), 'get' => 'some_other_pattern_*' or an array of patterns, 'sort' => 'asc' or 'desc', 'alpha' => TRUE, 'store' => 'external-key' ~~~ ##### *Return value* An array of values, or a number corresponding to the number of elements stored if that was used. ##### *Example* ~~~ $redis->delete('s'); $redis->sadd('s', 5); $redis->sadd('s', 4); $redis->sadd('s', 2); $redis->sadd('s', 1); $redis->sadd('s', 3); var_dump($redis->sort('s')); // 1,2,3,4,5 var_dump($redis->sort('s', array('sort' => 'desc'))); // 5,4,3,2,1 var_dump($redis->sort('s', array('sort' => 'desc', 'store' => 'out'))); // (int)5 ~~~ ### ttl, pttl ----- _**Description**_: Returns the time to live left for a given key in seconds (ttl), or milliseconds (pttl). ##### *Parameters* *Key*: key ##### *Return value* *LONG*: The time to live in seconds. If the key has no ttl, `-1` will be returned, and `-2` if the key doesn't exist. ##### *Example* ~~~ $redis->ttl('key'); ~~~ ### persist ----- _**Description**_: Remove the expiration timer from a key. ##### *Parameters* *Key*: key ##### *Return value* *BOOL*: `TRUE` if a timeout was removed, `FALSE` if the key didn’t exist or didn’t have an expiration timer. ##### *Example* ~~~ $redis->persist('key'); ~~~ ### mset, msetnx ----- _**Description**_: Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX). ##### *Parameters* *Pairs*: array(key => value, ...) ##### *Return value* *Bool* `TRUE` in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->mset(array('key0' => 'value0', 'key1' => 'value1')); var_dump($redis->get('key0')); var_dump($redis->get('key1')); ~~~ Output: ~~~ string(6) "value0" string(6) "value1" ~~~ ### dump ----- _**Description**_: Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data that comes out of DUMP is a binary representation of the key as Redis stores it. ##### *Parameters* *key* string ##### *Return value* The Redis encoded value of the key, or FALSE if the key doesn't exist ##### *Examples* ~~~ $redis->set('foo', 'bar'); $val = $redis->dump('foo'); // $val will be the Redis encoded key value ~~~ ### restore ----- _**Description**_: Restore a key from the result of a DUMP operation. ##### *Parameters* *key* string. The key name *ttl* integer. How long the key should live (if zero, no expire will be set on the key) *value* string (binary). The Redis encoded key value (from DUMP) ##### *Examples* ~~~ $redis->set('foo', 'bar'); $val = $redis->dump('foo'); $redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo' ~~~ ### migrate ----- _**Description**_: Migrates a key to a different Redis instance. ##### *Parameters* *host* string. The destination host *port* integer. The TCP port to connect to. *key* string. The key to migrate. *destination-db* integer. The target DB. *timeout* integer. The maximum amount of time given to this transfer. ##### *Examples* ~~~ $redis->migrate('backup', 6379, 'foo', 0, 3600); ~~~ ## Hashes * [hDel](#hdel) - Delete one or more hash fields * [hExists](#hexists) - Determine if a hash field exists * [hGet](#hget) - Get the value of a hash field * [hGetAll](#hgetall) - Get all the fields and values in a hash * [hIncrBy](#hincrby) - Increment the integer value of a hash field by the given number * [hIncrByFloat](#hincrbyfloat) - Increment the float value of a hash field by the given amount * [hKeys](#hkeys) - Get all the fields in a hash * [hLen](#hlen) - Get the number of fields in a hash * [hMGet](#hmget) - Get the values of all the given hash fields * [hMSet](#hmset) - Set multiple hash fields to multiple values * [hSet](#hset) - Set the string value of a hash field * [hSetNx](#hsetnx) - Set the value of a hash field, only if the field does not exist * [hVals](#hvals) - Get all the values in a hash ### hSet ----- _**Description**_: Adds a value to the hash stored at key. If this value is already in the hash, `FALSE` is returned. ##### *Parameters* *key* *hashKey* *value* ##### *Return value* *LONG* `1` if value didn't exist and was added successfully, `0` if the value was already present and was replaced, `FALSE` if there was an error. ##### *Example* ~~~ $redis->delete('h') $redis->hSet('h', 'key1', 'hello'); /* 1, 'key1' => 'hello' in the hash at "h" */ $redis->hGet('h', 'key1'); /* returns "hello" */ $redis->hSet('h', 'key1', 'plop'); /* 0, value was replaced. */ $redis->hGet('h', 'key1'); /* returns "plop" */ ~~~ ### hSetNx ----- _**Description**_: Adds a value to the hash stored at key only if this field isn't already in the hash. ##### *Return value* *BOOL* `TRUE` if the field was set, `FALSE` if it was already present. ##### *Example* ~~~ $redis->delete('h') $redis->hSetNx('h', 'key1', 'hello'); /* TRUE, 'key1' => 'hello' in the hash at "h" */ $redis->hSetNx('h', 'key1', 'world'); /* FALSE, 'key1' => 'hello' in the hash at "h". No change since the field wasn't replaced. */ ~~~ ### hGet ----- _**Description**_: Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, `FALSE` is returned. ##### *Parameters* *key* *hashKey* ##### *Return value* *STRING* The value, if the command executed successfully *BOOL* `FALSE` in case of failure ### hLen ----- _**Description**_: Returns the length of a hash, in number of items ##### *Parameters* *key* ##### *Return value* *LONG* the number of items in a hash, `FALSE` if the key doesn't exist or isn't a hash. ##### *Example* ~~~ $redis->delete('h') $redis->hSet('h', 'key1', 'hello'); $redis->hSet('h', 'key2', 'plop'); $redis->hLen('h'); /* returns 2 */ ~~~ ### hDel ----- _**Description**_: Removes a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, `FALSE` is returned. ##### *Parameters* *key* *hashKey* ##### *Return value* *BOOL* `TRUE` in case of success, `FALSE` in case of failure ### hKeys ----- _**Description**_: Returns the keys in a hash, as an array of strings. ##### *Parameters* *Key*: key ##### *Return value* An array of elements, the keys of the hash. This works like PHP's array_keys(). ##### *Example* ~~~ $redis->delete('h'); $redis->hSet('h', 'a', 'x'); $redis->hSet('h', 'b', 'y'); $redis->hSet('h', 'c', 'z'); $redis->hSet('h', 'd', 't'); var_dump($redis->hKeys('h')); ~~~ Output: ~~~ array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" } ~~~ The order is random and corresponds to redis' own internal representation of the set structure. ### hVals ----- _**Description**_: Returns the values in a hash, as an array of strings. ##### *Parameters* *Key*: key ##### *Return value* An array of elements, the values of the hash. This works like PHP's array_values(). ##### *Example* ~~~ $redis->delete('h'); $redis->hSet('h', 'a', 'x'); $redis->hSet('h', 'b', 'y'); $redis->hSet('h', 'c', 'z'); $redis->hSet('h', 'd', 't'); var_dump($redis->hVals('h')); ~~~ Output: ~~~ array(4) { [0]=> string(1) "x" [1]=> string(1) "y" [2]=> string(1) "z" [3]=> string(1) "t" } ~~~ The order is random and corresponds to redis' own internal representation of the set structure. ### hGetAll ----- _**Description**_: Returns the whole hash, as an array of strings indexed by strings. ##### *Parameters* *Key*: key ##### *Return value* An array of elements, the contents of the hash. ##### *Example* ~~~ $redis->delete('h'); $redis->hSet('h', 'a', 'x'); $redis->hSet('h', 'b', 'y'); $redis->hSet('h', 'c', 'z'); $redis->hSet('h', 'd', 't'); var_dump($redis->hGetAll('h')); ~~~ Output: ~~~ array(4) { ["a"]=> string(1) "x" ["b"]=> string(1) "y" ["c"]=> string(1) "z" ["d"]=> string(1) "t" } ~~~ The order is random and corresponds to redis' own internal representation of the set structure. ### hExists ----- _**Description**_: Verify if the specified member exists in a key. ##### *Parameters* *key* *memberKey* ##### *Return value* *BOOL*: If the member exists in the hash table, return `TRUE`, otherwise return `FALSE`. ##### *Examples* ~~~ $redis->hSet('h', 'a', 'x'); $redis->hExists('h', 'a'); /* TRUE */ $redis->hExists('h', 'NonExistingKey'); /* FALSE */ ~~~ ### hIncrBy ----- _**Description**_: Increments the value of a member from a hash by a given amount. ##### *Parameters* *key* *member* *value*: (integer) value that will be added to the member's value ##### *Return value* *LONG* the new value ##### *Examples* ~~~ $redis->delete('h'); $redis->hIncrBy('h', 'x', 2); /* returns 2: h[x] = 2 now. */ $redis->hIncrBy('h', 'x', 1); /* h[x] ← 2 + 1. Returns 3 */ ~~~ ### hIncrByFloat ----- _**Description**_: Increments the value of a hash member by the provided float value ##### *Parameters* *key* *member* *value*: (float) value that will be added to the member's value ##### *Return value* *FLOAT* the new value ##### *Examples* ~~~ $redis->delete('h'); $redis->hIncrByFloat('h','x', 1.5); /* returns 1.5: h[x] = 1.5 now */ $redis->hIncrByFLoat('h', 'x', 1.5); /* returns 3.0: h[x] = 3.0 now */ $redis->hIncrByFloat('h', 'x', -3.0); /* returns 0.0: h[x] = 0.0 now */ ~~~ ### hMSet ----- _**Description**_: Fills in a whole hash. Non-string values are converted to string, using the standard `(string)` cast. NULL values are stored as empty strings. ##### *Parameters* *key* *members*: key → value array ##### *Return value* *BOOL* ##### *Examples* ~~~ $redis->delete('user:1'); $redis->hMset('user:1', array('name' => 'Joe', 'salary' => 2000)); $redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now. ~~~ ### hMGet ----- _**Description**_: Retrieve the values associated to the specified fields in the hash. ##### *Parameters* *key* *memberKeys* Array ##### *Return value* *Array* An array of elements, the values of the specified fields in the hash, with the hash keys as array keys. ##### *Examples* ~~~ $redis->delete('h'); $redis->hSet('h', 'field1', 'value1'); $redis->hSet('h', 'field2', 'value2'); $redis->hmGet('h', array('field1', 'field2')); /* returns array('field1' => 'value1', 'field2' => 'value2') */ ~~~ ## Lists * [blPop, brPop](#blpop-brpop) - Remove and get the first/last element in a list * [brpoplpush](#brpoplpush) - Pop a value from a list, push it to another list and return it * [lIndex, lGet](#lindex-lget) - Get an element from a list by its index * [lInsert](#linsert) - Insert an element before or after another element in a list * [lLen, lSize](#llen-lsize) - Get the length/size of a list * [lPop](#lpop) - Remove and get the first element in a list * [lPush](#lpush) - Prepend one or multiple values to a list * [lPushx](#lpushx) - Prepend a value to a list, only if the list exists * [lRange, lGetRange](#lrange-lgetrange) - Get a range of elements from a list * [lRem, lRemove](#lrem-lremove) - Remove elements from a list * [lSet](#lset) - Set the value of an element in a list by its index * [lTrim, listTrim](#ltrim-listtrim) - Trim a list to the specified range * [rPop](#rpop) - Remove and get the last element in a list * [rpoplpush](#rpoplpush) - Remove the last element in a list, append it to another list and return it (redis >= 1.1) * [rPush](#rpush) - Append one or multiple values to a list * [rPushx](#rpushx) - Append a value to a list, only if the list exists ### blPop, brPop ----- _**Description**_: Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller. Il all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped. ##### *Parameters* *ARRAY* Array containing the keys of the lists *INTEGER* Timeout Or *STRING* Key1 *STRING* Key2 *STRING* Key3 ... *STRING* Keyn *INTEGER* Timeout ##### *Return value* *ARRAY* array('listName', 'element') ##### *Example* ~~~ /* Non blocking feature */ $redis->lPush('key1', 'A'); $redis->delete('key2'); $redis->blPop('key1', 'key2', 10); /* array('key1', 'A') */ /* OR */ $redis->blPop(array('key1', 'key2'), 10); /* array('key1', 'A') */ $redis->brPop('key1', 'key2', 10); /* array('key1', 'A') */ /* OR */ $redis->brPop(array('key1', 'key2'), 10); /* array('key1', 'A') */ /* Blocking feature */ /* process 1 */ $redis->delete('key1'); $redis->blPop('key1', 10); /* blocking for 10 seconds */ /* process 2 */ $redis->lPush('key1', 'A'); /* process 1 */ /* array('key1', 'A') is returned*/ ~~~ ### brpoplpush ----- _**Description**_: A blocking version of `rpoplpush`, with an integral timeout in the third parameter. ##### *Parameters* *Key*: srckey *Key*: dstkey *Long*: timeout ##### *Return value* *STRING* The element that was moved in case of success, `FALSE` in case of timeout. ### lIndex, lGet ----- _**Description**_: Return the specified element of the list stored at the specified key. 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ... Return `FALSE` in case of a bad index or a key that doesn't point to a list. ##### *Parameters* *key* *index* ##### *Return value* *String* the element at this index *Bool* `FALSE` if the key identifies a non-string data type, or no value corresponds to this index in the list `Key`. ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lGet('key1', 0); /* 'A' */ $redis->lGet('key1', -1); /* 'C' */ $redis->lGet('key1', 10); /* `FALSE` */ ~~~ ### lInsert ----- _**Description**_: Insert value in the list before or after the pivot value. The parameter options specify the position of the insert (before or after). If the list didn't exists, or the pivot didn't exists, the value is not inserted. ##### *Parameters* *key* *position* Redis::BEFORE | Redis::AFTER *pivot* *value* ##### *Return value* The number of the elements in the list, -1 if the pivot didn't exists. ##### *Example* ~~~ $redis->delete('key1'); $redis->lInsert('key1', Redis::AFTER, 'A', 'X'); /* 0 */ $redis->lPush('key1', 'A'); $redis->lPush('key1', 'B'); $redis->lPush('key1', 'C'); $redis->lInsert('key1', Redis::BEFORE, 'C', 'X'); /* 4 */ $redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C') */ $redis->lInsert('key1', Redis::AFTER, 'C', 'Y'); /* 5 */ $redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C', 'Y') */ $redis->lInsert('key1', Redis::AFTER, 'W', 'value'); /* -1 */ ~~~ ### lPop ----- _**Description**_: Return and remove the first element of the list. ##### *Parameters* *key* ##### *Return value* *STRING* if command executed successfully *BOOL* `FALSE` in case of failure (empty list) ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */ ~~~ ### lPush ----- _**Description**_: Adds the string value to the head (left) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, `FALSE` is returned. ##### *Parameters* *key* *value* String, value to push in key ##### *Return value* *LONG* The new length of the list in case of success, `FALSE` in case of Failure. ##### *Examples* ~~~ $redis->delete('key1'); $redis->lPush('key1', 'C'); // returns 1 $redis->lPush('key1', 'B'); // returns 2 $redis->lPush('key1', 'A'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */ ~~~ ### lPushx ----- _**Description**_: Adds the string value to the head (left) of the list if the list exists. ##### *Parameters* *key* *value* String, value to push in key ##### *Return value* *LONG* The new length of the list in case of success, `FALSE` in case of Failure. ##### *Examples* ~~~ $redis->delete('key1'); $redis->lPushx('key1', 'A'); // returns 0 $redis->lPush('key1', 'A'); // returns 1 $redis->lPushx('key1', 'B'); // returns 2 $redis->lPushx('key1', 'C'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */ ~~~ ### lRange, lGetRange ----- _**Description**_: Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpretated as indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ... ##### *Parameters* *key* *start* *end* ##### *Return value* *Array* containing the values in specified range. ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); $redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */ ~~~ ### lRem, lRemove ----- _**Description**_: Removes the first `count` occurences of the value element from the list. If count is zero, all the matching elements are removed. If count is negative, elements are removed from tail to head. **Note**: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons. ##### *Parameters* *key* *value* *count* ##### *Return value* *LONG* the number of elements to remove *BOOL* `FALSE` if the value identified by key is not a list. ##### *Example* ~~~ $redis->lPush('key1', 'A'); $redis->lPush('key1', 'B'); $redis->lPush('key1', 'C'); $redis->lPush('key1', 'A'); $redis->lPush('key1', 'A'); $redis->lRange('key1', 0, -1); /* array('A', 'A', 'C', 'B', 'A') */ $redis->lRem('key1', 'A', 2); /* 2 */ $redis->lRange('key1', 0, -1); /* array('C', 'B', 'A') */ ~~~ ### lSet ----- _**Description**_: Set the list at index with the new value. ##### *Parameters* *key* *index* *value* ##### *Return value* *BOOL* `TRUE` if the new value is setted. `FALSE` if the index is out of range, or data type identified by key is not a list. ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lGet('key1', 0); /* 'A' */ $redis->lSet('key1', 0, 'X'); $redis->lGet('key1', 0); /* 'X' */ ~~~ ### lTrim, listTrim ----- _**Description**_: Trims an existing list so that it will contain only a specified range of elements. ##### *Parameters* *key* *start* *stop* ##### *Return value* *Array* *Bool* return `FALSE` if the key identify a non-list value. ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); $redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */ $redis->lTrim('key1', 0, 1); $redis->lRange('key1', 0, -1); /* array('A', 'B') */ ~~~ ### rPop ----- _**Description**_: Returns and removes the last element of the list. ##### *Parameters* *key* ##### *Return value* *STRING* if command executed successfully *BOOL* `FALSE` in case of failure (empty list) ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */ ~~~ ### rpoplpush ----- _**Description**_: Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value. (redis >= 1.1) ##### *Parameters* *Key*: srckey *Key*: dstkey ##### *Return value* *STRING* The element that was moved in case of success, `FALSE` in case of failure. ##### *Example* ~~~ $redis->delete('x', 'y'); $redis->lPush('x', 'abc'); $redis->lPush('x', 'def'); $redis->lPush('y', '123'); $redis->lPush('y', '456'); // move the last of x to the front of y. var_dump($redis->rpoplpush('x', 'y')); var_dump($redis->lRange('x', 0, -1)); var_dump($redis->lRange('y', 0, -1)); ~~~ Output: ~~~ string(3) "abc" array(1) { [0]=> string(3) "def" } array(3) { [0]=> string(3) "abc" [1]=> string(3) "456" [2]=> string(3) "123" } ~~~ ### rPush ----- _**Description**_: Adds the string value to the tail (right) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, `FALSE` is returned. ##### *Parameters* *key* *value* String, value to push in key ##### *Return value* *LONG* The new length of the list in case of success, `FALSE` in case of Failure. ##### *Examples* ~~~ $redis->delete('key1'); $redis->rPush('key1', 'A'); // returns 1 $redis->rPush('key1', 'B'); // returns 2 $redis->rPush('key1', 'C'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */ ~~~ ### rPushx ----- _**Description**_: Adds the string value to the tail (right) of the list if the ist exists. `FALSE` in case of Failure. ##### *Parameters* *key* *value* String, value to push in key ##### *Return value* *LONG* The new length of the list in case of success, `FALSE` in case of Failure. ##### *Examples* ~~~ $redis->delete('key1'); $redis->rPushx('key1', 'A'); // returns 0 $redis->rPush('key1', 'A'); // returns 1 $redis->rPushx('key1', 'B'); // returns 2 $redis->rPushx('key1', 'C'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */ ~~~ ### lLen, lSize ----- _**Description**_: Returns the size of a list identified by Key. If the list didn't exist or is empty, the command returns 0. If the data type identified by Key is not a list, the command return `FALSE`. ##### *Parameters* *Key* ##### *Return value* *LONG* The size of the list identified by Key exists. *BOOL* `FALSE` if the data type identified by Key is not list ##### *Example* ~~~ $redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lSize('key1');/* 3 */ $redis->rPop('key1'); $redis->lSize('key1');/* 2 */ ~~~ ## Sets * [sAdd](#sadd) - Add one or more members to a set * [sCard, sSize](#scard-ssize) - Get the number of members in a set * [sDiff](#sdiff) - Subtract multiple sets * [sDiffStore](#sdiffstore) - Subtract multiple sets and store the resulting set in a key * [sInter](#sinter) - Intersect multiple sets * [sInterStore](#sinterstore) - Intersect multiple sets and store the resulting set in a key * [sIsMember, sContains](#sismember-scontains) - Determine if a given value is a member of a set * [sMembers, sGetMembers](#smembers-sgetmembers) - Get all the members in a set * [sMove](#smove) - Move a member from one set to another * [sPop](#spop) - Remove and return a random member from a set * [sRandMember](#srandmember) - Get one or multiple random members from a set * [sRem, sRemove](#srem-sremove) - Remove one or more members from a set * [sUnion](#sunion) - Add multiple sets * [sUnionStore](#sunionstore) - Add multiple sets and store the resulting set in a key ### sAdd ----- _**Description**_: Adds a value to the set value stored at key. If this value is already in the set, `FALSE` is returned. ##### *Parameters* *key* *value* ##### *Return value* *LONG* the number of elements added to the set. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */ $redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2', 'member3'}*/ ~~~ ### sCard, sSize ----- _**Description**_: Returns the cardinality of the set identified by key. ##### *Parameters* *key* ##### *Return value* *LONG* the cardinality of the set identified by key, 0 if the set doesn't exist. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); $redis->sAdd('key1' , 'member2'); $redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sCard('key1'); /* 3 */ $redis->sCard('keyX'); /* 0 */ ~~~ ### sDiff ----- _**Description**_: Performs the difference between N sets and returns it. ##### *Parameters* *Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. ##### *Return value* *Array of strings*: The difference of the first set will all the others. ##### *Example* ~~~ $redis->delete('s0', 's1', 's2'); $redis->sAdd('s0', '1'); $redis->sAdd('s0', '2'); $redis->sAdd('s0', '3'); $redis->sAdd('s0', '4'); $redis->sAdd('s1', '1'); $redis->sAdd('s2', '3'); var_dump($redis->sDiff('s0', 's1', 's2')); ~~~ Return value: all elements of s0 that are neither in s1 nor in s2. ~~~ array(2) { [0]=> string(1) "4" [1]=> string(1) "2" } ~~~ ### sDiffStore ----- _**Description**_: Performs the same action as sDiff, but stores the result in the first key ##### *Parameters* *Key*: dstkey, the key to store the diff into. *Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis ##### *Return value* *INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. ##### *Example* ~~~ $redis->delete('s0', 's1', 's2'); $redis->sAdd('s0', '1'); $redis->sAdd('s0', '2'); $redis->sAdd('s0', '3'); $redis->sAdd('s0', '4'); $redis->sAdd('s1', '1'); $redis->sAdd('s2', '3'); var_dump($redis->sDiffStore('dst', 's0', 's1', 's2')); var_dump($redis->sMembers('dst')); ~~~ Return value: the number of elements of s0 that are neither in s1 nor in s2. ~~~ int(2) array(2) { [0]=> string(1) "4" [1]=> string(1) "2" } ~~~ ### sInter ----- _**Description**_: Returns the members of a set resulting from the intersection of all the sets held at the specified keys. If just a single key is specified, then this command produces the members of this set. If one of the keys is missing, `FALSE` is returned. ##### *Parameters* key1, key2, keyN: keys identifying the different sets on which we will apply the intersection. ##### *Return value* Array, contain the result of the intersection between those keys. If the intersection beteen the different sets is empty, the return value will be empty array. ##### *Examples* ~~~ $redis->sAdd('key1', 'val1'); $redis->sAdd('key1', 'val2'); $redis->sAdd('key1', 'val3'); $redis->sAdd('key1', 'val4'); $redis->sAdd('key2', 'val3'); $redis->sAdd('key2', 'val4'); $redis->sAdd('key3', 'val3'); $redis->sAdd('key3', 'val4'); var_dump($redis->sInter('key1', 'key2', 'key3')); ~~~ Output: ~~~ array(2) { [0]=> string(4) "val4" [1]=> string(4) "val3" } ~~~ ### sInterStore ----- _**Description**_: Performs a sInter command and stores the result in a new set. ##### *Parameters* *Key*: dstkey, the key to store the diff into. *Keys*: key1, key2... keyN. key1..keyN are intersected as in sInter. ##### *Return value* *INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. ##### *Example* ~~~ $redis->sAdd('key1', 'val1'); $redis->sAdd('key1', 'val2'); $redis->sAdd('key1', 'val3'); $redis->sAdd('key1', 'val4'); $redis->sAdd('key2', 'val3'); $redis->sAdd('key2', 'val4'); $redis->sAdd('key3', 'val3'); $redis->sAdd('key3', 'val4'); var_dump($redis->sInterStore('output', 'key1', 'key2', 'key3')); var_dump($redis->sMembers('output')); ~~~ Output: ~~~ int(2) array(2) { [0]=> string(4) "val4" [1]=> string(4) "val3" } ~~~ ### sIsMember, sContains ----- _**Description**_: Checks if `value` is a member of the set stored at the key `key`. ##### *Parameters* *key* *value* ##### *Return value* *BOOL* `TRUE` if `value` is a member of the set at key `key`, `FALSE` otherwise. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); $redis->sAdd('key1' , 'member2'); $redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sIsMember('key1', 'member1'); /* TRUE */ $redis->sIsMember('key1', 'memberX'); /* FALSE */ ~~~ ### sMembers, sGetMembers ----- _**Description**_: Returns the contents of a set. ##### *Parameters* *Key*: key ##### *Return value* An array of elements, the contents of the set. ##### *Example* ~~~ $redis->delete('s'); $redis->sAdd('s', 'a'); $redis->sAdd('s', 'b'); $redis->sAdd('s', 'a'); $redis->sAdd('s', 'c'); var_dump($redis->sMembers('s')); ~~~ Output: ~~~ array(3) { [0]=> string(1) "c" [1]=> string(1) "a" [2]=> string(1) "b" } ~~~ The order is random and corresponds to redis' own internal representation of the set structure. ### sMove ----- _**Description**_: Moves the specified member from the set at srcKey to the set at dstKey. ##### *Parameters* *srcKey* *dstKey* *member* ##### *Return value* *BOOL* If the operation is successful, return `TRUE`. If the srcKey and/or dstKey didn't exist, and/or the member didn't exist in srcKey, `FALSE` is returned. ##### *Example* ~~~ $redis->sAdd('key1' , 'member11'); $redis->sAdd('key1' , 'member12'); $redis->sAdd('key1' , 'member13'); /* 'key1' => {'member11', 'member12', 'member13'}*/ $redis->sAdd('key2' , 'member21'); $redis->sAdd('key2' , 'member22'); /* 'key2' => {'member21', 'member22'}*/ $redis->sMove('key1', 'key2', 'member13'); /* 'key1' => {'member11', 'member12'} */ /* 'key2' => {'member21', 'member22', 'member13'} */ ~~~ ### sPop ----- _**Description**_: Removes and returns a random element from the set value at Key. ##### *Parameters* *key* ##### *Return value* *String* "popped" value *Bool* `FALSE` if set identified by key is empty or doesn't exist. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); $redis->sAdd('key1' , 'member2'); $redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/ $redis->sPop('key1'); /* 'member1', 'key1' => {'member3', 'member2'} */ $redis->sPop('key1'); /* 'member3', 'key1' => {'member2'} */ ~~~ ### sRandMember ----- _**Description**_: Returns a random element from the set value at Key, without removing it. ##### *Parameters* *key* *count* (Integer, optional) ##### *Return value* If no count is provided, a random *String* value from the set will be returned. If a count is provided, an array of values from the set will be returned. Read about the different ways to use the count here: [SRANDMEMBER](http://redis.io/commands/srandmember) *Bool* `FALSE` if set identified by key is empty or doesn't exist. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); $redis->sAdd('key1' , 'member2'); $redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/ // No count $redis->sRandMember('key1'); /* 'member1', 'key1' => {'member3', 'member1', 'member2'} */ $redis->sRandMember('key1'); /* 'member3', 'key1' => {'member3', 'member1', 'member2'} */ // With a count $redis->sRandMember('key1', 3); // Will return an array with all members from the set $redis->sRandMember('key1', 2); // Will an array with 2 members of the set $redis->sRandMember('key1', -100); // Will return an array of 100 elements, picked from our set (with dups) $redis->sRandMember('empty-set', 100); // Will return an empty array $redis->sRandMember('not-a-set', 100); // Will return FALSE ~~~ ### sRem, sRemove ----- _**Description**_: Removes the specified member from the set value stored at key. ##### *Parameters* *key* *member* ##### *Return value* *LONG* The number of elements removed from the set. ##### *Example* ~~~ $redis->sAdd('key1' , 'member1'); $redis->sAdd('key1' , 'member2'); $redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sRem('key1', 'member2', 'member3'); /*return 2. 'key1' => {'member1'} */ ~~~ ### sUnion ----- _**Description**_: Performs the union between N sets and returns it. ##### *Parameters* *Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. ##### *Return value* *Array of strings*: The union of all these sets. ##### *Example* ~~~ $redis->delete('s0', 's1', 's2'); $redis->sAdd('s0', '1'); $redis->sAdd('s0', '2'); $redis->sAdd('s1', '3'); $redis->sAdd('s1', '1'); $redis->sAdd('s2', '3'); $redis->sAdd('s2', '4'); var_dump($redis->sUnion('s0', 's1', 's2')); ~~~ Return value: all elements that are either in s0 or in s1 or in s2. ~~~ array(4) { [0]=> string(1) "3" [1]=> string(1) "4" [2]=> string(1) "1" [3]=> string(1) "2" } ~~~ ### sUnionStore ----- _**Description**_: Performs the same action as sUnion, but stores the result in the first key ##### *Parameters* *Key*: dstkey, the key to store the diff into. *Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. ##### *Return value* *INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. ##### *Example* ~~~ $redis->delete('s0', 's1', 's2'); $redis->sAdd('s0', '1'); $redis->sAdd('s0', '2'); $redis->sAdd('s1', '3'); $redis->sAdd('s1', '1'); $redis->sAdd('s2', '3'); $redis->sAdd('s2', '4'); var_dump($redis->sUnionStore('dst', 's0', 's1', 's2')); var_dump($redis->sMembers('dst')); ~~~ Return value: the number of elements that are either in s0 or in s1 or in s2. ~~~ int(4) array(4) { [0]=> string(1) "3" [1]=> string(1) "4" [2]=> string(1) "1" [3]=> string(1) "2" } ~~~ ## Sorted sets * [zAdd](#zadd) - Add one or more members to a sorted set or update its score if it already exists * [zCard, zSize](#zcard-zsize) - Get the number of members in a sorted set * [zCount](#zcount) - Count the members in a sorted set with scores within the given values * [zIncrBy](#zincrby) - Increment the score of a member in a sorted set * [zInter](#zinter) - Intersect multiple sorted sets and store the resulting sorted set in a new key * [zRange](#zrange) - Return a range of members in a sorted set, by index * [zRangeByScore, zRevRangeByScore](#zrangebyscore-zrevrangebyscore) - Return a range of members in a sorted set, by score * [zRank, zRevRank](#zrank-zrevrank) - Determine the index of a member in a sorted set * [zRem, zDelete](#zrem-zdelete) - Remove one or more members from a sorted set * [zRemRangeByRank, zDeleteRangeByRank](#zremrangebyrank-zdeleterangebyrank) - Remove all members in a sorted set within the given indexes * [zRemRangeByScore, zDeleteRangeByScore](#zremrangebyscore-zdeleterangebyscore) - Remove all members in a sorted set within the given scores * [zRevRange](#zrevrange) - Return a range of members in a sorted set, by index, with scores ordered from high to low * [zScore](#zscore) - Get the score associated with the given member in a sorted set * [zUnion](#zunion) - Add multiple sorted sets and store the resulting sorted set in a new key ### zAdd ----- _**Description**_: Add one or more members to a sorted set or update its score if it already exists ##### *Parameters* *key* *score* : double *value*: string ##### *Return value* *Long* 1 if the element is added. 0 otherwise. ##### *Example* ~~~ $redis->zAdd('key', 1, 'val1'); $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 5, 'val5'); $redis->zRange('key', 0, -1); // array(val0, val1, val5) ~~~ ### zCard, zSize ----- _**Description**_: Returns the cardinality of an ordered set. ##### *Parameters* *key* ##### *Return value* *Long*, the set's cardinality ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zSize('key'); /* 3 */ ~~~ ### zCount ----- _**Description**_: Returns the *number* of elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before `start` or `end` excludes it from the range. +inf and -inf are also valid limits. ##### *Parameters* *key* *start*: string *end*: string ##### *Return value* *LONG* the size of a corresponding zRangeByScore. ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zCount('key', 0, 3); /* 2, corresponding to array('val0', 'val2') */ ~~~ ### zIncrBy ----- _**Description**_: Increments the score of a member from a sorted set by a given amount. ##### *Parameters* *key* *value*: (double) value that will be added to the member's score *member* ##### *Return value* *DOUBLE* the new value ##### *Examples* ~~~ $redis->delete('key'); $redis->zIncrBy('key', 2.5, 'member1'); /* key or member1 didn't exist, so member1's score is to 0 before the increment */ /* and now has the value 2.5 */ $redis->zIncrBy('key', 1, 'member1'); /* 3.5 */ ~~~ ### zInter ----- _**Description**_: Creates an intersection of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument. The third optionnel argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines the `AGGREGATE` option which specify how the results of the union are aggregated. ##### *Parameters* *keyOutput* *arrayZSetKeys* *arrayWeights* *aggregateFunction* Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zInter. ##### *Return value* *LONG* The number of values in the new sorted set. ##### *Example* ~~~ $redis->delete('k1'); $redis->delete('k2'); $redis->delete('k3'); $redis->delete('ko1'); $redis->delete('ko2'); $redis->delete('ko3'); $redis->delete('ko4'); $redis->zAdd('k1', 0, 'val0'); $redis->zAdd('k1', 1, 'val1'); $redis->zAdd('k1', 3, 'val3'); $redis->zAdd('k2', 2, 'val1'); $redis->zAdd('k2', 3, 'val3'); $redis->zInter('ko1', array('k1', 'k2')); /* 2, 'ko1' => array('val1', 'val3') */ $redis->zInter('ko2', array('k1', 'k2'), array(1, 1)); /* 2, 'ko2' => array('val1', 'val3') */ /* Weighted zInter */ $redis->zInter('ko3', array('k1', 'k2'), array(1, 5), 'min'); /* 2, 'ko3' => array('val1', 'val3') */ $redis->zInter('ko4', array('k1', 'k2'), array(1, 5), 'max'); /* 2, 'ko4' => array('val3', 'val1') */ ~~~ ### zRange ----- _**Description**_: Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end]. Start and stop are interpreted as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ... ##### *Parameters* *key* *start*: long *end*: long *withscores*: bool = false ##### *Return value* *Array* containing the values in specified range. ##### *Example* ~~~ $redis->zAdd('key1', 0, 'val0'); $redis->zAdd('key1', 2, 'val2'); $redis->zAdd('key1', 10, 'val10'); $redis->zRange('key1', 0, -1); /* array('val0', 'val2', 'val10') */ // with scores $redis->zRange('key1', 0, -1, true); /* array('val0' => 0, 'val2' => 2, 'val10' => 10) */ ~~~ ### zRangeByScore, zRevRangeByScore ----- _**Description**_: Returns the elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before `start` or `end` excludes it from the range. +inf and -inf are also valid limits. zRevRangeByScore returns the same items in reverse order, when the `start` and `end` parameters are swapped. ##### *Parameters* *key* *start*: string *end*: string *options*: array Two options are available: `withscores => TRUE`, and `limit => array($offset, $count)` ##### *Return value* *Array* containing the values in specified range. ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zRangeByScore('key', 0, 3); /* array('val0', 'val2') */ $redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE); /* array('val0' => 0, 'val2' => 2) */ $redis->zRangeByScore('key', 0, 3, array('limit' => array(1, 1)); /* array('val2') */ $redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE, 'limit' => array(1, 1)); /* array('val2' => 2) */ ~~~ ### zRank, zRevRank ----- _**Description**_: Returns the rank of a given member in the specified sorted set, starting at 0 for the item with the smallest score. zRevRank starts at 0 for the item with the *largest* score. ##### *Parameters* *key* *member* ##### *Return value* *Long*, the item's score. ##### *Example* ~~~ $redis->delete('z'); $redis->zAdd('key', 1, 'one'); $redis->zAdd('key', 2, 'two'); $redis->zRank('key', 'one'); /* 0 */ $redis->zRank('key', 'two'); /* 1 */ $redis->zRevRank('key', 'one'); /* 1 */ $redis->zRevRank('key', 'two'); /* 0 */ ~~~ ### zRem, zDelete ----- _**Description**_: Deletes a specified member from the ordered set. ##### *Parameters* *key* *member* ##### *Return value* *LONG* 1 on success, 0 on failure. ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zDelete('key', 'val2'); $redis->zRange('key', 0, -1); /* array('val0', 'val10') */ ~~~ ### zRemRangeByRank, zDeleteRangeByRank ----- _**Description**_: Deletes the elements of the sorted set stored at the specified key which have rank in the range [start,end]. ##### *Parameters* *key* *start*: LONG *end*: LONG ##### *Return value* *LONG* The number of values deleted from the sorted set ##### *Example* ~~~ $redis->zAdd('key', 1, 'one'); $redis->zAdd('key', 2, 'two'); $redis->zAdd('key', 3, 'three'); $redis->zRemRangeByRank('key', 0, 1); /* 2 */ $redis->zRange('key', 0, -1, array('withscores' => TRUE)); /* array('three' => 3) */ ~~~ ### zRemRangeByScore, zDeleteRangeByScore ----- _**Description**_: Deletes the elements of the sorted set stored at the specified key which have scores in the range [start,end]. ##### *Parameters* *key* *start*: double or "+inf" or "-inf" string *end*: double or "+inf" or "-inf" string ##### *Return value* *LONG* The number of values deleted from the sorted set ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zRemRangeByScore('key', 0, 3); /* 2 */ ~~~ ### zRevRange ----- _**Description**_: Returns the elements of the sorted set stored at the specified key in the range [start, end] in reverse order. start and stop are interpretated as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ... ##### *Parameters* *key* *start*: long *end*: long *withscores*: bool = false ##### *Return value* *Array* containing the values in specified range. ##### *Example* ~~~ $redis->zAdd('key', 0, 'val0'); $redis->zAdd('key', 2, 'val2'); $redis->zAdd('key', 10, 'val10'); $redis->zRevRange('key', 0, -1); /* array('val10', 'val2', 'val0') */ // with scores $redis->zRevRange('key', 0, -1, true); /* array('val10' => 10, 'val2' => 2, 'val0' => 0) */ ~~~ ### zScore ----- _**Description**_: Returns the score of a given member in the specified sorted set. ##### *Parameters* *key* *member* ##### *Return value* *Double* ##### *Example* ~~~ $redis->zAdd('key', 2.5, 'val2'); $redis->zScore('key', 'val2'); /* 2.5 */ ~~~ ### zUnion ----- _**Description**_: Creates an union of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument. The third optionnel argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines the `AGGREGATE` option which specify how the results of the union are aggregated. ##### *Parameters* *keyOutput* *arrayZSetKeys* *arrayWeights* *aggregateFunction* Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zUnion. ##### *Return value* *LONG* The number of values in the new sorted set. ##### *Example* ~~~ $redis->delete('k1'); $redis->delete('k2'); $redis->delete('k3'); $redis->delete('ko1'); $redis->delete('ko2'); $redis->delete('ko3'); $redis->zAdd('k1', 0, 'val0'); $redis->zAdd('k1', 1, 'val1'); $redis->zAdd('k2', 2, 'val2'); $redis->zAdd('k2', 3, 'val3'); $redis->zUnion('ko1', array('k1', 'k2')); /* 4, 'ko1' => array('val0', 'val1', 'val2', 'val3') */ /* Weighted zUnion */ $redis->zUnion('ko2', array('k1', 'k2'), array(1, 1)); /* 4, 'ko2' => array('val0', 'val1', 'val2', 'val3') */ $redis->zUnion('ko3', array('k1', 'k2'), array(5, 1)); /* 4, 'ko3' => array('val0', 'val2', 'val3', 'val1') */ ~~~ ## Pub/sub * [psubscribe](#psubscribe) - Subscribe to channels by pattern * [publish](#publish) - Post a message to a channel * [subscribe](#subscribe) - Subscribe to channels ### psubscribe ----- _**Description**_: Subscribe to channels by pattern ##### *Parameters* *patterns*: An array of patterns to match *callback*: Either a string or an array with an object and method. The callback will get four arguments ($redis, $pattern, $channel, $message) ##### *Example* ~~~ function psubscribe($redis, $pattern, $chan, $msg) { echo "Pattern: $pattern\n"; echo "Channel: $chan\n"; echo "Payload: $msg\n"; } ~~~ ### publish ----- _**Description**_: Publish messages to channels. Warning: this function will probably change in the future. ##### *Parameters* *channel*: a channel to publish to *messsage*: string ##### *Example* ~~~ $redis->publish('chan-1', 'hello, world!'); // send message. ~~~ ### subscribe ----- _**Description**_: Subscribe to channels. Warning: this function will probably change in the future. ##### *Parameters* *channels*: an array of channels to subscribe to *callback*: either a string or an array($instance, 'method_name'). The callback function receives 3 parameters: the redis instance, the channel name, and the message. ##### *Example* ~~~ function f($redis, $chan, $msg) { switch($chan) { case 'chan-1': ... break; case 'chan-2': ... break; case 'chan-2': ... break; } } $redis->subscribe(array('chan-1', 'chan-2', 'chan-3'), 'f'); // subscribe to 3 chans ~~~ ## Transactions 1. [multi, exec, discard](#multi-exec-discard) - Enter and exit transactional mode 2. [watch, unwatch](#watch-unwatch) - Watches a key for modifications by another client. ### multi, exec, discard. ----- _**Description**_: Enter and exit transactional mode. ##### *Parameters* (optional) `Redis::MULTI` or `Redis::PIPELINE`. Defaults to `Redis::MULTI`. A `Redis::MULTI` block of commands runs as a single transaction; a `Redis::PIPELINE` block is simply transmitted faster to the server, but without any guarantee of atomicity. `discard` cancels a transaction. ##### *Return value* `multi()` returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object until `exec()` is called. ##### *Example* ~~~ $ret = $redis->multi() ->set('key1', 'val1') ->get('key1') ->set('key2', 'val2') ->get('key2') ->exec(); /* $ret == array( 0 => TRUE, 1 => 'val1', 2 => TRUE, 3 => 'val2'); */ ~~~ ### watch, unwatch ----- _**Description**_: Watches a key for modifications by another client. If the key is modified between `WATCH` and `EXEC`, the MULTI/EXEC transaction will fail (return `FALSE`). `unwatch` cancels all the watching of all keys by this client. ##### *Parameters* *keys*: a list of keys ##### *Example* ~~~ $redis->watch('x'); /* long code here during the execution of which other clients could well modify `x` */ $ret = $redis->multi() ->incr('x') ->exec(); /* $ret = FALSE if x has been modified between the call to WATCH and the call to EXEC. */ ~~~ ## Scripting * [eval](#) - Evaluate a LUA script serverside * [evalSha](#) - Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself * [script](#) - Execute the Redis SCRIPT command to perform various operations on the scripting subsystem * [getLastError](#) - The last error message (if any) * [clearLastError](#) - Clear the last error message * [_prefix](#) - A utility method to prefix the value with the prefix setting for phpredis * [_unserialize](#) - A utility method to unserialize data with whatever serializer is set up ### eval ----- _**Description**_: Evaluate a LUA script serverside ##### *Parameters* *script* string. *args* array, optional. *num_keys* int, optional. ##### *Return value* Mixed. What is returned depends on what the LUA script itself returns, which could be a scalar value (int/string), or an array. Arrays that are returned can also contain other arrays, if that's how it was set up in your LUA script. If there is an error executing the LUA script, the getLastError() function can tell you the message that came back from Redis (e.g. compile error). ##### *Examples* ~~~ $redis->eval("return 1"); // Returns an integer: 1 $redis->eval("return {1,2,3}"); // Returns Array(1,2,3) $redis->del('mylist'); $redis->rpush('mylist','a'); $redis->rpush('mylist','b'); $redis->rpush('mylist','c'); // Nested response: Array(1,2,3,Array('a','b','c')); $redis->eval("return {1,2,3,redis.call('lrange','mylist',0,-1)}}"); ~~~ ### evalSha ----- _**Description**_: Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself. In order to run this command Redis will have to have already loaded the script, either by running it or via the SCRIPT LOAD command. ##### *Parameters* *script_sha* string. The sha1 encoded hash of the script you want to run. *args* array, optional. Arguments to pass to the LUA script. *num_keys* int, optional. The number of arguments that should go into the KEYS array, vs. the ARGV array when Redis spins the script ##### *Return value* Mixed. See EVAL ##### *Examples* ~~~ $script = 'return 1'; $sha = $redis->script('load', $script); $redis->evalSha($sha); // Returns 1 ~~~ ### script ----- _**Description**_: Execute the Redis SCRIPT command to perform various operations on the scripting subsystem. ##### *Usage* ~~~ $redis->script('load', $script); $redis->script('flush'); $redis->script('kill'); $redis->script('exists', $script1, [$script2, $script3, ...]); ~~~ ##### *Return value* * SCRIPT LOAD will return the SHA1 hash of the passed script on success, and FALSE on failure. * SCRIPT FLUSH should always return TRUE * SCRIPT KILL will return true if a script was able to be killed and false if not * SCRIPT EXISTS will return an array with TRUE or FALSE for each passed script ### client ----- _**Description**_: Issue the CLIENT command with various arguments. The Redis CLIENT command can be used in four ways. * CLIENT LIST * CLIENT GETNAME * CLIENT SETNAME [name] * CLIENT KILL [ip:port] ##### *Usage* ~~~ $redis->client('list'); // Get a list of clients $redis->client('getname'); // Get the name of the current connection $redis->client('setname', 'somename'); // Set the name of the current connection $redis->client('kill', ); // Kill the process at ip:port ~~~ ##### *Return value* This will vary depending on which client command was executed. * CLIENT LIST will return an array of arrays with client information. * CLIENT GETNAME will return the client name or false if none has been set * CLIENT SETNAME will return true if it can be set and false if not * CLIENT KILL will return true if the client can be killed, and false if not Note: phpredis will attempt to reconnect so you can actually kill your own connection but may not notice losing it! ### getLastError ----- _**Description**_: The last error message (if any) ##### *Parameters* *none* ##### *Return value* A string with the last returned script based error message, or NULL if there is no error ##### *Examples* ~~~ $redis->eval('this-is-not-lua'); $err = $redis->getLastError(); // "ERR Error compiling script (new function): user_script:1: '=' expected near '-'" ~~~ ### clearLastError ----- _**Description**_: Clear the last error message ##### *Parameters* *none* ##### *Return value* *BOOL* TRUE ##### *Examples* ~~~ $redis->set('x', 'a'); $redis->incr('x'); $err = $redis->getLastError(); // "ERR value is not an integer or out of range" $redis->clearLastError(); $err = $redis->getLastError(); // NULL ~~~ ### _prefix ----- _**Description**_: A utility method to prefix the value with the prefix setting for phpredis. ##### *Parameters* *value* string. The value you wish to prefix ##### *Return value* If a prefix is set up, the value now prefixed. If there is no prefix, the value will be returned unchanged. ##### *Examples* ~~~ $redis->setOption(Redis::OPT_PREFIX, 'my-prefix:'); $redis->_prefix('my-value'); // Will return 'my-prefix:my-value' ~~~ ### _unserialize ----- _**Description**_: A utility method to unserialize data with whatever serializer is set up. If there is no serializer set, the value will be returned unchanged. If there is a serializer set up, and the data passed in is malformed, an exception will be thrown. This can be useful if phpredis is serializing values, and you return something from redis in a LUA script that is serialized. ##### *Parameters* *value* string. The value to be unserialized ##### *Examples* ~~~ $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); $redis->_unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // Will return Array(1,2,3) ~~~ ## Introspection ### IsConnected ----- _**Description**_: A method to determine if a phpredis object thinks it's connected to a server ##### *Parameters* None ##### *Return value* *Boolean* Returns TRUE if phpredis thinks it's connected and FALSE if not ### GetHost ----- _**Description**_: Retreive our host or unix socket that we're connected to ##### *Parameters* None ##### *Return value* *Mixed* The host or unix socket we're connected to or FALSE if we're not connected ### GetPort ----- _**Description**_: Get the port we're connected to ##### *Parameters* None ##### *Return value* *Mixed* Returns the port we're connected to or FALSE if we're not connected ### getDBNum ----- _**Description**_: Get the database number phpredis is pointed to ##### *Parameters* None ##### *Return value* *Mixed* Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected ### GetTimeout ----- _**Description**_: Get the (write) timeout in use for phpreids ##### *Parameters* None ##### *Return value* *Mixed* The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected ### GetReadTimeout _**Description**_: Get the read timeout specified to phpredis or FALSE if we're not connected ##### *Parameters* None ##### *Return value* *Mixed* Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMOUT) or FALSE if we're not connected ### GetPersistentID ----- _**Description**_: Gets the persistent ID that phpredis is using ##### *Parameters* None ##### *Return value* *Mixed* Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not using a persistent ID, and FALSE if we're not connected ### GetAuth ----- _**Description**_: Get the password used to authenticate the phpredis connection ### *Parameters* None ### *Return value* *Mixed* Returns the password used to authenticate a phpredis session or NULL if none was used, and FALSE if we're not connected redis-2.2.4/arrays.markdown0000664000175000017500000001773412211042406015542 0ustar nicolasnicolasRedis Arrays ============ A Redis array is an isolated namespace in which keys are related in some manner. Keys are distributed across a number of Redis instances, using consistent hashing. A hash function is used to spread the keys across the array in order to keep a uniform distribution. **This feature was added as the result of a generous sponsorship by [A+E Networks](http://www.aetn.com/).** An array is composed of the following: * A list of Redis hosts. * A key extraction function, used to hash part of the key in order to distribute related keys on the same node (optional). This is set by the "function" option. * A list of nodes previously in the ring, only present after a node has been added or removed. When a read command is sent to the array (e.g. GET, LRANGE...), the key is first queryied in the main ring, and then in the secondary ring if it was not found in the main one. Optionally, the keys can be migrated automatically when this happens. Write commands will always go to the main ring. This is set by the "previous" option. * An optional index in the form of a Redis set per node, used to migrate keys when nodes are added or removed; set by the "index" option. * An option to rehash the array automatically as nodes are added or removed, set by the "autorehash" option. ## Creating an array There are several ways of creating Redis arrays; they can be pre-defined in redis.ini using `new RedisArray(string $name);`, or created dynamically using `new RedisArray(array $hosts, array $options);` #### Declaring a new array with a list of nodes
$ra = new RedisArray(array("host1", "host2:63792", "host2:6380"));
#### Declaring a new array with a list of nodes and a function to extract a part of the key
function extract_key_part($k) {
    return substr($k, 0, 3);	// hash only on first 3 characters.
}
$ra = new RedisArray(array("host1", "host2:63792", "host2:6380"), array("function" => "extract_key_part"));
#### Defining a "previous" array when nodes are added or removed. When a new node is added to an array, phpredis needs to know about it. The old list of nodes becomes the “previous” array, and the new list of nodes is used as a main ring. Right after a node has been added, some read commands will point to the wrong nodes and will need to look up the keys in the previous ring.
// adding host3 to a ring containing host1 and host2. Read commands will look in the previous ring if the data is not found in the main ring.
$ra = new RedisArray(array("host1", "host2", "host3"), array("previous" => array("host1", "host2")));
#### Specifying the "retry_interval" parameter The retry_interval is used to specify a delay in milliseconds between reconnection attempts in case the client loses connection with a server
$ra = new RedisArray(array("host1", "host2:63792", "host2:6380"), array("retry_timeout" => 100)));
#### Specifying the "lazy_connect" parameter This option is useful when a cluster has many shards but not of them are necessarily used at one time.
$ra = new RedisArray(array("host1", "host2:63792", "host2:6380"), array("lazy_connect" => true)));
#### Defining arrays in Redis.ini Because php.ini parameters must be pre-defined, Redis Arrays must all share the same .ini settings.
// list available Redis Arrays
ini_set('redis.array.names', 'users,friends');

// set host names for each array.
ini_set('redis.arrays.hosts', 'users[]=localhost:6379&users[]=localhost:6380&users[]=localhost:6381&users[]=localhost:6382&friends[]=localhost');

// set functions
ini_set('redis.arrays.functions', 'users=user_hash');

// use index only for users
ini_set('redis.arrays.index', 'users=1,friends=0');
## Usage Redis arrays can be used just as Redis objects:
$ra = new RedisArray("users");
$ra->set("user1:name", "Joe");
$ra->set("user2:name", "Mike");
## Key hashing By default and in order to be compatible with other libraries, phpredis will try to find a substring enclosed in curly braces within the key name, and use it to distribute the data. For instance, the keys “{user:1}:name” and “{user:1}:email” will be stored on the same server as only “user:1” will be hashed. You can provide a custom function name in your redis array with the "function" option; this function will be called every time a key needs to be hashed. It should take a string and return a string. ## Custom key distribution function In order to control the distribution of keys by hand, you can provide a custom function or closure that returns the server number, which is the index in the array of servers that you created the RedisArray object with. For instance, instanciate a RedisArray object with `new RedisArray(array("us-host", "uk-host", "de-host"), array("distributor" => "dist"));` and write a function called "dist" that will return `2` for all the keys that should end up on the "de-host" server. ### Example
$ra = new RedisArray(array("host1", "host2", "host3", "host4", "host5", "host6", "host7", "host8"), array("distributor" => array(2, 2)));
This declares that we started with 2 shards and moved to 4 then 8 shards. The number of initial shards is 2 and the resharding level (or number of iterations) is 2. ## Migrating keys When a node is added or removed from a ring, RedisArray instances must be instanciated with a “previous” list of nodes. A single call to `$ra->_rehash()` causes all the keys to be redistributed according to the new list of nodes. Passing a callback function to `_rehash()` makes it possible to track the progress of that operation: the function is called with a node name and a number of keys that will be examined, e.g. `_rehash(function ($host, $count){ ... });`. It is possible to automate this process, by setting `'autorehash' => TRUE` in the constructor options. This will cause keys to be migrated when they need to be read from the previous array. In order to migrate keys, they must all be examined and rehashed. If the "index" option was set, a single key per node lists all keys present there. Otherwise, the `KEYS` command is used to list them. If a “previous” list of servers is provided, it will be used as a backup ring when keys can not be found in the current ring. Writes will always go to the new ring, whilst reads will go to the new ring first, and to the second ring as a backup. Adding and/or removing several instances is supported. ### Example
$ra = new RedisArray("users"); // load up a new config from redis.ini, using the “.previous” listing.
$ra->_rehash();
Running this code will: * Create a new ring with the updated list of nodes. * Server by server, look up all the keys in the previous list of nodes. * Rehash each key and possibly move it to another server. * Update the array object with the new list of nodes. ## Multi/exec Multi/exec is still available, but must be run on a single node:
$host = $ra->_target("{users}:user1:name");	// find host first
$ra->multi($host)	// then run transaction on that host.
   ->del("{users}:user1:name")
   ->srem("{users}:index", "user1")
   ->exec();
## Limitations Key arrays offer no guarantee when using Redis commands that span multiple keys. Except for the use of MGET, MSET, and DEL, a single connection will be used and all the keys read or written there. Running KEYS() on a RedisArray object will execute the command on each node and return an associative array of keys, indexed by host name. ## Array info RedisArray objects provide several methods to help understand the state of the cluster. These methods start with an underscore. * `$ra->_hosts()` → returns a list of hosts for the selected array. * `$ra->_function()` → returns the name of the function used to extract key parts during consistent hashing. * `$ra->_target($key)` → returns the host to be used for a certain key. * `$ra->_instance($host)` → returns a redis instance connected to a specific node; use with `_target` to get a single Redis object. ## Running the unit tests
$ cd tests
$ ./mkring.sh start
$ php array-tests.php
redis-2.2.4/CREDITS0000664000175000017500000000024012211042406013475 0ustar nicolasnicolasRedis client extension for PHP Alfonso Jimenez Nasreddine Bouafif Nicolas Favre-Felix redis-2.2.4/COPYING0000664000175000017500000000622212211042406013516 0ustar nicolasnicolas-------------------------------------------------------------------- The PHP License, version 3.01 Copyright (c) 1999 - 2010 The PHP Group. All rights reserved. -------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, is permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name "PHP" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact group@php.net. 4. Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission from group@php.net. You may indicate that your software works in conjunction with PHP by saying "Foo for PHP" instead of calling it "PHP Foo" or "phpfoo" 5. The PHP Group may publish revised and/or new versions of the license from time to time. Each version will be given a distinguishing version number. Once covered code has been published under a particular version of the license, you may always continue to use it under the terms of that version. You may also choose to use such covered code under the terms of any subsequent version of the license published by the PHP Group. No one other than the PHP Group has the right to modify the terms applicable to covered code created under this License. 6. Redistributions of any form whatsoever must retain the following acknowledgment: "This product includes PHP software, freely available from ". THIS SOFTWARE IS PROVIDED BY THE PHP DEVELOPMENT TEAM ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PHP DEVELOPMENT TEAM OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------- This software consists of voluntary contributions made by many individuals on behalf of the PHP Group. The PHP Group can be contacted via Email at group@php.net. For more information on the PHP Group and the PHP project, please see . PHP includes the Zend Engine, freely available at . redis-2.2.4/config.m40000775000175000017500000000642012211042406014175 0ustar nicolasnicolasdnl $Id$ dnl config.m4 for extension redis PHP_ARG_ENABLE(redis, whether to enable redis support, dnl Make sure that the comment is aligned: [ --enable-redis Enable redis support]) PHP_ARG_ENABLE(redis-session, whether to enable sessions, [ --disable-redis-session Disable session support], yes, no) PHP_ARG_ENABLE(redis-igbinary, whether to enable igbinary serializer support, [ --enable-redis-igbinary Enable igbinary serializer support], no, no) if test "$PHP_REDIS" != "no"; then if test "$PHP_REDIS_SESSION" != "no"; then AC_DEFINE(PHP_SESSION,1,[redis sessions]) fi dnl Check for igbinary if test "$PHP_REDIS_IGBINARY" != "no"; then AC_MSG_CHECKING([for igbinary includes]) igbinary_inc_path="" if test -f "$abs_srcdir/include/php/ext/igbinary/igbinary.h"; then igbinary_inc_path="$abs_srcdir/include/php" elif test -f "$abs_srcdir/ext/igbinary/igbinary.h"; then igbinary_inc_path="$abs_srcdir" elif test -f "$phpincludedir/ext/igbinary/igbinary.h"; then igbinary_inc_path="$phpincludedir" else for i in php php4 php5 php6; do if test -f "$prefix/include/$i/ext/igbinary/igbinary.h"; then igbinary_inc_path="$prefix/include/$i" fi done fi if test "$igbinary_inc_path" = ""; then AC_MSG_ERROR([Cannot find igbinary.h]) else AC_MSG_RESULT([$igbinary_inc_path]) fi fi AC_MSG_CHECKING([for redis igbinary support]) if test "$PHP_REDIS_IGBINARY" != "no"; then AC_MSG_RESULT([enabled]) AC_DEFINE(HAVE_REDIS_IGBINARY,1,[Whether redis igbinary serializer is enabled]) IGBINARY_INCLUDES="-I$igbinary_inc_path" IGBINARY_EXT_DIR="$igbinary_inc_path/ext" ifdef([PHP_ADD_EXTENSION_DEP], [ PHP_ADD_EXTENSION_DEP(redis, igbinary) ]) PHP_ADD_INCLUDE($IGBINARY_EXT_DIR) else IGBINARY_INCLUDES="" AC_MSG_RESULT([disabled]) fi dnl # --with-redis -> check with-path dnl SEARCH_PATH="/usr/local /usr" # you might want to change this dnl SEARCH_FOR="/include/redis.h" # you most likely want to change this dnl if test -r $PHP_REDIS/$SEARCH_FOR; then # path given as parameter dnl REDIS_DIR=$PHP_REDIS dnl else # search default path list dnl AC_MSG_CHECKING([for redis files in default path]) dnl for i in $SEARCH_PATH ; do dnl if test -r $i/$SEARCH_FOR; then dnl REDIS_DIR=$i dnl AC_MSG_RESULT(found in $i) dnl fi dnl done dnl fi dnl dnl if test -z "$REDIS_DIR"; then dnl AC_MSG_RESULT([not found]) dnl AC_MSG_ERROR([Please reinstall the redis distribution]) dnl fi dnl # --with-redis -> add include path dnl PHP_ADD_INCLUDE($REDIS_DIR/include) dnl # --with-redis -> check for lib and symbol presence dnl LIBNAME=redis # you may want to change this dnl LIBSYMBOL=redis # you most likely want to change this dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL, dnl [ dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $REDIS_DIR/lib, REDIS_SHARED_LIBADD) dnl AC_DEFINE(HAVE_REDISLIB,1,[ ]) dnl ],[ dnl AC_MSG_ERROR([wrong redis lib version or lib not found]) dnl ],[ dnl -L$REDIS_DIR/lib -lm -ldl dnl ]) dnl dnl PHP_SUBST(REDIS_SHARED_LIBADD) PHP_NEW_EXTENSION(redis, redis.c library.c redis_session.c redis_array.c redis_array_impl.c, $ext_shared) fi redis-2.2.4/config.w320000664000175000017500000000071612211042406014267 0ustar nicolasnicolas// vim: ft=javascript: ARG_ENABLE("redis", "whether to enable redis support", "yes"); ARG_ENABLE("redis-session", "whether to enable sessions", "yes"); if (PHP_REDIS != "no") { var sources = "redis.c library.c igbinary\\igbinary.c igbinary\\hash_si.c igbinary\\hash_function.c"; if (PHP_REDIS_SESSION != "no") { AC_DEFINE('PHP_SESSION', 1); sources += " redis_session.c"; } AC_DEFINE("PHP_EXPORTS", 1); EXTENSION("redis", sources); } redis-2.2.4/common.h0000664000175000017500000001316312211042406014126 0ustar nicolasnicolas#include "php.h" #include "php_ini.h" #include #ifndef REDIS_COMMON_H #define REDIS_COMMON_H /* NULL check so Eclipse doesn't go crazy */ #ifndef NULL #define NULL ((void *) 0) #endif #define redis_sock_name "Redis Socket Buffer" #define REDIS_SOCK_STATUS_FAILED 0 #define REDIS_SOCK_STATUS_DISCONNECTED 1 #define REDIS_SOCK_STATUS_UNKNOWN 2 #define REDIS_SOCK_STATUS_CONNECTED 3 #define redis_multi_access_type_name "Redis Multi type access" #define _NL "\r\n" /* properties */ #define REDIS_NOT_FOUND 0 #define REDIS_STRING 1 #define REDIS_SET 2 #define REDIS_LIST 3 #define REDIS_ZSET 4 #define REDIS_HASH 5 /* reply types */ typedef enum _REDIS_REPLY_TYPE { TYPE_LINE = '+', TYPE_INT = ':', TYPE_ERR = '-', TYPE_BULK = '$', TYPE_MULTIBULK = '*' } REDIS_REPLY_TYPE; /* options */ #define REDIS_OPT_SERIALIZER 1 #define REDIS_OPT_PREFIX 2 #define REDIS_OPT_READ_TIMEOUT 3 /* serializers */ #define REDIS_SERIALIZER_NONE 0 #define REDIS_SERIALIZER_PHP 1 #define REDIS_SERIALIZER_IGBINARY 2 #define IF_MULTI() if(redis_sock->mode == MULTI) #define IF_MULTI_OR_ATOMIC() if(redis_sock->mode == MULTI || redis_sock->mode == ATOMIC)\ #define IF_MULTI_OR_PIPELINE() if(redis_sock->mode == MULTI || redis_sock->mode == PIPELINE) #define IF_PIPELINE() if(redis_sock->mode == PIPELINE) #define IF_NOT_MULTI() if(redis_sock->mode != MULTI) #define IF_ATOMIC() if(redis_sock->mode == ATOMIC) #define ELSE_IF_MULTI() else if(redis_sock->mode == MULTI) { \ if(redis_response_enqueued(redis_sock TSRMLS_CC) == 1) {\ RETURN_ZVAL(getThis(), 1, 0);\ } else {\ RETURN_FALSE;\ } \ } #define ELSE_IF_PIPELINE() else IF_PIPELINE() { \ RETURN_ZVAL(getThis(), 1, 0);\ } #define MULTI_RESPONSE(callback) IF_MULTI_OR_PIPELINE() { \ fold_item *f1, *current; \ f1 = malloc(sizeof(fold_item)); \ f1->fun = (void *)callback; \ f1->next = NULL; \ current = redis_sock->current;\ if(current) current->next = f1; \ redis_sock->current = f1; \ } #define PIPELINE_ENQUEUE_COMMAND(cmd, cmd_len) request_item *tmp; \ struct request_item *current_request;\ tmp = malloc(sizeof(request_item));\ tmp->request_str = calloc(cmd_len, 1);\ memcpy(tmp->request_str, cmd, cmd_len);\ tmp->request_size = cmd_len;\ tmp->next = NULL;\ current_request = redis_sock->pipeline_current; \ if(current_request) {\ current_request->next = tmp;\ } \ redis_sock->pipeline_current = tmp; \ if(NULL == redis_sock->pipeline_head) { \ redis_sock->pipeline_head = redis_sock->pipeline_current;\ } #define SOCKET_WRITE_COMMAND(redis_sock, cmd, cmd_len) if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { \ efree(cmd); \ RETURN_FALSE; \ } #define REDIS_SAVE_CALLBACK(callback, closure_context) IF_MULTI_OR_PIPELINE() { \ fold_item *f1, *current; \ f1 = malloc(sizeof(fold_item)); \ f1->fun = (void *)callback; \ f1->ctx = closure_context; \ f1->next = NULL; \ current = redis_sock->current;\ if(current) current->next = f1; \ redis_sock->current = f1; \ if(NULL == redis_sock->head) { \ redis_sock->head = redis_sock->current;\ }\ } #define REDIS_ELSE_IF_MULTI(function, closure_context) \ else if(redis_sock->mode == MULTI) { \ if(redis_response_enqueued(redis_sock TSRMLS_CC) == 1) {\ REDIS_SAVE_CALLBACK(function, closure_context); \ RETURN_ZVAL(getThis(), 1, 0);\ } else {\ RETURN_FALSE;\ }\ } #define REDIS_ELSE_IF_PIPELINE(function, closure_context) else IF_PIPELINE() { \ REDIS_SAVE_CALLBACK(function, closure_context); \ RETURN_ZVAL(getThis(), 1, 0);\ } #define REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len) \ IF_MULTI_OR_ATOMIC() { \ SOCKET_WRITE_COMMAND(redis_sock, cmd, cmd_len); \ efree(cmd); \ }\ IF_PIPELINE() { \ PIPELINE_ENQUEUE_COMMAND(cmd, cmd_len); \ efree(cmd); \ } #define REDIS_PROCESS_RESPONSE_CLOSURE(function, closure_context) \ REDIS_ELSE_IF_MULTI(function, closure_context) \ REDIS_ELSE_IF_PIPELINE(function, closure_context); #define REDIS_PROCESS_RESPONSE(function) REDIS_PROCESS_RESPONSE_CLOSURE(function, NULL) /* Extended SET argument detection */ #define IS_EX_ARG(a) ((a[0]=='e' || a[0]=='E') && (a[1]=='x' || a[1]=='X') && a[2]=='\0') #define IS_PX_ARG(a) ((a[0]=='p' || a[0]=='P') && (a[1]=='x' || a[1]=='X') && a[2]=='\0') #define IS_NX_ARG(a) ((a[0]=='n' || a[0]=='N') && (a[1]=='x' || a[1]=='X') && a[2]=='\0') #define IS_XX_ARG(a) ((a[0]=='x' || a[0]=='X') && (a[1]=='x' || a[1]=='X') && a[2]=='\0') #define IS_EX_PX_ARG(a) (IS_EX_ARG(a) || IS_PX_ARG(a)) #define IS_NX_XX_ARG(a) (IS_NX_ARG(a) || IS_XX_ARG(a)) typedef enum {ATOMIC, MULTI, PIPELINE} redis_mode; typedef struct fold_item { zval * (*fun)(INTERNAL_FUNCTION_PARAMETERS, void *, ...); void *ctx; struct fold_item *next; } fold_item; typedef struct request_item { char *request_str; int request_size; /* size_t */ struct request_item *next; } request_item; /* {{{ struct RedisSock */ typedef struct { php_stream *stream; char *host; short port; char *auth; double timeout; double read_timeout; long retry_interval; int failed; int status; int persistent; int watching; char *persistent_id; int serializer; long dbNumber; char *prefix; int prefix_len; redis_mode mode; fold_item *head; fold_item *current; request_item *pipeline_head; request_item *pipeline_current; char *err; int err_len; zend_bool lazy_connect; } RedisSock; /* }}} */ void free_reply_callbacks(zval *z_this, RedisSock *redis_sock); #endif redis-2.2.4/library.c0000664000175000017500000013776712211042406014316 0ustar nicolasnicolas#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "common.h" #include "php_network.h" #include #ifndef _MSC_VER #include /* TCP_NODELAY */ #include #endif #include #include #ifdef HAVE_REDIS_IGBINARY #include "igbinary/igbinary.h" #endif #include #include "php_redis.h" #include "library.h" #include #define UNSERIALIZE_ONLY_VALUES 0 #define UNSERIALIZE_ALL 1 extern zend_class_entry *redis_ce; extern zend_class_entry *redis_exception_ce; extern zend_class_entry *spl_ce_RuntimeException; PHPAPI void redis_stream_close(RedisSock *redis_sock TSRMLS_DC) { if (!redis_sock->persistent) { php_stream_close(redis_sock->stream); } else { php_stream_pclose(redis_sock->stream); } } PHPAPI int redis_check_eof(RedisSock *redis_sock TSRMLS_DC) { int eof; int count = 0; if (!redis_sock->stream) { return -1; } eof = php_stream_eof(redis_sock->stream); for (; eof; count++) { if((MULTI == redis_sock->mode) || redis_sock->watching || count == 10) { /* too many failures */ if(redis_sock->stream) { /* close stream if still here */ redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->mode = ATOMIC; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->watching = 0; } zend_throw_exception(redis_exception_ce, "Connection lost", 0 TSRMLS_CC); return -1; } if(redis_sock->stream) { /* close existing stream before reconnecting */ redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->mode = ATOMIC; redis_sock->watching = 0; } // Wait for a while before trying to reconnect if (redis_sock->retry_interval) { // Random factor to avoid having several (or many) concurrent connections trying to reconnect at the same time long retry_interval = (count ? redis_sock->retry_interval : (random() % redis_sock->retry_interval)); usleep(retry_interval); } redis_sock_connect(redis_sock TSRMLS_CC); /* reconnect */ if(redis_sock->stream) { /* check for EOF again. */ eof = php_stream_eof(redis_sock->stream); } } // Reselect the DB. if (count && redis_sock->dbNumber) { char *cmd, *response; int cmd_len, response_len; cmd_len = redis_cmd_format_static(&cmd, "SELECT", "d", redis_sock->dbNumber); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return -1; } efree(cmd); if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { return -1; } if (strncmp(response, "+OK", 3)) { efree(response); return -1; } efree(response); } return 0; } PHPAPI zval *redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock) { char inbuf[1024]; int numElems; zval *z_tab; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return NULL; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return NULL; } if(inbuf[0] != '*') { return NULL; } numElems = atoi(inbuf+1); MAKE_STD_ZVAL(z_tab); array_init(z_tab); redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, numElems, 1, UNSERIALIZE_ALL); return z_tab; } /** * redis_sock_read_bulk_reply */ PHPAPI char *redis_sock_read_bulk_reply(RedisSock *redis_sock, int bytes TSRMLS_DC) { int offset = 0; size_t got; char * reply; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return NULL; } if (bytes == -1) { return NULL; } else { char c; int i; reply = emalloc(bytes+1); while(offset < bytes) { got = php_stream_read(redis_sock->stream, reply + offset, bytes-offset); if (got <= 0) { /* Error or EOF */ zend_throw_exception(redis_exception_ce, "socket error on read socket", 0 TSRMLS_CC); break; } offset += got; } for(i = 0; i < 2; i++) { php_stream_read(redis_sock->stream, &c, 1); } } reply[bytes] = 0; return reply; } /** * redis_sock_read */ PHPAPI char *redis_sock_read(RedisSock *redis_sock, int *buf_len TSRMLS_DC) { char inbuf[1024]; char *resp = NULL; size_t err_len; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return NULL; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return NULL; } switch(inbuf[0]) { case '-': err_len = strlen(inbuf+1) - 2; redis_sock_set_err(redis_sock, inbuf+1, err_len); /* stale data */ if(memcmp(inbuf + 1, "-ERR SYNC ", 10) == 0) { zend_throw_exception(redis_exception_ce, "SYNC with master in progress", 0 TSRMLS_CC); } return NULL; case '$': *buf_len = atoi(inbuf + 1); resp = redis_sock_read_bulk_reply(redis_sock, *buf_len TSRMLS_CC); return resp; case '*': /* For null multi-bulk replies (like timeouts from brpoplpush): */ if(memcmp(inbuf + 1, "-1", 2) == 0) { return NULL; } /* fall through */ case '+': case ':': // Single Line Reply /* :123\r\n */ *buf_len = strlen(inbuf) - 2; if(*buf_len >= 2) { resp = emalloc(1+*buf_len); memcpy(resp, inbuf, *buf_len); resp[*buf_len] = 0; return resp; } default: zend_throw_exception_ex( redis_exception_ce, 0 TSRMLS_CC, "protocol error, got '%c' as reply type byte\n", inbuf[0] ); } return NULL; } void add_constant_long(zend_class_entry *ce, char *name, int value) { zval *constval; constval = pemalloc(sizeof(zval), 1); INIT_PZVAL(constval); ZVAL_LONG(constval, value); zend_hash_add(&ce->constants_table, name, 1 + strlen(name), (void*)&constval, sizeof(zval*), NULL); } int integer_length(int i) { int sz = 0; int ci = abs(i); while (ci > 0) { ci /= 10; sz++; } if (i == 0) { /* log 0 doesn't make sense. */ sz = 1; } else if (i < 0) { /* allow for neg sign as well. */ sz++; } return sz; } int redis_cmd_format_header(char **ret, char *keyword, int arg_count) { // Our return buffer smart_str buf = {0}; // Keyword length int l = strlen(keyword); smart_str_appendc(&buf, '*'); smart_str_append_long(&buf, arg_count + 1); smart_str_appendl(&buf, _NL, sizeof(_NL) -1); smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, l); smart_str_appendl(&buf, _NL, sizeof(_NL) -1); smart_str_appendl(&buf, keyword, l); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); // Set our return pointer *ret = buf.c; // Return the length return buf.len; } int redis_cmd_format_static(char **ret, char *keyword, char *format, ...) { char *p = format; va_list ap; smart_str buf = {0}; int l = strlen(keyword); char *dbl_str; int dbl_len; va_start(ap, format); /* add header */ smart_str_appendc(&buf, '*'); smart_str_append_long(&buf, strlen(format) + 1); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, l); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, keyword, l); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); while (*p) { smart_str_appendc(&buf, '$'); switch(*p) { case 's': { char *val = va_arg(ap, char*); int val_len = va_arg(ap, int); smart_str_append_long(&buf, val_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, val, val_len); } break; case 'f': case 'F': { double d = va_arg(ap, double); REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, d) smart_str_append_long(&buf, dbl_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, dbl_str, dbl_len); efree(dbl_str); } break; case 'i': case 'd': { int i = va_arg(ap, int); char tmp[32]; int tmp_len = snprintf(tmp, sizeof(tmp), "%d", i); smart_str_append_long(&buf, tmp_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, tmp, tmp_len); } break; case 'l': case 'L': { long l = va_arg(ap, long); char tmp[32]; int tmp_len = snprintf(tmp, sizeof(tmp), "%ld", l); smart_str_append_long(&buf, tmp_len); smart_str_appendl(&buf, _NL, sizeof(_NL) -1); smart_str_appendl(&buf, tmp, tmp_len); } break; } p++; smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); } smart_str_0(&buf); *ret = buf.c; return buf.len; } /** * This command behave somehow like printf, except that strings need 2 arguments: * Their data and their size (strlen). * Supported formats are: %d, %i, %s, %l */ int redis_cmd_format(char **ret, char *format, ...) { smart_str buf = {0}; va_list ap; char *p = format; char *dbl_str; int dbl_len; va_start(ap, format); while (*p) { if (*p == '%') { switch (*(++p)) { case 's': { char *tmp = va_arg(ap, char*); int tmp_len = va_arg(ap, int); smart_str_appendl(&buf, tmp, tmp_len); } break; case 'F': case 'f': { double d = va_arg(ap, double); REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, d) smart_str_append_long(&buf, dbl_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, dbl_str, dbl_len); efree(dbl_str); } break; case 'd': case 'i': { int i = va_arg(ap, int); char tmp[32]; int tmp_len = snprintf(tmp, sizeof(tmp), "%d", i); smart_str_appendl(&buf, tmp, tmp_len); } break; } } else { smart_str_appendc(&buf, *p); } p++; } smart_str_0(&buf); *ret = buf.c; return buf.len; } /* * Append a command sequence to a Redis command */ int redis_cmd_append_str(char **cmd, int cmd_len, char *append, int append_len) { // Smart string buffer smart_str buf = {0}; // Append the current command to our smart_str smart_str_appendl(&buf, *cmd, cmd_len); // Append our new command sequence smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, append_len); smart_str_appendl(&buf, _NL, sizeof(_NL) -1); smart_str_appendl(&buf, append, append_len); smart_str_appendl(&buf, _NL, sizeof(_NL) -1); // Free our old command efree(*cmd); // Set our return pointer *cmd = buf.c; // Return new command length return buf.len; } /* * Given a smart string, number of arguments, a keyword, and the length of the keyword * initialize our smart string with the proper Redis header for the command to follow */ int redis_cmd_init_sstr(smart_str *str, int num_args, char *keyword, int keyword_len) { smart_str_appendc(str, '*'); smart_str_append_long(str, num_args + 1); smart_str_appendl(str, _NL, sizeof(_NL) -1); smart_str_appendc(str, '$'); smart_str_append_long(str, keyword_len); smart_str_appendl(str, _NL, sizeof(_NL) - 1); smart_str_appendl(str, keyword, keyword_len); smart_str_appendl(str, _NL, sizeof(_NL) - 1); return str->len; } /* * Append a command sequence to a smart_str */ int redis_cmd_append_sstr(smart_str *str, char *append, int append_len) { smart_str_appendc(str, '$'); smart_str_append_long(str, append_len); smart_str_appendl(str, _NL, sizeof(_NL) - 1); smart_str_appendl(str, append, append_len); smart_str_appendl(str, _NL, sizeof(_NL) - 1); // Return our new length return str->len; } /* * Append an integer to a smart string command */ int redis_cmd_append_sstr_int(smart_str *str, int append) { char int_buf[32]; int int_len = snprintf(int_buf, sizeof(int_buf), "%d", append); return redis_cmd_append_sstr(str, int_buf, int_len); } /* * Append a long to a smart string command */ int redis_cmd_append_sstr_long(smart_str *str, long append) { char long_buf[32]; int long_len = snprintf(long_buf, sizeof(long_buf), "%ld", append); return redis_cmd_append_sstr(str, long_buf, long_len); } /* * Append a double to a smart string command */ int redis_cmd_append_sstr_dbl(smart_str *str, double value) { char *dbl_str; int dbl_len; /// Convert to double REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, value); // Append the string int retval = redis_cmd_append_sstr(str, dbl_str, dbl_len); // Free our double string efree(dbl_str); // Return new length return retval; } /* * Append an integer command to a Redis command */ int redis_cmd_append_int(char **cmd, int cmd_len, int append) { char int_buf[32]; // Conver to an int, capture length int int_len = snprintf(int_buf, sizeof(int_buf), "%d", append); // Return the new length return redis_cmd_append_str(cmd, cmd_len, int_buf, int_len); } PHPAPI void redis_bulk_double_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; double ret; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETURN_FALSE; } return; } ret = atof(response); efree(response); IF_MULTI_OR_PIPELINE() { add_next_index_double(z_tab, ret); } else { RETURN_DOUBLE(ret); } } PHPAPI void redis_type_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; long l; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETURN_FALSE; } } if (strncmp(response, "+string", 7) == 0) { l = REDIS_STRING; } else if (strncmp(response, "+set", 4) == 0){ l = REDIS_SET; } else if (strncmp(response, "+list", 5) == 0){ l = REDIS_LIST; } else if (strncmp(response, "+zset", 5) == 0){ l = REDIS_ZSET; } else if (strncmp(response, "+hash", 5) == 0){ l = REDIS_HASH; } else { l = REDIS_NOT_FOUND; } efree(response); IF_MULTI_OR_PIPELINE() { add_next_index_long(z_tab, l); } else { RETURN_LONG(l); } } PHPAPI void redis_info_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; char *pos, *cur; char *key, *value, *p; int is_numeric; zval *z_multi_result; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { RETURN_FALSE; } MAKE_STD_ZVAL(z_multi_result); array_init(z_multi_result); /* pre-allocate array for multi's results. */ /* response :: [response_line] * response_line :: key ':' value CRLF */ cur = response; while(1) { /* skip comments and empty lines */ if(*cur == '#' || *cur == '\r') { if(!(cur = strchr(cur, '\n'))) break; cur++; continue; } /* key */ pos = strchr(cur, ':'); if(pos == NULL) { break; } key = emalloc(pos - cur + 1); memcpy(key, cur, pos-cur); key[pos-cur] = 0; /* value */ cur = pos + 1; pos = strchr(cur, '\r'); if(pos == NULL) { break; } value = emalloc(pos - cur + 1); memcpy(value, cur, pos-cur); value[pos-cur] = 0; pos += 2; /* \r, \n */ cur = pos; is_numeric = 1; for(p = value; *p; ++p) { if(*p < '0' || *p > '9') { is_numeric = 0; break; } } if(is_numeric == 1) { add_assoc_long(z_multi_result, key, atol(value)); efree(value); } else { add_assoc_string(z_multi_result, key, value, 0); } efree(key); } efree(response); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_multi_result); } else { RETVAL_ZVAL(z_multi_result, 0, 1); } } /* * Specialized handling of the CLIENT LIST output so it comes out in a simple way for PHP userland code * to handle. */ PHPAPI void redis_client_list_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab) { char *resp; int resp_len; zval *z_result, *z_sub_result; // Make sure we can read a response from Redis if((resp = redis_sock_read(redis_sock, &resp_len TSRMLS_CC)) == NULL) { RETURN_FALSE; } // Allocate memory for our response MAKE_STD_ZVAL(z_result); array_init(z_result); // Allocate memory for one user (there should be at least one, namely us!) ALLOC_INIT_ZVAL(z_sub_result); array_init(z_sub_result); // Pointers for parsing char *p = resp, *lpos = resp, *kpos = NULL, *vpos = NULL, *p2, *key, *value; // Key length, done flag int klen, done = 0, is_numeric; // While we've got more to parse while(!done) { // What character are we on switch(*p) { /* We're done */ case '\0': done = 1; break; /* \n, ' ' mean we can pull a k/v pair */ case '\n': case ' ': // Grab our value vpos = lpos; // There is some communication error or Redis bug if we don't // have a key and value, but check anyway. if(kpos && vpos) { // Allocate, copy in our key key = emalloc(klen + 1); strncpy(key, kpos, klen); key[klen] = 0; // Allocate, copy in our value value = emalloc(p-lpos+1); strncpy(value,lpos,p-lpos+1); value[p-lpos]=0; // Treat numbers as numbers, strings as strings is_numeric = 1; for(p2 = value; *p; ++p) { if(*p < '0' || *p > '9') { is_numeric = 0; break; } } // Add as a long or string, depending if(is_numeric == 1) { add_assoc_long(z_sub_result, key, atol(value)); efree(value); } else { add_assoc_string(z_sub_result, key, value, 0); } // If we hit a '\n', then we can add this user to our list if(*p == '\n') { // Add our user add_next_index_zval(z_result, z_sub_result); // If we have another user, make another one if(*(p+1) != '\0') { ALLOC_INIT_ZVAL(z_sub_result); array_init(z_sub_result); } } // Free our key efree(key); } else { // Something is wrong efree(resp); RETURN_FALSE; } // Move forward lpos = p + 1; break; /* We can pull the key and null terminate at our sep */ case '=': // Key, key length kpos = lpos; klen = p - lpos; // Move forward lpos = p + 1; break; } // Increment p++; } // Free our respoonse efree(resp); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_result); } else { RETVAL_ZVAL(z_result, 0, 1); } } PHPAPI void redis_boolean_response_impl(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx, SuccessCallback success_callback) { char *response; int response_len; char ret; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); return; } RETURN_FALSE; } ret = response[0]; efree(response); IF_MULTI_OR_PIPELINE() { if (ret == '+') { if (success_callback != NULL) { success_callback(redis_sock); } add_next_index_bool(z_tab, 1); } else { add_next_index_bool(z_tab, 0); } } else { if (ret == '+') { if (success_callback != NULL) { success_callback(redis_sock); } RETURN_TRUE; } else { RETURN_FALSE; } } } PHPAPI void redis_boolean_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { redis_boolean_response_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, ctx, NULL); } PHPAPI void redis_long_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval * z_tab, void *ctx) { char *response; int response_len; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); return; } else { RETURN_FALSE; } } if(response[0] == ':') { long long ret = atoll(response + 1); IF_MULTI_OR_PIPELINE() { if(ret > LONG_MAX) { /* overflow */ add_next_index_stringl(z_tab, response+1, response_len-1, 1); } else { efree(response); add_next_index_long(z_tab, (long)ret); } } else { if(ret > LONG_MAX) { /* overflow */ RETURN_STRINGL(response+1, response_len-1, 1); } else { efree(response); RETURN_LONG((long)ret); } } } else { efree(response); IF_MULTI_OR_PIPELINE() { add_next_index_null(z_tab); } else { RETURN_FALSE; } } } PHPAPI int redis_sock_read_multibulk_reply_zipped_with_flag(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, int flag) { /* int ret = redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab TSRMLS_CC); array_zip_values_and_scores(return_value, 0); */ char inbuf[1024]; int numElems; zval *z_multi_result; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return -1; } if(inbuf[0] != '*') { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETVAL_FALSE; } return -1; } numElems = atoi(inbuf+1); MAKE_STD_ZVAL(z_multi_result); array_init(z_multi_result); /* pre-allocate array for multi's results. */ redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_multi_result, numElems, 1, flag ? UNSERIALIZE_ALL : UNSERIALIZE_ONLY_VALUES); array_zip_values_and_scores(redis_sock, z_multi_result, 0 TSRMLS_CC); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_multi_result); } else { *return_value = *z_multi_result; zval_copy_ctor(return_value); zval_dtor(z_multi_result); efree(z_multi_result); } return 0; } PHPAPI int redis_sock_read_multibulk_reply_zipped(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { return redis_sock_read_multibulk_reply_zipped_with_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, 1); } PHPAPI int redis_sock_read_multibulk_reply_zipped_strings(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { return redis_sock_read_multibulk_reply_zipped_with_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, 0); } PHPAPI void redis_1_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; char ret; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); return; } else { RETURN_FALSE; } } ret = response[1]; efree(response); IF_MULTI_OR_PIPELINE() { if(ret == '1') { add_next_index_bool(z_tab, 1); } else { add_next_index_bool(z_tab, 0); } } else { if (ret == '1') { RETURN_TRUE; } else { RETURN_FALSE; } } } PHPAPI void redis_string_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); return; } RETURN_FALSE; } IF_MULTI_OR_PIPELINE() { zval *z = NULL; if(redis_unserialize(redis_sock, response, response_len, &z TSRMLS_CC) == 1) { efree(response); add_next_index_zval(z_tab, z); } else { add_next_index_stringl(z_tab, response, response_len, 0); } } else { if(redis_unserialize(redis_sock, response, response_len, &return_value TSRMLS_CC) == 0) { RETURN_STRINGL(response, response_len, 0); } else { efree(response); } } } /* like string response, but never unserialized. */ PHPAPI void redis_ping_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char *response; int response_len; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); return; } RETURN_FALSE; } IF_MULTI_OR_PIPELINE() { add_next_index_stringl(z_tab, response, response_len, 0); } else { RETURN_STRINGL(response, response_len, 0); } } /** * redis_sock_create */ PHPAPI RedisSock* redis_sock_create(char *host, int host_len, unsigned short port, double timeout, int persistent, char *persistent_id, long retry_interval, zend_bool lazy_connect) { RedisSock *redis_sock; redis_sock = ecalloc(1, sizeof(RedisSock)); redis_sock->host = estrndup(host, host_len); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_DISCONNECTED; redis_sock->watching = 0; redis_sock->dbNumber = 0; redis_sock->retry_interval = retry_interval * 1000; redis_sock->persistent = persistent; redis_sock->lazy_connect = lazy_connect; if(persistent_id) { size_t persistent_id_len = strlen(persistent_id); redis_sock->persistent_id = ecalloc(persistent_id_len + 1, 1); memcpy(redis_sock->persistent_id, persistent_id, persistent_id_len); } else { redis_sock->persistent_id = NULL; } memcpy(redis_sock->host, host, host_len); redis_sock->host[host_len] = '\0'; redis_sock->port = port; redis_sock->timeout = timeout; redis_sock->read_timeout = timeout; redis_sock->serializer = REDIS_SERIALIZER_NONE; redis_sock->mode = ATOMIC; redis_sock->head = NULL; redis_sock->current = NULL; redis_sock->pipeline_head = NULL; redis_sock->pipeline_current = NULL; redis_sock->err = NULL; redis_sock->err_len = 0; return redis_sock; } /** * redis_sock_connect */ PHPAPI int redis_sock_connect(RedisSock *redis_sock TSRMLS_DC) { struct timeval tv, read_tv, *tv_ptr = NULL; char *host = NULL, *persistent_id = NULL, *errstr = NULL; int host_len, err = 0; php_netstream_data_t *sock; int tcp_flag = 1; if (redis_sock->stream != NULL) { redis_sock_disconnect(redis_sock TSRMLS_CC); } tv.tv_sec = (time_t)redis_sock->timeout; tv.tv_usec = (int)((redis_sock->timeout - tv.tv_sec) * 1000000); if(tv.tv_sec != 0 || tv.tv_usec != 0) { tv_ptr = &tv; } read_tv.tv_sec = (time_t)redis_sock->read_timeout; read_tv.tv_usec = (int)((redis_sock->read_timeout - read_tv.tv_sec) * 1000000); if(redis_sock->host[0] == '/' && redis_sock->port < 1) { host_len = spprintf(&host, 0, "unix://%s", redis_sock->host); } else { if(redis_sock->port == 0) redis_sock->port = 6379; host_len = spprintf(&host, 0, "%s:%d", redis_sock->host, redis_sock->port); } if (redis_sock->persistent) { if (redis_sock->persistent_id) { spprintf(&persistent_id, 0, "phpredis:%s:%s", host, redis_sock->persistent_id); } else { spprintf(&persistent_id, 0, "phpredis:%s:%f", host, redis_sock->timeout); } } redis_sock->stream = php_stream_xport_create(host, host_len, ENFORCE_SAFE_MODE, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, persistent_id, tv_ptr, NULL, &errstr, &err ); if (persistent_id) { efree(persistent_id); } efree(host); if (!redis_sock->stream) { efree(errstr); return -1; } /* set TCP_NODELAY */ sock = (php_netstream_data_t*)redis_sock->stream->abstract; setsockopt(sock->socket, IPPROTO_TCP, TCP_NODELAY, (char *) &tcp_flag, sizeof(int)); php_stream_auto_cleanup(redis_sock->stream); if(tv.tv_sec != 0 || tv.tv_usec != 0) { php_stream_set_option(redis_sock->stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &read_tv); } php_stream_set_option(redis_sock->stream, PHP_STREAM_OPTION_WRITE_BUFFER, PHP_STREAM_BUFFER_NONE, NULL); redis_sock->status = REDIS_SOCK_STATUS_CONNECTED; return 0; } /** * redis_sock_server_open */ PHPAPI int redis_sock_server_open(RedisSock *redis_sock, int force_connect TSRMLS_DC) { int res = -1; switch (redis_sock->status) { case REDIS_SOCK_STATUS_DISCONNECTED: return redis_sock_connect(redis_sock TSRMLS_CC); case REDIS_SOCK_STATUS_CONNECTED: res = 0; break; case REDIS_SOCK_STATUS_UNKNOWN: if (force_connect > 0 && redis_sock_connect(redis_sock TSRMLS_CC) < 0) { res = -1; } else { res = 0; redis_sock->status = REDIS_SOCK_STATUS_CONNECTED; } break; } return res; } /** * redis_sock_disconnect */ PHPAPI int redis_sock_disconnect(RedisSock *redis_sock TSRMLS_DC) { if (redis_sock == NULL) { return 1; } redis_sock->dbNumber = 0; if (redis_sock->stream != NULL) { if (!redis_sock->persistent) { redis_sock_write(redis_sock, "QUIT", sizeof("QUIT") - 1 TSRMLS_CC); } redis_sock->status = REDIS_SOCK_STATUS_DISCONNECTED; redis_sock->watching = 0; if(redis_sock->stream && !redis_sock->persistent) { /* still valid after the write? */ php_stream_close(redis_sock->stream); } redis_sock->stream = NULL; return 1; } return 0; } PHPAPI void redis_send_discard(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock) { char *cmd; int response_len, cmd_len; char * response; cmd_len = redis_cmd_format_static(&cmd, "DISCARD", ""); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); RETURN_FALSE; } efree(cmd); if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { RETURN_FALSE; } if(response_len == 3 && strncmp(response, "+OK", 3) == 0) { RETURN_TRUE; } RETURN_FALSE; } /** * redis_sock_set_err */ PHPAPI int redis_sock_set_err(RedisSock *redis_sock, const char *msg, int msg_len) { // Allocate/Reallocate our last error member if(msg != NULL && msg_len > 0) { if(redis_sock->err == NULL) { redis_sock->err = emalloc(msg_len + 1); } else if(msg_len > redis_sock->err_len) { redis_sock->err = erealloc(redis_sock->err, msg_len +1); } // Copy in our new error message, set new length, and null terminate memcpy(redis_sock->err, msg, msg_len); redis_sock->err[msg_len] = '\0'; redis_sock->err_len = msg_len; } else { // Free our last error if(redis_sock->err != NULL) { efree(redis_sock->err); } // Set to null, with zero length redis_sock->err = NULL; redis_sock->err_len = 0; } // Success return 0; } /** * redis_sock_read_multibulk_reply */ PHPAPI int redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char inbuf[1024]; int numElems; zval *z_multi_result; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return -1; } if(inbuf[0] != '*') { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETVAL_FALSE; } return -1; } numElems = atoi(inbuf+1); MAKE_STD_ZVAL(z_multi_result); array_init(z_multi_result); /* pre-allocate array for multi's results. */ redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_multi_result, numElems, 1, UNSERIALIZE_ALL); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_multi_result); } else { *return_value = *z_multi_result; efree(z_multi_result); } //zval_copy_ctor(return_value); return 0; } /** * Like multibulk reply, but don't touch the values, they won't be compressed. (this is used by HKEYS). */ PHPAPI int redis_sock_read_multibulk_reply_raw(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char inbuf[1024]; int numElems; zval *z_multi_result; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return -1; } if(inbuf[0] != '*') { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETVAL_FALSE; } return -1; } numElems = atoi(inbuf+1); MAKE_STD_ZVAL(z_multi_result); array_init(z_multi_result); /* pre-allocate array for multi's results. */ redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_multi_result, numElems, 0, UNSERIALIZE_ALL); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_multi_result); } else { *return_value = *z_multi_result; efree(z_multi_result); } //zval_copy_ctor(return_value); return 0; } PHPAPI int redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, int numElems, int unwrap_key, int unserialize_even_only) { char *response; int response_len; while(numElems > 0) { response = redis_sock_read(redis_sock, &response_len TSRMLS_CC); if(response != NULL) { zval *z = NULL; int can_unserialize = unwrap_key; if(unserialize_even_only == UNSERIALIZE_ONLY_VALUES && numElems % 2 == 0) can_unserialize = 0; if(can_unserialize && redis_unserialize(redis_sock, response, response_len, &z TSRMLS_CC) == 1) { efree(response); add_next_index_zval(z_tab, z); } else { add_next_index_stringl(z_tab, response, response_len, 0); } } else { add_next_index_bool(z_tab, 0); } numElems --; } return 0; } /** * redis_sock_read_multibulk_reply_assoc */ PHPAPI int redis_sock_read_multibulk_reply_assoc(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { char inbuf[1024], *response; int response_len; int i, numElems; zval *z_multi_result; zval **z_keys = ctx; if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) { redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); return -1; } if(inbuf[0] != '*') { IF_MULTI_OR_PIPELINE() { add_next_index_bool(z_tab, 0); } else { RETVAL_FALSE; } return -1; } numElems = atoi(inbuf+1); MAKE_STD_ZVAL(z_multi_result); array_init(z_multi_result); /* pre-allocate array for multi's results. */ for(i = 0; i < numElems; ++i) { response = redis_sock_read(redis_sock, &response_len TSRMLS_CC); if(response != NULL) { zval *z = NULL; if(redis_unserialize(redis_sock, response, response_len, &z TSRMLS_CC) == 1) { efree(response); add_assoc_zval_ex(z_multi_result, Z_STRVAL_P(z_keys[i]), 1+Z_STRLEN_P(z_keys[i]), z); } else { add_assoc_stringl_ex(z_multi_result, Z_STRVAL_P(z_keys[i]), 1+Z_STRLEN_P(z_keys[i]), response, response_len, 0); } } else { add_assoc_bool_ex(z_multi_result, Z_STRVAL_P(z_keys[i]), 1+Z_STRLEN_P(z_keys[i]), 0); } zval_dtor(z_keys[i]); efree(z_keys[i]); } efree(z_keys); IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_multi_result); } else { *return_value = *z_multi_result; zval_copy_ctor(return_value); INIT_PZVAL(return_value); zval_dtor(z_multi_result); efree(z_multi_result); } return 0; } /** * redis_sock_write */ PHPAPI int redis_sock_write(RedisSock *redis_sock, char *cmd, size_t sz TSRMLS_DC) { if(redis_sock && redis_sock->status == REDIS_SOCK_STATUS_DISCONNECTED) { zend_throw_exception(redis_exception_ce, "Connection closed", 0 TSRMLS_CC); return -1; } if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } return php_stream_write(redis_sock->stream, cmd, sz); } /** * redis_free_socket */ PHPAPI void redis_free_socket(RedisSock *redis_sock) { if(redis_sock->prefix) { efree(redis_sock->prefix); } if(redis_sock->err) { efree(redis_sock->err); } if(redis_sock->auth) { efree(redis_sock->auth); } if(redis_sock->persistent_id) { efree(redis_sock->persistent_id); } efree(redis_sock->host); efree(redis_sock); } PHPAPI int redis_serialize(RedisSock *redis_sock, zval *z, char **val, int *val_len TSRMLS_DC) { #if ZEND_MODULE_API_NO >= 20100000 php_serialize_data_t ht; #else HashTable ht; #endif smart_str sstr = {0}; zval *z_copy; size_t sz; uint8_t *val8; switch(redis_sock->serializer) { case REDIS_SERIALIZER_NONE: switch(Z_TYPE_P(z)) { case IS_STRING: *val = Z_STRVAL_P(z); *val_len = Z_STRLEN_P(z); return 0; case IS_OBJECT: MAKE_STD_ZVAL(z_copy); ZVAL_STRINGL(z_copy, "Object", 6, 1); break; case IS_ARRAY: MAKE_STD_ZVAL(z_copy); ZVAL_STRINGL(z_copy, "Array", 5, 1); break; default: /* copy */ MAKE_STD_ZVAL(z_copy); *z_copy = *z; zval_copy_ctor(z_copy); break; } /* return string */ convert_to_string(z_copy); *val = Z_STRVAL_P(z_copy); *val_len = Z_STRLEN_P(z_copy); efree(z_copy); return 1; case REDIS_SERIALIZER_PHP: #if ZEND_MODULE_API_NO >= 20100000 PHP_VAR_SERIALIZE_INIT(ht); #else zend_hash_init(&ht, 10, NULL, NULL, 0); #endif php_var_serialize(&sstr, &z, &ht TSRMLS_CC); *val = sstr.c; *val_len = (int)sstr.len; #if ZEND_MODULE_API_NO >= 20100000 PHP_VAR_SERIALIZE_DESTROY(ht); #else zend_hash_destroy(&ht); #endif return 1; case REDIS_SERIALIZER_IGBINARY: #ifdef HAVE_REDIS_IGBINARY if(igbinary_serialize(&val8, (size_t *)&sz, z TSRMLS_CC) == 0) { /* ok */ *val = (char*)val8; *val_len = (int)sz; return 1; } #endif return 0; } return 0; } PHPAPI int redis_unserialize(RedisSock *redis_sock, const char *val, int val_len, zval **return_value TSRMLS_DC) { php_unserialize_data_t var_hash; int ret, rv_free = 0; switch(redis_sock->serializer) { case REDIS_SERIALIZER_NONE: return 0; case REDIS_SERIALIZER_PHP: if(!*return_value) { MAKE_STD_ZVAL(*return_value); rv_free = 1; } #if ZEND_MODULE_API_NO >= 20100000 PHP_VAR_UNSERIALIZE_INIT(var_hash); #else memset(&var_hash, 0, sizeof(var_hash)); #endif if(!php_var_unserialize(return_value, (const unsigned char**)&val, (const unsigned char*)val + val_len, &var_hash TSRMLS_CC)) { if(rv_free==1) efree(*return_value); ret = 0; } else { ret = 1; } #if ZEND_MODULE_API_NO >= 20100000 PHP_VAR_UNSERIALIZE_DESTROY(var_hash); #else var_destroy(&var_hash); #endif return ret; case REDIS_SERIALIZER_IGBINARY: #ifdef HAVE_REDIS_IGBINARY if(!*return_value) { MAKE_STD_ZVAL(*return_value); } if(igbinary_unserialize((const uint8_t *)val, (size_t)val_len, return_value TSRMLS_CC) == 0) { return 1; } efree(*return_value); #endif return 0; break; } return 0; } PHPAPI int redis_key_prefix(RedisSock *redis_sock, char **key, int *key_len TSRMLS_DC) { int ret_len; char *ret; if(redis_sock->prefix == NULL || redis_sock->prefix_len == 0) { return 0; } ret_len = redis_sock->prefix_len + *key_len; ret = ecalloc(1 + ret_len, 1); memcpy(ret, redis_sock->prefix, redis_sock->prefix_len); memcpy(ret + redis_sock->prefix_len, *key, *key_len); *key = ret; *key_len = ret_len; return 1; } /* * Processing for variant reply types (think EVAL) */ PHPAPI int redis_sock_gets(RedisSock *redis_sock, char *buf, int buf_size, size_t *line_size TSRMLS_DC) { // Handle EOF if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { return -1; } if(php_stream_get_line(redis_sock->stream, buf, buf_size, line_size) == NULL) { // Close, put our socket state into error redis_stream_close(redis_sock TSRMLS_CC); redis_sock->stream = NULL; redis_sock->status = REDIS_SOCK_STATUS_FAILED; redis_sock->mode = ATOMIC; redis_sock->watching = 0; // Throw a read error exception zend_throw_exception(redis_exception_ce, "read error on connection", 0 TSRMLS_CC); } // We don't need \r\n *line_size-=2; buf[*line_size]='\0'; // Success! return 0; } PHPAPI int redis_read_reply_type(RedisSock *redis_sock, REDIS_REPLY_TYPE *reply_type, int *reply_info TSRMLS_DC) { // Make sure we haven't lost the connection, even trying to reconnect if(-1 == redis_check_eof(redis_sock TSRMLS_CC)) { // Failure return -1; } // Attempt to read the reply-type byte if((*reply_type = php_stream_getc(redis_sock->stream)) == EOF) { zend_throw_exception(redis_exception_ce, "socket error on read socket", 0 TSRMLS_CC); } // If this is a BULK, MULTI BULK, or simply an INTEGER response, we can extract the value or size info here if(*reply_type == TYPE_INT || *reply_type == TYPE_BULK || *reply_type == TYPE_MULTIBULK) { // Buffer to hold size information char inbuf[255]; // Read up to our newline if(php_stream_gets(redis_sock->stream, inbuf, sizeof(inbuf)) < 0) { return -1; } // Set our size response *reply_info = atoi(inbuf); } // Success! return 0; } /* * Read a single line response, having already consumed the reply-type byte */ PHPAPI int redis_read_variant_line(RedisSock *redis_sock, REDIS_REPLY_TYPE reply_type, zval **z_ret TSRMLS_DC) { // Buffer to read our single line reply char inbuf[1024]; size_t line_size; // Attempt to read our single line reply if(redis_sock_gets(redis_sock, inbuf, sizeof(inbuf), &line_size TSRMLS_CC) < 0) { return -1; } // If this is an error response, check if it is a SYNC error, and throw in that case if(reply_type == TYPE_ERR) { if(memcmp(inbuf, "ERR SYNC", 9) == 0) { zend_throw_exception(redis_exception_ce, "SYNC with master in progress", 0 TSRMLS_CC); } // Set our last error redis_sock_set_err(redis_sock, inbuf, line_size); // Set our response to FALSE ZVAL_FALSE(*z_ret); } else { // Set our response to TRUE ZVAL_TRUE(*z_ret); } return 0; } PHPAPI int redis_read_variant_bulk(RedisSock *redis_sock, int size, zval **z_ret TSRMLS_DC) { // Attempt to read the bulk reply char *bulk_resp = redis_sock_read_bulk_reply(redis_sock, size TSRMLS_CC); // Set our reply to FALSE on failure, and the string on success if(bulk_resp == NULL) { ZVAL_FALSE(*z_ret); return -1; } else { ZVAL_STRINGL(*z_ret, bulk_resp, size, 0); return 0; } } PHPAPI int redis_read_multibulk_recursive(RedisSock *redis_sock, int elements, zval **z_ret TSRMLS_DC) { int reply_info; REDIS_REPLY_TYPE reply_type; zval *z_subelem; // Iterate while we have elements while(elements > 0) { // Attempt to read our reply type if(redis_read_reply_type(redis_sock, &reply_type, &reply_info TSRMLS_CC) < 0) { zend_throw_exception_ex(redis_exception_ce, 0 TSRMLS_CC, "protocol error, couldn't parse MULTI-BULK response\n", reply_type); return -1; } // Switch on our reply-type byte switch(reply_type) { case TYPE_ERR: case TYPE_LINE: ALLOC_INIT_ZVAL(z_subelem); redis_read_variant_line(redis_sock, reply_type, &z_subelem TSRMLS_CC); add_next_index_zval(*z_ret, z_subelem); break; case TYPE_INT: // Add our long value add_next_index_long(*z_ret, reply_info); break; case TYPE_BULK: // Init a zval for our bulk response, read and add it ALLOC_INIT_ZVAL(z_subelem); redis_read_variant_bulk(redis_sock, reply_info, &z_subelem TSRMLS_CC); add_next_index_zval(*z_ret, z_subelem); break; case TYPE_MULTIBULK: // Construct an array for our sub element, and add it, and recurse ALLOC_INIT_ZVAL(z_subelem); array_init(z_subelem); add_next_index_zval(*z_ret, z_subelem); redis_read_multibulk_recursive(redis_sock, reply_info, &z_subelem TSRMLS_CC); break; } // Decrement our element counter elements--; } return 0; } PHPAPI int redis_read_variant_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab) { // Reply type, and reply size vars REDIS_REPLY_TYPE reply_type; int reply_info; //char *bulk_resp; zval *z_ret; // Attempt to read our header if(redis_read_reply_type(redis_sock, &reply_type, &reply_info TSRMLS_CC) < 0) { return -1; } // Our return ZVAL MAKE_STD_ZVAL(z_ret); // Switch based on our top level reply type switch(reply_type) { case TYPE_ERR: case TYPE_LINE: redis_read_variant_line(redis_sock, reply_type, &z_ret TSRMLS_CC); break; case TYPE_INT: ZVAL_LONG(z_ret, reply_info); break; case TYPE_BULK: redis_read_variant_bulk(redis_sock, reply_info, &z_ret TSRMLS_CC); break; case TYPE_MULTIBULK: // Initialize an array for our multi-bulk response array_init(z_ret); // If we've got more than zero elements, parse our multi bulk respoinse recursively if(reply_info > -1) { redis_read_multibulk_recursive(redis_sock, reply_info, &z_ret TSRMLS_CC); } break; default: // Protocol error zend_throw_exception_ex(redis_exception_ce, 0 TSRMLS_CC, "protocol error, got '%c' as reply-type byte\n", reply_type); break; } IF_MULTI_OR_PIPELINE() { add_next_index_zval(z_tab, z_ret); } else { // Set our return value *return_value = *z_ret; zval_copy_ctor(return_value); zval_dtor(z_ret); efree(z_ret); } // Success return 0; } /* vim: set tabstop=4 softtabstop=4 noexpandtab shiftwidth=4: */ redis-2.2.4/library.h0000664000175000017500000001217612211042406014305 0ustar nicolasnicolasvoid add_constant_long(zend_class_entry *ce, char *name, int value); int integer_length(int i); int redis_cmd_format(char **ret, char *format, ...); int redis_cmd_format_static(char **ret, char *keyword, char *format, ...); int redis_cmd_format_header(char **ret, char *keyword, int arg_count); int redis_cmd_append_str(char **cmd, int cmd_len, char *append, int append_len); int redis_cmd_init_sstr(smart_str *str, int num_args, char *keyword, int keyword_len); int redis_cmd_append_sstr(smart_str *str, char *append, int append_len); int redis_cmd_append_sstr_int(smart_str *str, int append); int redis_cmd_append_sstr_long(smart_str *str, long append); int redis_cmd_append_int(char **cmd, int cmd_len, int append); int redis_cmd_append_sstr_dbl(smart_str *str, double value); PHPAPI char * redis_sock_read(RedisSock *redis_sock, int *buf_len TSRMLS_DC); PHPAPI void redis_1_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_long_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval* z_tab, void *ctx); typedef void (*SuccessCallback)(RedisSock *redis_sock); PHPAPI void redis_boolean_response_impl(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx, SuccessCallback success_callback); PHPAPI void redis_boolean_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_bulk_double_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_string_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_ping_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_info_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void redis_type_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI RedisSock* redis_sock_create(char *host, int host_len, unsigned short port, double timeout, int persistent, char *persistent_id, long retry_interval, zend_bool lazy_connect); PHPAPI int redis_sock_connect(RedisSock *redis_sock TSRMLS_DC); PHPAPI int redis_sock_server_open(RedisSock *redis_sock, int force_connect TSRMLS_DC); PHPAPI int redis_sock_disconnect(RedisSock *redis_sock TSRMLS_DC); PHPAPI zval *redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock); PHPAPI char *redis_sock_read_bulk_reply(RedisSock *redis_sock, int bytes TSRMLS_DC); PHPAPI int redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *_z_tab, void *ctx); PHPAPI int redis_sock_read_multibulk_reply_raw(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI int redis_sock_read_multibulk_reply_loop(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, int numElems, int unwrap_key, int unserialize_even_only); PHPAPI int redis_sock_read_multibulk_reply_zipped(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI int redis_sock_read_multibulk_reply_zipped_strings(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI int redis_sock_read_multibulk_reply_assoc(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI int redis_sock_write(RedisSock *redis_sock, char *cmd, size_t sz TSRMLS_DC); PHPAPI void redis_stream_close(RedisSock *redis_sock TSRMLS_DC); PHPAPI int redis_check_eof(RedisSock *redis_sock TSRMLS_DC); //PHPAPI int redis_sock_get(zval *id, RedisSock **redis_sock TSRMLS_DC); PHPAPI void redis_free_socket(RedisSock *redis_sock); PHPAPI void redis_send_discard(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock); PHPAPI int redis_sock_set_err(RedisSock *redis_sock, const char *msg, int msg_len); PHPAPI int redis_serialize(RedisSock *redis_sock, zval *z, char **val, int *val_len TSRMLS_DC); PHPAPI int redis_key_prefix(RedisSock *redis_sock, char **key, int *key_len TSRMLS_DC); PHPAPI int redis_unserialize(RedisSock *redis_sock, const char *val, int val_len, zval **return_value TSRMLS_DC); /* * Variant Read methods, mostly to implement eval */ PHPAPI int redis_read_reply_type(RedisSock *redis_sock, REDIS_REPLY_TYPE *reply_type, int *reply_info TSRMLS_DC); PHPAPI int redis_read_variant_line(RedisSock *redis_sock, REDIS_REPLY_TYPE reply_type, zval **z_ret TSRMLS_DC); PHPAPI int redis_read_variant_bulk(RedisSock *redis_sock, int size, zval **z_ret TSRMLS_DC); PHPAPI int redis_read_multibulk_recursive(RedisSock *redis_sock, int elements, zval **z_ret TSRMLS_DC); PHPAPI int redis_read_variant_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab); PHPAPI void redis_client_list_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab); #if ZEND_MODULE_API_NO >= 20100000 #define REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, dbl) \ char dbl_decsep; \ dbl_decsep = '.'; \ dbl_str = _php_math_number_format_ex(dbl, 16, &dbl_decsep, 1, NULL, 0); \ dbl_len = strlen(dbl_str); #else #define REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, dbl) \ dbl_str = _php_math_number_format(dbl, 16, '.', '\x00'); \ dbl_len = strlen(dbl_str); #endif redis-2.2.4/php_redis.h0000664000175000017500000002024512211042406014612 0ustar nicolasnicolas/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2009 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Original author: Alfonso Jimenez | | Maintainer: Nicolas Favre-Felix | | Maintainer: Nasreddine Bouafif | +----------------------------------------------------------------------+ */ #include "common.h" #ifndef PHP_REDIS_H #define PHP_REDIS_H PHP_METHOD(Redis, __construct); PHP_METHOD(Redis, __destruct); PHP_METHOD(Redis, connect); PHP_METHOD(Redis, pconnect); PHP_METHOD(Redis, close); PHP_METHOD(Redis, ping); PHP_METHOD(Redis, echo); PHP_METHOD(Redis, get); PHP_METHOD(Redis, set); PHP_METHOD(Redis, setex); PHP_METHOD(Redis, psetex); PHP_METHOD(Redis, setnx); PHP_METHOD(Redis, getSet); PHP_METHOD(Redis, randomKey); PHP_METHOD(Redis, renameKey); PHP_METHOD(Redis, renameNx); PHP_METHOD(Redis, getMultiple); PHP_METHOD(Redis, exists); PHP_METHOD(Redis, delete); PHP_METHOD(Redis, incr); PHP_METHOD(Redis, incrBy); PHP_METHOD(Redis, incrByFloat); PHP_METHOD(Redis, decr); PHP_METHOD(Redis, decrBy); PHP_METHOD(Redis, type); PHP_METHOD(Redis, append); PHP_METHOD(Redis, getRange); PHP_METHOD(Redis, setRange); PHP_METHOD(Redis, getBit); PHP_METHOD(Redis, setBit); PHP_METHOD(Redis, strlen); PHP_METHOD(Redis, getKeys); PHP_METHOD(Redis, sort); PHP_METHOD(Redis, sortAsc); PHP_METHOD(Redis, sortAscAlpha); PHP_METHOD(Redis, sortDesc); PHP_METHOD(Redis, sortDescAlpha); PHP_METHOD(Redis, lPush); PHP_METHOD(Redis, lPushx); PHP_METHOD(Redis, rPush); PHP_METHOD(Redis, rPushx); PHP_METHOD(Redis, lPop); PHP_METHOD(Redis, rPop); PHP_METHOD(Redis, blPop); PHP_METHOD(Redis, brPop); PHP_METHOD(Redis, lSize); PHP_METHOD(Redis, lRemove); PHP_METHOD(Redis, listTrim); PHP_METHOD(Redis, lGet); PHP_METHOD(Redis, lGetRange); PHP_METHOD(Redis, lSet); PHP_METHOD(Redis, lInsert); PHP_METHOD(Redis, sAdd); PHP_METHOD(Redis, sSize); PHP_METHOD(Redis, sRemove); PHP_METHOD(Redis, sMove); PHP_METHOD(Redis, sPop); PHP_METHOD(Redis, sRandMember); PHP_METHOD(Redis, sContains); PHP_METHOD(Redis, sMembers); PHP_METHOD(Redis, sInter); PHP_METHOD(Redis, sInterStore); PHP_METHOD(Redis, sUnion); PHP_METHOD(Redis, sUnionStore); PHP_METHOD(Redis, sDiff); PHP_METHOD(Redis, sDiffStore); PHP_METHOD(Redis, setTimeout); PHP_METHOD(Redis, pexpire); PHP_METHOD(Redis, save); PHP_METHOD(Redis, bgSave); PHP_METHOD(Redis, lastSave); PHP_METHOD(Redis, flushDB); PHP_METHOD(Redis, flushAll); PHP_METHOD(Redis, dbSize); PHP_METHOD(Redis, auth); PHP_METHOD(Redis, ttl); PHP_METHOD(Redis, pttl); PHP_METHOD(Redis, persist); PHP_METHOD(Redis, info); PHP_METHOD(Redis, resetStat); PHP_METHOD(Redis, select); PHP_METHOD(Redis, move); PHP_METHOD(Redis, zAdd); PHP_METHOD(Redis, zDelete); PHP_METHOD(Redis, zRange); PHP_METHOD(Redis, zReverseRange); PHP_METHOD(Redis, zRangeByScore); PHP_METHOD(Redis, zRevRangeByScore); PHP_METHOD(Redis, zCount); PHP_METHOD(Redis, zDeleteRangeByScore); PHP_METHOD(Redis, zDeleteRangeByRank); PHP_METHOD(Redis, zCard); PHP_METHOD(Redis, zScore); PHP_METHOD(Redis, zRank); PHP_METHOD(Redis, zRevRank); PHP_METHOD(Redis, zIncrBy); PHP_METHOD(Redis, zInter); PHP_METHOD(Redis, zUnion); PHP_METHOD(Redis, expireAt); PHP_METHOD(Redis, pexpireAt); PHP_METHOD(Redis, bgrewriteaof); PHP_METHOD(Redis, slaveof); PHP_METHOD(Redis, object); PHP_METHOD(Redis, bitop); PHP_METHOD(Redis, bitcount); PHP_METHOD(Redis, eval); PHP_METHOD(Redis, evalsha); PHP_METHOD(Redis, script); PHP_METHOD(Redis, dump); PHP_METHOD(Redis, restore); PHP_METHOD(Redis, migrate); PHP_METHOD(Redis, time); PHP_METHOD(Redis, getLastError); PHP_METHOD(Redis, clearLastError); PHP_METHOD(Redis, _prefix); PHP_METHOD(Redis, _unserialize); PHP_METHOD(Redis, mset); PHP_METHOD(Redis, msetnx); PHP_METHOD(Redis, rpoplpush); PHP_METHOD(Redis, brpoplpush); PHP_METHOD(Redis, hGet); PHP_METHOD(Redis, hSet); PHP_METHOD(Redis, hSetNx); PHP_METHOD(Redis, hDel); PHP_METHOD(Redis, hLen); PHP_METHOD(Redis, hKeys); PHP_METHOD(Redis, hVals); PHP_METHOD(Redis, hGetAll); PHP_METHOD(Redis, hExists); PHP_METHOD(Redis, hIncrBy); PHP_METHOD(Redis, hIncrByFloat); PHP_METHOD(Redis, hMset); PHP_METHOD(Redis, hMget); PHP_METHOD(Redis, multi); PHP_METHOD(Redis, discard); PHP_METHOD(Redis, exec); PHP_METHOD(Redis, watch); PHP_METHOD(Redis, unwatch); PHP_METHOD(Redis, pipeline); PHP_METHOD(Redis, publish); PHP_METHOD(Redis, subscribe); PHP_METHOD(Redis, psubscribe); PHP_METHOD(Redis, unsubscribe); PHP_METHOD(Redis, punsubscribe); PHP_METHOD(Redis, getOption); PHP_METHOD(Redis, setOption); PHP_METHOD(Redis, config); PHP_METHOD(Redis, slowlog); PHP_METHOD(Redis, client); PHP_METHOD(Redis, getHost); PHP_METHOD(Redis, getPort); PHP_METHOD(Redis, getDBNum); PHP_METHOD(Redis, getTimeout); PHP_METHOD(Redis, getReadTimeout); PHP_METHOD(Redis, isConnected); PHP_METHOD(Redis, getPersistentID); PHP_METHOD(Redis, getAuth); #ifdef PHP_WIN32 #define PHP_REDIS_API __declspec(dllexport) #else #define PHP_REDIS_API #endif #ifdef ZTS #include "TSRM.h" #endif PHP_MINIT_FUNCTION(redis); PHP_MSHUTDOWN_FUNCTION(redis); PHP_RINIT_FUNCTION(redis); PHP_RSHUTDOWN_FUNCTION(redis); PHP_MINFO_FUNCTION(redis); PHPAPI int redis_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent); PHPAPI void redis_atomic_increment(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int count); PHPAPI int generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len, int min_argc, RedisSock **redis_sock, int has_timeout, int all_keys, int can_serialize); PHPAPI void generic_sort_cmd(INTERNAL_FUNCTION_PARAMETERS, char *sort, int use_alpha); typedef void (*ResultCallback)(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); PHPAPI void generic_empty_cmd_impl(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ResultCallback result_callback); PHPAPI void generic_empty_cmd(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ...); PHPAPI void generic_empty_long_cmd(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ...); PHPAPI void generic_subscribe_cmd(INTERNAL_FUNCTION_PARAMETERS, char *sub_cmd); PHPAPI void generic_unsubscribe_cmd(INTERNAL_FUNCTION_PARAMETERS, char *unsub_cmd); PHPAPI void array_zip_values_and_scores(RedisSock *redis_sock, zval *z_tab, int use_atof TSRMLS_DC); PHPAPI int redis_response_enqueued(RedisSock *redis_sock TSRMLS_DC); PHPAPI int get_flag(zval *object TSRMLS_DC); PHPAPI void set_flag(zval *object, int new_flag TSRMLS_DC); PHPAPI int redis_sock_read_multibulk_multi_reply_loop(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, int numElems); /* pipeline */ PHPAPI request_item* get_pipeline_head(zval *object); PHPAPI void set_pipeline_head(zval *object, request_item *head); PHPAPI request_item* get_pipeline_current(zval *object); PHPAPI void set_pipeline_current(zval *object, request_item *current); #ifndef _MSC_VER ZEND_BEGIN_MODULE_GLOBALS(redis) ZEND_END_MODULE_GLOBALS(redis) #endif struct redis_queued_item { /* reading function */ zval * (*fun)(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, ...); char *cmd; int cmd_len; struct redis_queued_item *next; }; extern zend_module_entry redis_module_entry; #define redis_module_ptr &redis_module_entry #define phpext_redis_ptr redis_module_ptr #define PHP_REDIS_VERSION "2.2.4" #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ redis-2.2.4/redis_array.c0000664000175000017500000010637412211042406015144 0ustar nicolasnicolas/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2009 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Nicolas Favre-Felix | | Maintainer: Michael Grunder | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "common.h" #include "ext/standard/info.h" #include "php_ini.h" #include "php_redis.h" #include "redis_array.h" #include #include "library.h" #include "redis_array.h" #include "redis_array_impl.h" extern zend_class_entry *redis_ce; zend_class_entry *redis_array_ce; ZEND_BEGIN_ARG_INFO_EX(__redis_array_call_args, 0, 0, 2) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, arguments) ZEND_END_ARG_INFO() zend_function_entry redis_array_functions[] = { PHP_ME(RedisArray, __construct, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, __call, __redis_array_call_args, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _hosts, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _target, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _instance, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _function, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _distributor, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, _rehash, NULL, ZEND_ACC_PUBLIC) /* special implementation for a few functions */ PHP_ME(RedisArray, select, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, info, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, ping, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, flushdb, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, flushall, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, mget, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, mset, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, del, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, getOption, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, setOption, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, keys, NULL, ZEND_ACC_PUBLIC) /* Multi/Exec */ PHP_ME(RedisArray, multi, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, exec, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, discard, NULL, ZEND_ACC_PUBLIC) PHP_ME(RedisArray, unwatch, NULL, ZEND_ACC_PUBLIC) /* Aliases */ PHP_MALIAS(RedisArray, delete, del, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(RedisArray, getMultiple, mget, NULL, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; int le_redis_array; void redis_destructor_redis_array(zend_rsrc_list_entry * rsrc TSRMLS_DC) { int i; RedisArray *ra = (RedisArray*)rsrc->ptr; /* delete Redis objects */ for(i = 0; i < ra->count; ++i) { zval_dtor(ra->redis[i]); efree(ra->redis[i]); /* remove host too */ efree(ra->hosts[i]); } efree(ra->redis); efree(ra->hosts); /* delete function */ if(ra->z_fun) { zval_dtor(ra->z_fun); efree(ra->z_fun); } /* delete distributor */ if(ra->z_dist) { zval_dtor(ra->z_dist); efree(ra->z_dist); } /* delete list of pure commands */ zval_dtor(ra->z_pure_cmds); efree(ra->z_pure_cmds); /* free container */ efree(ra); } /** * redis_array_get */ PHPAPI int redis_array_get(zval *id, RedisArray **ra TSRMLS_DC) { zval **socket; int resource_type; if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), "socket", sizeof("socket"), (void **) &socket) == FAILURE) { return -1; } *ra = (RedisArray *) zend_list_find(Z_LVAL_PP(socket), &resource_type); if (!*ra || resource_type != le_redis_array) { return -1; } return Z_LVAL_PP(socket); } uint32_t rcrc32(const char *s, size_t sz) { static const uint32_t table[256] = { 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535, 0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD, 0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D, 0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC, 0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4, 0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C, 0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC, 0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F, 0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB, 0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F, 0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB, 0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E, 0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA, 0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE, 0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A, 0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9, 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409, 0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81, 0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739, 0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8, 0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268, 0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0, 0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8, 0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B, 0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF, 0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703, 0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7, 0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A, 0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE, 0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242, 0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6, 0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45, 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D, 0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5, 0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605, 0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94, 0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D}; unsigned long ret = 0xffffffff; size_t i; for (i = 0; i < sz; i++) { ret = (ret >> 8) ^ table[ (ret ^ ((unsigned char)s[i])) & 0xFF ]; } return (ret ^ 0xFFFFFFFF); } /* {{{ proto RedisArray RedisArray::__construct() Public constructor */ PHP_METHOD(RedisArray, __construct) { zval *z0, *z_fun = NULL, *z_dist = NULL, **zpData, *z_opts = NULL; int id; RedisArray *ra = NULL; zend_bool b_index = 0, b_autorehash = 0, b_pconnect = 0; HashTable *hPrev = NULL, *hOpts = NULL; long l_retry_interval = 0; zend_bool b_lazy_connect = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|a", &z0, &z_opts) == FAILURE) { RETURN_FALSE; } /* extract options */ if(z_opts) { hOpts = Z_ARRVAL_P(z_opts); /* extract previous ring. */ if(FAILURE != zend_hash_find(hOpts, "previous", sizeof("previous"), (void**)&zpData) && Z_TYPE_PP(zpData) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_PP(zpData)) != 0) { /* consider previous array as non-existent if empty. */ hPrev = Z_ARRVAL_PP(zpData); } /* extract function name. */ if(FAILURE != zend_hash_find(hOpts, "function", sizeof("function"), (void**)&zpData)) { MAKE_STD_ZVAL(z_fun); *z_fun = **zpData; zval_copy_ctor(z_fun); } /* extract function name. */ if(FAILURE != zend_hash_find(hOpts, "distributor", sizeof("distributor"), (void**)&zpData)) { MAKE_STD_ZVAL(z_dist); *z_dist = **zpData; zval_copy_ctor(z_dist); } /* extract index option. */ if(FAILURE != zend_hash_find(hOpts, "index", sizeof("index"), (void**)&zpData) && Z_TYPE_PP(zpData) == IS_BOOL) { b_index = Z_BVAL_PP(zpData); } /* extract autorehash option. */ if(FAILURE != zend_hash_find(hOpts, "autorehash", sizeof("autorehash"), (void**)&zpData) && Z_TYPE_PP(zpData) == IS_BOOL) { b_autorehash = Z_BVAL_PP(zpData); } /* pconnect */ if(FAILURE != zend_hash_find(hOpts, "pconnect", sizeof("pconnect"), (void**)&zpData) && Z_TYPE_PP(zpData) == IS_BOOL) { b_pconnect = Z_BVAL_PP(zpData); } /* extract retry_interval option. */ zval **z_retry_interval_pp; if (FAILURE != zend_hash_find(hOpts, "retry_interval", sizeof("retry_interval"), (void**)&z_retry_interval_pp)) { if (Z_TYPE_PP(z_retry_interval_pp) == IS_LONG || Z_TYPE_PP(z_retry_interval_pp) == IS_STRING) { if (Z_TYPE_PP(z_retry_interval_pp) == IS_LONG) { l_retry_interval = Z_LVAL_PP(z_retry_interval_pp); } else { l_retry_interval = atol(Z_STRVAL_PP(z_retry_interval_pp)); } } } /* extract lazy connect option. */ if(FAILURE != zend_hash_find(hOpts, "lazy_connect", sizeof("lazy_connect"), (void**)&zpData) && Z_TYPE_PP(zpData) == IS_BOOL) { b_lazy_connect = Z_BVAL_PP(zpData); } } /* extract either name of list of hosts from z0 */ switch(Z_TYPE_P(z0)) { case IS_STRING: ra = ra_load_array(Z_STRVAL_P(z0) TSRMLS_CC); break; case IS_ARRAY: ra = ra_make_array(Z_ARRVAL_P(z0), z_fun, z_dist, hPrev, b_index, b_pconnect, l_retry_interval, b_lazy_connect TSRMLS_CC); break; default: WRONG_PARAM_COUNT; break; } if(ra) { ra->auto_rehash = b_autorehash; #if PHP_VERSION_ID >= 50400 id = zend_list_insert(ra, le_redis_array TSRMLS_CC); #else id = zend_list_insert(ra, le_redis_array); #endif add_property_resource(getThis(), "socket", id); } } static void ra_forward_call(INTERNAL_FUNCTION_PARAMETERS, RedisArray *ra, const char *cmd, int cmd_len, zval *z_args, zval *z_new_target) { zval **zp_tmp, z_tmp; char *key = NULL; // set to avoid "unused-but-set-variable" int key_len; int i; zval *redis_inst; zval z_fun, **z_callargs; HashPosition pointer; HashTable *h_args; int argc; int failed; zend_bool b_write_cmd = 0; h_args = Z_ARRVAL_P(z_args); argc = zend_hash_num_elements(h_args); if(ra->z_multi_exec) { redis_inst = ra->z_multi_exec; /* we already have the instance */ } else { /* extract key and hash it. */ if(!(key = ra_find_key(ra, z_args, cmd, &key_len))) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Could not find key"); RETURN_FALSE; } /* find node */ redis_inst = ra_find_node(ra, key, key_len, NULL TSRMLS_CC); if(!redis_inst) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Could not find any redis servers for this key."); RETURN_FALSE; } } /* check if write cmd */ b_write_cmd = ra_is_write_cmd(ra, cmd, cmd_len); if(ra->index && b_write_cmd && !ra->z_multi_exec) { /* add MULTI + SADD */ ra_index_multi(redis_inst, MULTI TSRMLS_CC); } /* pass call through */ ZVAL_STRING(&z_fun, cmd, 0); /* method name */ z_callargs = emalloc(argc * sizeof(zval*)); /* copy args to array */ for (i = 0, zend_hash_internal_pointer_reset_ex(h_args, &pointer); zend_hash_get_current_data_ex(h_args, (void**) &zp_tmp, &pointer) == SUCCESS; ++i, zend_hash_move_forward_ex(h_args, &pointer)) { z_callargs[i] = *zp_tmp; } /* multi/exec */ if(ra->z_multi_exec) { call_user_function(&redis_ce->function_table, &ra->z_multi_exec, &z_fun, return_value, argc, z_callargs TSRMLS_CC); efree(z_callargs); RETURN_ZVAL(getThis(), 1, 0); } /* CALL! */ if(ra->index && b_write_cmd) { /* call using discarded temp value and extract exec results after. */ call_user_function(&redis_ce->function_table, &redis_inst, &z_fun, &z_tmp, argc, z_callargs TSRMLS_CC); zval_dtor(&z_tmp); /* add keys to index. */ ra_index_key(key, key_len, redis_inst TSRMLS_CC); /* call EXEC */ ra_index_exec(redis_inst, return_value, 0 TSRMLS_CC); } else { /* call directly through. */ call_user_function(&redis_ce->function_table, &redis_inst, &z_fun, return_value, argc, z_callargs TSRMLS_CC); failed = 0; if((Z_TYPE_P(return_value) == IS_BOOL && Z_BVAL_P(return_value) == 0) || (Z_TYPE_P(return_value) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(return_value)) == 0) || (Z_TYPE_P(return_value) == IS_LONG && Z_LVAL_P(return_value) == 0 && !strcasecmp(cmd, "TYPE"))) { failed = 1; } /* check if we have an error. */ if(failed && ra->prev && !b_write_cmd) { /* there was an error reading, try with prev ring. */ /* ERROR, FALLBACK TO PREVIOUS RING and forward a reference to the first redis instance we were looking at. */ ra_forward_call(INTERNAL_FUNCTION_PARAM_PASSTHRU, ra->prev, cmd, cmd_len, z_args, z_new_target?z_new_target:redis_inst); } if(!failed && !b_write_cmd && z_new_target && ra->auto_rehash) { /* move key from old ring to new ring */ ra_move_key(key, key_len, redis_inst, z_new_target TSRMLS_CC); } } /* cleanup */ efree(z_callargs); } PHP_METHOD(RedisArray, __call) { zval *object; RedisArray *ra; zval *z_args; char *cmd; int cmd_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osa", &object, redis_array_ce, &cmd, &cmd_len, &z_args) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } ra_forward_call(INTERNAL_FUNCTION_PARAM_PASSTHRU, ra, cmd, cmd_len, z_args, NULL); } PHP_METHOD(RedisArray, _hosts) { zval *object; int i; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } array_init(return_value); for(i = 0; i < ra->count; ++i) { add_next_index_string(return_value, ra->hosts[i], 1); } } PHP_METHOD(RedisArray, _target) { zval *object; RedisArray *ra; char *key; int key_len, i; zval *redis_inst; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_array_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } redis_inst = ra_find_node(ra, key, key_len, &i TSRMLS_CC); if(redis_inst) { ZVAL_STRING(return_value, ra->hosts[i], 1); } else { RETURN_NULL(); } } PHP_METHOD(RedisArray, _instance) { zval *object; RedisArray *ra; char *target; int target_len; zval *z_redis; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_array_ce, &target, &target_len) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } z_redis = ra_find_node_by_name(ra, target, target_len TSRMLS_CC); if(z_redis) { RETURN_ZVAL(z_redis, 1, 0); } else { RETURN_NULL(); } } PHP_METHOD(RedisArray, _function) { zval *object; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } if(ra->z_fun) { *return_value = *ra->z_fun; zval_copy_ctor(return_value); } else { RETURN_NULL(); } } PHP_METHOD(RedisArray, _distributor) { zval *object; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } if(ra->z_fun) { *return_value = *ra->z_fun; zval_copy_ctor(return_value); } else { RETURN_NULL(); } } PHP_METHOD(RedisArray, _rehash) { zval *object; RedisArray *ra; zend_fcall_info z_cb; zend_fcall_info_cache z_cb_cache; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|f", &object, redis_array_ce, &z_cb, &z_cb_cache) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 0) { ra_rehash(ra, NULL, NULL TSRMLS_CC); } else { ra_rehash(ra, &z_cb, &z_cb_cache TSRMLS_CC); } } static void multihost_distribute(INTERNAL_FUNCTION_PARAMETERS, const char *method_name) { zval *object, z_fun, *z_tmp; int i; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* prepare call */ ZVAL_STRING(&z_fun, method_name, 0); array_init(return_value); for(i = 0; i < ra->count; ++i) { MAKE_STD_ZVAL(z_tmp); /* Call each node in turn */ call_user_function(&redis_ce->function_table, &ra->redis[i], &z_fun, z_tmp, 0, NULL TSRMLS_CC); add_assoc_zval(return_value, ra->hosts[i], z_tmp); } } PHP_METHOD(RedisArray, info) { multihost_distribute(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INFO"); } PHP_METHOD(RedisArray, ping) { multihost_distribute(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PING"); } PHP_METHOD(RedisArray, flushdb) { multihost_distribute(INTERNAL_FUNCTION_PARAM_PASSTHRU, "FLUSHDB"); } PHP_METHOD(RedisArray, flushall) { multihost_distribute(INTERNAL_FUNCTION_PARAM_PASSTHRU, "FLUSHALL"); } PHP_METHOD(RedisArray, keys) { zval *object, *z_args[1], *z_tmp, z_fun; RedisArray *ra; char *pattern; int pattern_len, i; // Make sure the prototype is correct if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_array_ce, &pattern, &pattern_len) == FAILURE) { RETURN_FALSE; } // Make sure we can grab our RedisArray object if(redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } // Set up our function call (KEYS) ZVAL_STRING(&z_fun, "KEYS", 0); // We will be passing with one string argument (the pattern) MAKE_STD_ZVAL(z_args[0]); ZVAL_STRINGL(z_args[0], pattern, pattern_len, 0); // Init our array return array_init(return_value); // Iterate our RedisArray nodes for(i=0; icount; ++i) { // Return for this node MAKE_STD_ZVAL(z_tmp); // Call KEYS on each node call_user_function(&redis_ce->function_table, &ra->redis[i], &z_fun, z_tmp, 1, z_args TSRMLS_CC); // Add the result for this host add_assoc_zval(return_value, ra->hosts[i], z_tmp); } // Free arg array efree(z_args[0]); } PHP_METHOD(RedisArray, getOption) { zval *object, z_fun, *z_tmp, *z_args[1]; int i; RedisArray *ra; long opt; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, redis_array_ce, &opt) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* prepare call */ ZVAL_STRING(&z_fun, "getOption", 0); /* copy arg */ MAKE_STD_ZVAL(z_args[0]); ZVAL_LONG(z_args[0], opt); array_init(return_value); for(i = 0; i < ra->count; ++i) { MAKE_STD_ZVAL(z_tmp); /* Call each node in turn */ call_user_function(&redis_ce->function_table, &ra->redis[i], &z_fun, z_tmp, 1, z_args TSRMLS_CC); add_assoc_zval(return_value, ra->hosts[i], z_tmp); } /* cleanup */ efree(z_args[0]); } PHP_METHOD(RedisArray, setOption) { zval *object, z_fun, *z_tmp, *z_args[2]; int i; RedisArray *ra; long opt; char *val_str; int val_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ols", &object, redis_array_ce, &opt, &val_str, &val_len) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* prepare call */ ZVAL_STRING(&z_fun, "setOption", 0); /* copy args */ MAKE_STD_ZVAL(z_args[0]); ZVAL_LONG(z_args[0], opt); MAKE_STD_ZVAL(z_args[1]); ZVAL_STRINGL(z_args[1], val_str, val_len, 0); array_init(return_value); for(i = 0; i < ra->count; ++i) { MAKE_STD_ZVAL(z_tmp); /* Call each node in turn */ call_user_function(&redis_ce->function_table, &ra->redis[i], &z_fun, z_tmp, 2, z_args TSRMLS_CC); add_assoc_zval(return_value, ra->hosts[i], z_tmp); } /* cleanup */ efree(z_args[0]); efree(z_args[1]); } PHP_METHOD(RedisArray, select) { zval *object, z_fun, *z_tmp, *z_args[2]; int i; RedisArray *ra; long opt; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, redis_array_ce, &opt) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* prepare call */ ZVAL_STRING(&z_fun, "select", 0); /* copy args */ MAKE_STD_ZVAL(z_args[0]); ZVAL_LONG(z_args[0], opt); array_init(return_value); for(i = 0; i < ra->count; ++i) { MAKE_STD_ZVAL(z_tmp); /* Call each node in turn */ call_user_function(&redis_ce->function_table, &ra->redis[i], &z_fun, z_tmp, 1, z_args TSRMLS_CC); add_assoc_zval(return_value, ra->hosts[i], z_tmp); } /* cleanup */ efree(z_args[0]); } #define HANDLE_MULTI_EXEC(cmd) do {\ if (redis_array_get(getThis(), &ra TSRMLS_CC) >= 0 && ra->z_multi_exec) {\ int i, num_varargs;\ zval ***varargs = NULL;\ zval z_arg_array;\ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O*",\ &object, redis_array_ce, &varargs, &num_varargs) == FAILURE) {\ RETURN_FALSE;\ }\ /* copy all args into a zval hash table */\ array_init(&z_arg_array);\ for(i = 0; i < num_varargs; ++i) {\ zval *z_tmp;\ MAKE_STD_ZVAL(z_tmp);\ *z_tmp = **varargs[i];\ zval_copy_ctor(z_tmp);\ INIT_PZVAL(z_tmp);\ add_next_index_zval(&z_arg_array, z_tmp);\ }\ /* call */\ ra_forward_call(INTERNAL_FUNCTION_PARAM_PASSTHRU, ra, cmd, sizeof(cmd)-1, &z_arg_array, NULL);\ zval_dtor(&z_arg_array);\ if(varargs) {\ efree(varargs);\ }\ return;\ }\ }while(0) /* MGET will distribute the call to several nodes and regroup the values. */ PHP_METHOD(RedisArray, mget) { zval *object, *z_keys, z_fun, *z_argarray, **data, *z_ret, **z_cur, *z_tmp_array, *z_tmp; int i, j, n; RedisArray *ra; int *pos, argc, *argc_each; HashTable *h_keys; HashPosition pointer; zval **redis_instances, **argv; /* Multi/exec support */ HANDLE_MULTI_EXEC("MGET"); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa", &object, redis_array_ce, &z_keys) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* prepare call */ ZVAL_STRING(&z_fun, "MGET", 0); /* init data structures */ h_keys = Z_ARRVAL_P(z_keys); argc = zend_hash_num_elements(h_keys); argv = emalloc(argc * sizeof(zval*)); pos = emalloc(argc * sizeof(int)); redis_instances = emalloc(argc * sizeof(zval*)); memset(redis_instances, 0, argc * sizeof(zval*)); argc_each = emalloc(ra->count * sizeof(int)); memset(argc_each, 0, ra->count * sizeof(int)); /* associate each key to a redis node */ for (i = 0, zend_hash_internal_pointer_reset_ex(h_keys, &pointer); zend_hash_get_current_data_ex(h_keys, (void**) &data, &pointer) == SUCCESS; zend_hash_move_forward_ex(h_keys, &pointer), ++i) { /* If we need to represent a long key as a string */ unsigned int key_len; char kbuf[40], *key_lookup; /* phpredis proper can only use string or long keys, so restrict to that here */ if(Z_TYPE_PP(data) != IS_STRING && Z_TYPE_PP(data) != IS_LONG) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "MGET: all keys must be strings or longs"); efree(argv); efree(pos); efree(redis_instances); efree(argc_each); RETURN_FALSE; } /* Convert to a string for hash lookup if it isn't one */ if(Z_TYPE_PP(data) == IS_STRING) { key_len = Z_STRLEN_PP(data); key_lookup = Z_STRVAL_PP(data); } else { key_len = snprintf(kbuf, sizeof(kbuf), "%ld", Z_LVAL_PP(data)); key_lookup = (char*)kbuf; } /* Find our node */ redis_instances[i] = ra_find_node(ra, key_lookup, key_len, &pos[i] TSRMLS_CC); argc_each[pos[i]]++; /* count number of keys per node */ argv[i] = *data; } /* prepare return value */ array_init(return_value); MAKE_STD_ZVAL(z_tmp_array); array_init(z_tmp_array); /* calls */ for(n = 0; n < ra->count; ++n) { /* for each node */ /* copy args for MGET call on node. */ MAKE_STD_ZVAL(z_argarray); array_init(z_argarray); for(i = 0; i < argc; ++i) { if(pos[i] != n) continue; MAKE_STD_ZVAL(z_tmp); *z_tmp = *argv[i]; zval_copy_ctor(z_tmp); INIT_PZVAL(z_tmp); add_next_index_zval(z_argarray, z_tmp); } /* call MGET on the node */ MAKE_STD_ZVAL(z_ret); call_user_function(&redis_ce->function_table, &ra->redis[n], &z_fun, z_ret, 1, &z_argarray TSRMLS_CC); /* cleanup args array */ zval_ptr_dtor(&z_argarray); for(i = 0, j = 0; i < argc; ++i) { /* Error out if we didn't get a proper response */ if(Z_TYPE_P(z_ret) != IS_ARRAY) { /* cleanup */ zval_dtor(z_ret); efree(z_ret); zval_ptr_dtor(&z_tmp_array); efree(pos); efree(redis_instances); efree(argc_each); /* failure */ RETURN_FALSE; } if(pos[i] != n) continue; zend_hash_quick_find(Z_ARRVAL_P(z_ret), NULL, 0, j, (void**)&z_cur); j++; MAKE_STD_ZVAL(z_tmp); *z_tmp = **z_cur; zval_copy_ctor(z_tmp); INIT_PZVAL(z_tmp); add_index_zval(z_tmp_array, i, z_tmp); } zval_dtor(z_ret); efree(z_ret); } /* copy temp array in the right order to return_value */ for(i = 0; i < argc; ++i) { zend_hash_quick_find(Z_ARRVAL_P(z_tmp_array), NULL, 0, i, (void**)&z_cur); MAKE_STD_ZVAL(z_tmp); *z_tmp = **z_cur; zval_copy_ctor(z_tmp); INIT_PZVAL(z_tmp); add_next_index_zval(return_value, z_tmp); } /* cleanup */ zval_ptr_dtor(&z_tmp_array); efree(argv); efree(pos); efree(redis_instances); efree(argc_each); } /* MSET will distribute the call to several nodes and regroup the values. */ PHP_METHOD(RedisArray, mset) { zval *object, *z_keys, z_fun, *z_argarray, **data, z_ret; int i, n; RedisArray *ra; int *pos, argc, *argc_each; HashTable *h_keys; zval **redis_instances, *redis_inst, **argv; char *key, **keys, **key_free, kbuf[40]; unsigned int key_len, free_idx = 0; int type, *key_lens; unsigned long idx; /* Multi/exec support */ HANDLE_MULTI_EXEC("MSET"); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa", &object, redis_array_ce, &z_keys) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* init data structures */ h_keys = Z_ARRVAL_P(z_keys); argc = zend_hash_num_elements(h_keys); argv = emalloc(argc * sizeof(zval*)); pos = emalloc(argc * sizeof(int)); keys = emalloc(argc * sizeof(char*)); key_lens = emalloc(argc * sizeof(int)); redis_instances = emalloc(argc * sizeof(zval*)); memset(redis_instances, 0, argc * sizeof(zval*)); /* Allocate an array holding the indexes of any keys that need freeing */ key_free = emalloc(argc * sizeof(char*)); argc_each = emalloc(ra->count * sizeof(int)); memset(argc_each, 0, ra->count * sizeof(int)); /* associate each key to a redis node */ for(i = 0, zend_hash_internal_pointer_reset(h_keys); zend_hash_has_more_elements(h_keys) == SUCCESS; zend_hash_move_forward(h_keys), i++) { /* We have to skip the element if we can't get the array value */ if(zend_hash_get_current_data(h_keys, (void**)&data) == FAILURE) { continue; } /* Grab our key */ type = zend_hash_get_current_key_ex(h_keys, &key, &key_len, &idx, 0, NULL); /* If the key isn't a string, make a string representation of it */ if(type != HASH_KEY_IS_STRING) { key_len = snprintf(kbuf, sizeof(kbuf), "%ld", (long)idx); key = estrndup(kbuf, key_len); key_free[free_idx++]=key; } else { key_len--; /* We don't want the null terminator */ } redis_instances[i] = ra_find_node(ra, key, (int)key_len, &pos[i] TSRMLS_CC); argc_each[pos[i]]++; /* count number of keys per node */ argv[i] = *data; keys[i] = key; key_lens[i] = (int)key_len; } /* calls */ for(n = 0; n < ra->count; ++n) { /* for each node */ /* prepare call */ ZVAL_STRING(&z_fun, "MSET", 0); redis_inst = ra->redis[n]; /* copy args */ int found = 0; MAKE_STD_ZVAL(z_argarray); array_init(z_argarray); for(i = 0; i < argc; ++i) { if(pos[i] != n) continue; zval *z_tmp; ALLOC_ZVAL(z_tmp); *z_tmp = *argv[i]; zval_copy_ctor(z_tmp); INIT_PZVAL(z_tmp); add_assoc_zval_ex(z_argarray, keys[i], key_lens[i] + 1, z_tmp); /* +1 to count the \0 here */ found++; } if(!found) { zval_dtor(z_argarray); efree(z_argarray); continue; /* don't run empty MSETs */ } if(ra->index) { /* add MULTI */ ra_index_multi(redis_inst, MULTI TSRMLS_CC); } /* call */ call_user_function(&redis_ce->function_table, &ra->redis[n], &z_fun, &z_ret, 1, &z_argarray TSRMLS_CC); if(ra->index) { ra_index_keys(z_argarray, redis_inst TSRMLS_CC); /* use SADD to add keys to node index */ ra_index_exec(redis_inst, NULL, 0 TSRMLS_CC); /* run EXEC */ } zval_dtor(&z_ret); zval_ptr_dtor(&z_argarray); } /* Free any keys that we needed to allocate memory for, because they weren't strings */ for(i=0; icount * sizeof(int)); memset(argc_each, 0, ra->count * sizeof(int)); /* associate each key to a redis node */ for (i = 0, zend_hash_internal_pointer_reset_ex(h_keys, &pointer); zend_hash_get_current_data_ex(h_keys, (void**) &data, &pointer) == SUCCESS; zend_hash_move_forward_ex(h_keys, &pointer), ++i) { if (Z_TYPE_PP(data) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "DEL: all keys must be string."); efree(pos); RETURN_FALSE; } redis_instances[i] = ra_find_node(ra, Z_STRVAL_PP(data), Z_STRLEN_PP(data), &pos[i] TSRMLS_CC); argc_each[pos[i]]++; /* count number of keys per node */ argv[i] = *data; } /* calls */ for(n = 0; n < ra->count; ++n) { /* for each node */ int found = 0; redis_inst = ra->redis[n]; /* copy args */ MAKE_STD_ZVAL(z_argarray); array_init(z_argarray); for(i = 0; i < argc; ++i) { if(pos[i] != n) continue; MAKE_STD_ZVAL(z_tmp); *z_tmp = *argv[i]; zval_copy_ctor(z_tmp); INIT_PZVAL(z_tmp); add_next_index_zval(z_argarray, z_tmp); found++; } if(!found) { // don't run empty DELs zval_dtor(z_argarray); efree(z_argarray); continue; } if(ra->index) { /* add MULTI */ ra_index_multi(redis_inst, MULTI TSRMLS_CC); } /* call */ MAKE_STD_ZVAL(z_ret); call_user_function(&redis_ce->function_table, &redis_inst, &z_fun, z_ret, 1, &z_argarray TSRMLS_CC); if(ra->index) { ra_index_del(z_argarray, redis_inst TSRMLS_CC); /* use SREM to remove keys from node index */ ra_index_exec(redis_inst, z_tmp, 0 TSRMLS_CC); /* run EXEC */ total += Z_LVAL_P(z_tmp); /* increment total from multi/exec block */ } else { total += Z_LVAL_P(z_ret); /* increment total from single command */ } zval_dtor(z_ret); efree(z_ret); zval_dtor(z_argarray); efree(z_argarray); } /* cleanup */ efree(argv); efree(pos); efree(redis_instances); efree(argc_each); if(free_zkeys) { zval_dtor(z_keys); efree(z_keys); } efree(z_args); RETURN_LONG(total); } PHP_METHOD(RedisArray, multi) { zval *object; RedisArray *ra; zval *z_redis; char *host; int host_len; long multi_value = MULTI; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_array_ce, &host, &host_len, &multi_value) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0) { RETURN_FALSE; } /* find node */ z_redis = ra_find_node_by_name(ra, host, host_len TSRMLS_CC); if(!z_redis) { RETURN_FALSE; } if(multi_value != MULTI && multi_value != PIPELINE) { RETURN_FALSE; } /* save multi object */ ra->z_multi_exec = z_redis; /* switch redis instance to multi/exec mode. */ ra_index_multi(z_redis, multi_value TSRMLS_CC); /* return this. */ RETURN_ZVAL(object, 1, 0); } PHP_METHOD(RedisArray, exec) { zval *object; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0 || !ra->z_multi_exec) { RETURN_FALSE; } /* switch redis instance out of multi/exec mode. */ ra_index_exec(ra->z_multi_exec, return_value, 1 TSRMLS_CC); /* remove multi object */ ra->z_multi_exec = NULL; } PHP_METHOD(RedisArray, discard) { zval *object; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0 || !ra->z_multi_exec) { RETURN_FALSE; } /* switch redis instance out of multi/exec mode. */ ra_index_discard(ra->z_multi_exec, return_value TSRMLS_CC); /* remove multi object */ ra->z_multi_exec = NULL; } PHP_METHOD(RedisArray, unwatch) { zval *object; RedisArray *ra; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_array_ce) == FAILURE) { RETURN_FALSE; } if (redis_array_get(object, &ra TSRMLS_CC) < 0 || !ra->z_multi_exec) { RETURN_FALSE; } /* unwatch keys, stay in multi/exec mode. */ ra_index_unwatch(ra->z_multi_exec, return_value TSRMLS_CC); } redis-2.2.4/redis_array.h0000664000175000017500000000275112211042406015143 0ustar nicolasnicolas#ifndef REDIS_ARRAY_H #define REDIS_ARRAY_H #include #include "common.h" void redis_destructor_redis_array(zend_rsrc_list_entry * rsrc TSRMLS_DC); PHP_METHOD(RedisArray, __construct); PHP_METHOD(RedisArray, __call); PHP_METHOD(RedisArray, _hosts); PHP_METHOD(RedisArray, _target); PHP_METHOD(RedisArray, _instance); PHP_METHOD(RedisArray, _function); PHP_METHOD(RedisArray, _distributor); PHP_METHOD(RedisArray, _rehash); PHP_METHOD(RedisArray, select); PHP_METHOD(RedisArray, info); PHP_METHOD(RedisArray, ping); PHP_METHOD(RedisArray, flushdb); PHP_METHOD(RedisArray, flushall); PHP_METHOD(RedisArray, mget); PHP_METHOD(RedisArray, mset); PHP_METHOD(RedisArray, del); PHP_METHOD(RedisArray, keys); PHP_METHOD(RedisArray, getOption); PHP_METHOD(RedisArray, setOption); PHP_METHOD(RedisArray, multi); PHP_METHOD(RedisArray, exec); PHP_METHOD(RedisArray, discard); PHP_METHOD(RedisArray, unwatch); typedef struct RedisArray_ { int count; char **hosts; /* array of host:port strings */ zval **redis; /* array of Redis instances */ zval *z_multi_exec; /* Redis instance to be used in multi-exec */ zend_bool index; /* use per-node index */ zend_bool auto_rehash; /* migrate keys on read operations */ zend_bool pconnect; /* should we use pconnect */ zval *z_fun; /* key extractor, callable */ zval *z_dist; /* key distributor, callable */ zval *z_pure_cmds; /* hash table */ struct RedisArray_ *prev; } RedisArray; uint32_t rcrc32(const char *s, size_t sz); #endif redis-2.2.4/redis_array_impl.c0000664000175000017500000010541012211042406016153 0ustar nicolasnicolas/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2009 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Nicolas Favre-Felix | | Maintainer: Michael Grunder | +----------------------------------------------------------------------+ */ #include "redis_array_impl.h" #include "php_redis.h" #include "library.h" #include "php_variables.h" #include "SAPI.h" #include "ext/standard/url.h" #define PHPREDIS_INDEX_NAME "__phpredis_array_index__" extern int le_redis_sock; extern zend_class_entry *redis_ce; RedisArray* ra_load_hosts(RedisArray *ra, HashTable *hosts, long retry_interval, zend_bool b_lazy_connect TSRMLS_DC) { int i, host_len, id; int count = zend_hash_num_elements(hosts); char *host, *p; short port; zval **zpData, z_cons, z_ret; RedisSock *redis_sock = NULL; /* function calls on the Redis object */ ZVAL_STRING(&z_cons, "__construct", 0); /* init connections */ for(i = 0; i < count; ++i) { if(FAILURE == zend_hash_quick_find(hosts, NULL, 0, i, (void**)&zpData)) { efree(ra); return NULL; } ra->hosts[i] = estrdup(Z_STRVAL_PP(zpData)); /* default values */ host = Z_STRVAL_PP(zpData); host_len = Z_STRLEN_PP(zpData); port = 6379; if((p = strchr(host, ':'))) { /* found port */ host_len = p - host; port = (short)atoi(p+1); } else if(strchr(host,'/') != NULL) { /* unix socket */ port = -1; } /* create Redis object */ MAKE_STD_ZVAL(ra->redis[i]); object_init_ex(ra->redis[i], redis_ce); INIT_PZVAL(ra->redis[i]); call_user_function(&redis_ce->function_table, &ra->redis[i], &z_cons, &z_ret, 0, NULL TSRMLS_CC); /* create socket */ redis_sock = redis_sock_create(host, host_len, port, 0, ra->pconnect, NULL, retry_interval, b_lazy_connect); if (!b_lazy_connect) { /* connect */ redis_sock_server_open(redis_sock, 1 TSRMLS_CC); } /* attach */ #if PHP_VERSION_ID >= 50400 id = zend_list_insert(redis_sock, le_redis_sock TSRMLS_CC); #else id = zend_list_insert(redis_sock, le_redis_sock); #endif add_property_resource(ra->redis[i], "socket", id); } return ra; } /* List pure functions */ void ra_init_function_table(RedisArray *ra) { MAKE_STD_ZVAL(ra->z_pure_cmds); array_init(ra->z_pure_cmds); add_assoc_bool(ra->z_pure_cmds, "HGET", 1); add_assoc_bool(ra->z_pure_cmds, "HGETALL", 1); add_assoc_bool(ra->z_pure_cmds, "HKEYS", 1); add_assoc_bool(ra->z_pure_cmds, "HLEN", 1); add_assoc_bool(ra->z_pure_cmds, "SRANDMEMBER", 1); add_assoc_bool(ra->z_pure_cmds, "HMGET", 1); add_assoc_bool(ra->z_pure_cmds, "STRLEN", 1); add_assoc_bool(ra->z_pure_cmds, "SUNION", 1); add_assoc_bool(ra->z_pure_cmds, "HVALS", 1); add_assoc_bool(ra->z_pure_cmds, "TYPE", 1); add_assoc_bool(ra->z_pure_cmds, "EXISTS", 1); add_assoc_bool(ra->z_pure_cmds, "LINDEX", 1); add_assoc_bool(ra->z_pure_cmds, "SCARD", 1); add_assoc_bool(ra->z_pure_cmds, "LLEN", 1); add_assoc_bool(ra->z_pure_cmds, "SDIFF", 1); add_assoc_bool(ra->z_pure_cmds, "ZCARD", 1); add_assoc_bool(ra->z_pure_cmds, "ZCOUNT", 1); add_assoc_bool(ra->z_pure_cmds, "LRANGE", 1); add_assoc_bool(ra->z_pure_cmds, "ZRANGE", 1); add_assoc_bool(ra->z_pure_cmds, "ZRANK", 1); add_assoc_bool(ra->z_pure_cmds, "GET", 1); add_assoc_bool(ra->z_pure_cmds, "GETBIT", 1); add_assoc_bool(ra->z_pure_cmds, "SINTER", 1); add_assoc_bool(ra->z_pure_cmds, "GETRANGE", 1); add_assoc_bool(ra->z_pure_cmds, "ZREVRANGE", 1); add_assoc_bool(ra->z_pure_cmds, "SISMEMBER", 1); add_assoc_bool(ra->z_pure_cmds, "ZREVRANGEBYSCORE", 1); add_assoc_bool(ra->z_pure_cmds, "ZREVRANK", 1); add_assoc_bool(ra->z_pure_cmds, "HEXISTS", 1); add_assoc_bool(ra->z_pure_cmds, "ZSCORE", 1); add_assoc_bool(ra->z_pure_cmds, "HGET", 1); add_assoc_bool(ra->z_pure_cmds, "OBJECT", 1); add_assoc_bool(ra->z_pure_cmds, "SMEMBERS", 1); } static int ra_find_name(const char *name) { const char *ini_names, *p, *next; /* php_printf("Loading redis array with name=[%s]\n", name); */ ini_names = INI_STR("redis.arrays.names"); for(p = ini_names; p;) { next = strchr(p, ','); if(next) { if(strncmp(p, name, next - p) == 0) { return 1; } } else { if(strcmp(p, name) == 0) { return 1; } break; } p = next + 1; } return 0; } /* laod array from INI settings */ RedisArray *ra_load_array(const char *name TSRMLS_DC) { zval *z_params_hosts, **z_hosts; zval *z_params_prev, **z_prev; zval *z_params_funs, **z_data_pp, *z_fun = NULL, *z_dist = NULL; zval *z_params_index; zval *z_params_autorehash; zval *z_params_retry_interval; zval *z_params_pconnect; zval *z_params_lazy_connect; RedisArray *ra = NULL; zend_bool b_index = 0, b_autorehash = 0, b_pconnect = 0; long l_retry_interval = 0; zend_bool b_lazy_connect = 0; HashTable *hHosts = NULL, *hPrev = NULL; /* find entry */ if(!ra_find_name(name)) return ra; /* find hosts */ MAKE_STD_ZVAL(z_params_hosts); array_init(z_params_hosts); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.hosts")), z_params_hosts TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_hosts), name, strlen(name) + 1, (void **) &z_hosts) != FAILURE) { hHosts = Z_ARRVAL_PP(z_hosts); } /* find previous hosts */ MAKE_STD_ZVAL(z_params_prev); array_init(z_params_prev); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.previous")), z_params_prev TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_prev), name, strlen(name) + 1, (void **) &z_prev) != FAILURE) { hPrev = Z_ARRVAL_PP(z_prev); } /* find function */ MAKE_STD_ZVAL(z_params_funs); array_init(z_params_funs); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.functions")), z_params_funs TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_funs), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { MAKE_STD_ZVAL(z_fun); *z_fun = **z_data_pp; zval_copy_ctor(z_fun); } /* find distributor */ MAKE_STD_ZVAL(z_params_funs); array_init(z_params_funs); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.distributor")), z_params_funs TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_funs), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { MAKE_STD_ZVAL(z_dist); *z_dist = **z_data_pp; zval_copy_ctor(z_dist); } /* find index option */ MAKE_STD_ZVAL(z_params_index); array_init(z_params_index); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.index")), z_params_index TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_index), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { if(Z_TYPE_PP(z_data_pp) == IS_STRING && strncmp(Z_STRVAL_PP(z_data_pp), "1", 1) == 0) { b_index = 1; } } /* find autorehash option */ MAKE_STD_ZVAL(z_params_autorehash); array_init(z_params_autorehash); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.autorehash")), z_params_autorehash TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_autorehash), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { if(Z_TYPE_PP(z_data_pp) == IS_STRING && strncmp(Z_STRVAL_PP(z_data_pp), "1", 1) == 0) { b_autorehash = 1; } } /* find retry interval option */ MAKE_STD_ZVAL(z_params_retry_interval); array_init(z_params_retry_interval); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.retryinterval")), z_params_retry_interval TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_retry_interval), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { if (Z_TYPE_PP(z_data_pp) == IS_LONG || Z_TYPE_PP(z_data_pp) == IS_STRING) { if (Z_TYPE_PP(z_data_pp) == IS_LONG) { l_retry_interval = Z_LVAL_PP(z_data_pp); } else { l_retry_interval = atol(Z_STRVAL_PP(z_data_pp)); } } } /* find pconnect option */ MAKE_STD_ZVAL(z_params_pconnect); array_init(z_params_pconnect); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.pconnect")), z_params_pconnect TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_pconnect), name, strlen(name) + 1, (void**) &z_data_pp) != FAILURE) { if(Z_TYPE_PP(z_data_pp) == IS_STRING && strncmp(Z_STRVAL_PP(z_data_pp), "1", 1) == 0) { b_pconnect = 1; } } /* find retry interval option */ MAKE_STD_ZVAL(z_params_lazy_connect); array_init(z_params_lazy_connect); sapi_module.treat_data(PARSE_STRING, estrdup(INI_STR("redis.arrays.lazyconnect")), z_params_lazy_connect TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(z_params_lazy_connect), name, strlen(name) + 1, (void **) &z_data_pp) != FAILURE) { if(Z_TYPE_PP(z_data_pp) == IS_STRING && strncmp(Z_STRVAL_PP(z_data_pp), "1", 1) == 0) { b_lazy_connect = 1; } } /* create RedisArray object */ ra = ra_make_array(hHosts, z_fun, z_dist, hPrev, b_index, b_pconnect, l_retry_interval, b_lazy_connect TSRMLS_CC); ra->auto_rehash = b_autorehash; /* cleanup */ zval_dtor(z_params_hosts); efree(z_params_hosts); zval_dtor(z_params_prev); efree(z_params_prev); zval_dtor(z_params_funs); efree(z_params_funs); zval_dtor(z_params_index); efree(z_params_index); zval_dtor(z_params_autorehash); efree(z_params_autorehash); zval_dtor(z_params_retry_interval); efree(z_params_retry_interval); zval_dtor(z_params_pconnect); efree(z_params_pconnect); zval_dtor(z_params_lazy_connect); efree(z_params_lazy_connect); return ra; } RedisArray * ra_make_array(HashTable *hosts, zval *z_fun, zval *z_dist, HashTable *hosts_prev, zend_bool b_index, zend_bool b_pconnect, long retry_interval, zend_bool b_lazy_connect TSRMLS_DC) { int count = zend_hash_num_elements(hosts); /* create object */ RedisArray *ra = emalloc(sizeof(RedisArray)); ra->hosts = emalloc(count * sizeof(char*)); ra->redis = emalloc(count * sizeof(zval*)); ra->count = count; ra->z_fun = NULL; ra->z_dist = NULL; ra->z_multi_exec = NULL; ra->index = b_index; ra->auto_rehash = 0; /* init array data structures */ ra_init_function_table(ra); if(NULL == ra_load_hosts(ra, hosts, retry_interval, b_lazy_connect TSRMLS_CC)) { return NULL; } ra->prev = hosts_prev ? ra_make_array(hosts_prev, z_fun, z_dist, NULL, b_index, b_pconnect, retry_interval, b_lazy_connect TSRMLS_CC) : NULL; /* copy function if provided */ if(z_fun) { MAKE_STD_ZVAL(ra->z_fun); *ra->z_fun = *z_fun; zval_copy_ctor(ra->z_fun); } /* copy distributor if provided */ if(z_dist) { MAKE_STD_ZVAL(ra->z_dist); *ra->z_dist = *z_dist; zval_copy_ctor(ra->z_dist); } return ra; } /* call userland key extraction function */ char * ra_call_extractor(RedisArray *ra, const char *key, int key_len, int *out_len TSRMLS_DC) { char *out; zval z_ret; zval *z_argv0; /* check that we can call the extractor function */ if(!zend_is_callable_ex(ra->z_fun, NULL, 0, NULL, NULL, NULL, NULL TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Could not call extractor function"); return NULL; } //convert_to_string(ra->z_fun); /* call extraction function */ MAKE_STD_ZVAL(z_argv0); ZVAL_STRINGL(z_argv0, key, key_len, 0); call_user_function(EG(function_table), NULL, ra->z_fun, &z_ret, 1, &z_argv0 TSRMLS_CC); efree(z_argv0); if(Z_TYPE(z_ret) != IS_STRING) { zval_dtor(&z_ret); return NULL; } *out_len = Z_STRLEN(z_ret); out = emalloc(*out_len + 1); out[*out_len] = 0; memcpy(out, Z_STRVAL(z_ret), *out_len); zval_dtor(&z_ret); return out; } static char * ra_extract_key(RedisArray *ra, const char *key, int key_len, int *out_len TSRMLS_DC) { char *start, *end, *out; *out_len = key_len; if(ra->z_fun) return ra_call_extractor(ra, key, key_len, out_len TSRMLS_CC); /* look for '{' */ start = strchr(key, '{'); if(!start) return estrndup(key, key_len); /* look for '}' */ end = strchr(start + 1, '}'); if(!end) return estrndup(key, key_len); /* found substring */ *out_len = end - start - 1; out = emalloc(*out_len + 1); out[*out_len] = 0; memcpy(out, start+1, *out_len); return out; } /* call userland key distributor function */ zend_bool ra_call_distributor(RedisArray *ra, const char *key, int key_len, int *pos TSRMLS_DC) { zval z_ret; zval *z_argv0; /* check that we can call the extractor function */ if(!zend_is_callable_ex(ra->z_dist, NULL, 0, NULL, NULL, NULL, NULL TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Could not call distributor function"); return 0; } //convert_to_string(ra->z_fun); /* call extraction function */ MAKE_STD_ZVAL(z_argv0); ZVAL_STRINGL(z_argv0, key, key_len, 0); call_user_function(EG(function_table), NULL, ra->z_dist, &z_ret, 1, &z_argv0 TSRMLS_CC); efree(z_argv0); if(Z_TYPE(z_ret) != IS_LONG) { zval_dtor(&z_ret); return 0; } *pos = Z_LVAL(z_ret); zval_dtor(&z_ret); return 1; } zval * ra_find_node(RedisArray *ra, const char *key, int key_len, int *out_pos TSRMLS_DC) { uint32_t hash; char *out; int pos, out_len; /* extract relevant part of the key */ out = ra_extract_key(ra, key, key_len, &out_len TSRMLS_CC); if(!out) return NULL; if(ra->z_dist) { if (!ra_call_distributor(ra, key, key_len, &pos TSRMLS_CC)) { return NULL; } } else { /* hash */ hash = rcrc32(out, out_len); efree(out); /* get position on ring */ uint64_t h64 = hash; h64 *= ra->count; h64 /= 0xffffffff; pos = (int)h64; } if(out_pos) *out_pos = pos; return ra->redis[pos]; } zval * ra_find_node_by_name(RedisArray *ra, const char *host, int host_len TSRMLS_DC) { int i; for(i = 0; i < ra->count; ++i) { if(strncmp(ra->hosts[i], host, host_len) == 0) { return ra->redis[i]; } } return NULL; } char * ra_find_key(RedisArray *ra, zval *z_args, const char *cmd, int *key_len) { zval **zp_tmp; int key_pos = 0; /* TODO: change this depending on the command */ if( zend_hash_num_elements(Z_ARRVAL_P(z_args)) == 0 || zend_hash_quick_find(Z_ARRVAL_P(z_args), NULL, 0, key_pos, (void**)&zp_tmp) == FAILURE || Z_TYPE_PP(zp_tmp) != IS_STRING) { return NULL; } *key_len = Z_STRLEN_PP(zp_tmp); return Z_STRVAL_PP(zp_tmp); } void ra_index_multi(zval *z_redis, long multi_value TSRMLS_DC) { zval z_fun_multi, z_ret; zval *z_args[1]; /* run MULTI */ ZVAL_STRING(&z_fun_multi, "MULTI", 0); MAKE_STD_ZVAL(z_args[0]); ZVAL_LONG(z_args[0], multi_value); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_multi, &z_ret, 1, z_args TSRMLS_CC); efree(z_args[0]); //zval_dtor(&z_ret); } static void ra_index_change_keys(const char *cmd, zval *z_keys, zval *z_redis TSRMLS_DC) { int i, argc; zval z_fun, z_ret, **z_args; /* alloc */ argc = 1 + zend_hash_num_elements(Z_ARRVAL_P(z_keys)); z_args = emalloc(argc * sizeof(zval*)); /* prepare first parameters */ ZVAL_STRING(&z_fun, cmd, 0); MAKE_STD_ZVAL(z_args[0]); ZVAL_STRING(z_args[0], PHPREDIS_INDEX_NAME, 0); /* prepare keys */ for(i = 0; i < argc - 1; ++i) { zval **zpp; zend_hash_quick_find(Z_ARRVAL_P(z_keys), NULL, 0, i, (void**)&zpp); z_args[i+1] = *zpp; } /* run cmd */ call_user_function(&redis_ce->function_table, &z_redis, &z_fun, &z_ret, argc, z_args TSRMLS_CC); /* don't dtor z_ret, since we're returning z_redis */ efree(z_args[0]); /* free index name zval */ efree(z_args); /* free container */ } void ra_index_del(zval *z_keys, zval *z_redis TSRMLS_DC) { ra_index_change_keys("SREM", z_keys, z_redis TSRMLS_CC); } void ra_index_keys(zval *z_pairs, zval *z_redis TSRMLS_DC) { /* Initialize key array */ zval *z_keys, **z_entry_pp; MAKE_STD_ZVAL(z_keys); #if PHP_VERSION_ID > 50300 array_init_size(z_keys, zend_hash_num_elements(Z_ARRVAL_P(z_pairs))); #else array_init(z_keys); #endif HashPosition pos; /* Go through input array and add values to the key array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(z_pairs), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(z_pairs), (void **)&z_entry_pp, &pos) == SUCCESS) { char *key; unsigned int key_len; unsigned long num_key; zval *z_new; MAKE_STD_ZVAL(z_new); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(z_pairs), &key, &key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(z_new, key, (int)key_len - 1, 0); zend_hash_next_index_insert(Z_ARRVAL_P(z_keys), &z_new, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(z_new) = IS_LONG; Z_LVAL_P(z_new) = (long)num_key; zend_hash_next_index_insert(Z_ARRVAL_P(z_keys), &z_new, sizeof(zval *), NULL); break; } zend_hash_move_forward_ex(Z_ARRVAL_P(z_pairs), &pos); } /* add keys to index */ ra_index_change_keys("SADD", z_keys, z_redis TSRMLS_CC); /* cleanup */ zval_dtor(z_keys); efree(z_keys); } void ra_index_key(const char *key, int key_len, zval *z_redis TSRMLS_DC) { zval z_fun_sadd, z_ret, *z_args[2]; MAKE_STD_ZVAL(z_args[0]); MAKE_STD_ZVAL(z_args[1]); /* prepare args */ ZVAL_STRINGL(&z_fun_sadd, "SADD", 4, 0); ZVAL_STRING(z_args[0], PHPREDIS_INDEX_NAME, 0); ZVAL_STRINGL(z_args[1], key, key_len, 1); /* run SADD */ call_user_function(&redis_ce->function_table, &z_redis, &z_fun_sadd, &z_ret, 2, z_args TSRMLS_CC); /* don't dtor z_ret, since we're returning z_redis */ efree(z_args[0]); efree(z_args[1]); } void ra_index_exec(zval *z_redis, zval *return_value, int keep_all TSRMLS_DC) { zval z_fun_exec, z_ret, **zp_tmp; /* run EXEC */ ZVAL_STRING(&z_fun_exec, "EXEC", 0); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_exec, &z_ret, 0, NULL TSRMLS_CC); /* extract first element of exec array and put into return_value. */ if(Z_TYPE(z_ret) == IS_ARRAY) { if(return_value) { if(keep_all) { *return_value = z_ret; zval_copy_ctor(return_value); } else if(zend_hash_quick_find(Z_ARRVAL(z_ret), NULL, 0, 0, (void**)&zp_tmp) != FAILURE) { *return_value = **zp_tmp; zval_copy_ctor(return_value); } } zval_dtor(&z_ret); } //zval *zptr = &z_ret; //php_var_dump(&zptr, 0 TSRMLS_CC); } void ra_index_discard(zval *z_redis, zval *return_value TSRMLS_DC) { zval z_fun_discard, z_ret; /* run DISCARD */ ZVAL_STRING(&z_fun_discard, "DISCARD", 0); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_discard, &z_ret, 0, NULL TSRMLS_CC); zval_dtor(&z_ret); } void ra_index_unwatch(zval *z_redis, zval *return_value TSRMLS_DC) { zval z_fun_unwatch, z_ret; /* run UNWATCH */ ZVAL_STRING(&z_fun_unwatch, "UNWATCH", 0); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_unwatch, &z_ret, 0, NULL TSRMLS_CC); zval_dtor(&z_ret); } zend_bool ra_is_write_cmd(RedisArray *ra, const char *cmd, int cmd_len) { zend_bool ret; int i; char *cmd_up = emalloc(1 + cmd_len); /* convert to uppercase */ for(i = 0; i < cmd_len; ++i) cmd_up[i] = toupper(cmd[i]); cmd_up[cmd_len] = 0; ret = zend_hash_exists(Z_ARRVAL_P(ra->z_pure_cmds), cmd_up, cmd_len+1); efree(cmd_up); return !ret; } /* list keys from array index */ static long ra_rehash_scan(zval *z_redis, char ***keys, int **key_lens, const char *cmd, const char *arg TSRMLS_DC) { long count, i; zval z_fun_smembers, z_ret, *z_arg, **z_data_pp; HashTable *h_keys; HashPosition pointer; char *key; int key_len; /* arg */ MAKE_STD_ZVAL(z_arg); ZVAL_STRING(z_arg, arg, 0); /* run SMEMBERS */ ZVAL_STRING(&z_fun_smembers, cmd, 0); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_smembers, &z_ret, 1, &z_arg TSRMLS_CC); efree(z_arg); if(Z_TYPE(z_ret) != IS_ARRAY) { /* failure */ return -1; /* TODO: log error. */ } h_keys = Z_ARRVAL(z_ret); /* allocate key array */ count = zend_hash_num_elements(h_keys); *keys = emalloc(count * sizeof(char*)); *key_lens = emalloc(count * sizeof(int)); for (i = 0, zend_hash_internal_pointer_reset_ex(h_keys, &pointer); zend_hash_get_current_data_ex(h_keys, (void**) &z_data_pp, &pointer) == SUCCESS; zend_hash_move_forward_ex(h_keys, &pointer), ++i) { key = Z_STRVAL_PP(z_data_pp); key_len = Z_STRLEN_PP(z_data_pp); /* copy key and length */ (*keys)[i] = emalloc(1 + key_len); memcpy((*keys)[i], key, key_len); (*key_lens)[i] = key_len; (*keys)[i][key_len] = 0; /* null-terminate string */ } /* cleanup */ zval_dtor(&z_ret); return count; } static long ra_rehash_scan_index(zval *z_redis, char ***keys, int **key_lens TSRMLS_DC) { return ra_rehash_scan(z_redis, keys, key_lens, "SMEMBERS", PHPREDIS_INDEX_NAME TSRMLS_CC); } /* list keys using KEYS command */ static long ra_rehash_scan_keys(zval *z_redis, char ***keys, int **key_lens TSRMLS_DC) { return ra_rehash_scan(z_redis, keys, key_lens, "KEYS", "*" TSRMLS_CC); } /* run TYPE to find the type */ static zend_bool ra_get_key_type(zval *z_redis, const char *key, int key_len, zval *z_from, long *res TSRMLS_DC) { int i; zval z_fun_type, z_ret, *z_arg; zval **z_data; long success = 1; MAKE_STD_ZVAL(z_arg); /* Pipelined */ ra_index_multi(z_from, PIPELINE TSRMLS_CC); /* prepare args */ ZVAL_STRINGL(&z_fun_type, "TYPE", 4, 0); ZVAL_STRINGL(z_arg, key, key_len, 0); /* run TYPE */ call_user_function(&redis_ce->function_table, &z_redis, &z_fun_type, &z_ret, 1, &z_arg TSRMLS_CC); ZVAL_STRINGL(&z_fun_type, "TTL", 3, 0); ZVAL_STRINGL(z_arg, key, key_len, 0); /* run TYPE */ call_user_function(&redis_ce->function_table, &z_redis, &z_fun_type, &z_ret, 1, &z_arg TSRMLS_CC); /* cleanup */ efree(z_arg); /* Get the result from the pipeline. */ ra_index_exec(z_from, &z_ret, 1 TSRMLS_CC); if(Z_TYPE(z_ret) == IS_ARRAY) { HashTable *retHash = Z_ARRVAL(z_ret); for(i = 0, zend_hash_internal_pointer_reset(retHash); zend_hash_has_more_elements(retHash) == SUCCESS; zend_hash_move_forward(retHash)) { if(zend_hash_get_current_data(retHash, (void**)&z_data) == FAILURE) { success = 0; break; } if(Z_TYPE_PP(z_data) != IS_LONG) { success = 0; break; } /* Get the result - Might change in the future to handle doubles as well */ res[i] = Z_LVAL_PP(z_data); i++; } } zval_dtor(&z_ret); return success; } /* delete key from source server index during rehashing */ static void ra_remove_from_index(zval *z_redis, const char *key, int key_len TSRMLS_DC) { zval z_fun_srem, z_ret, *z_args[2]; /* run SREM on source index */ ZVAL_STRINGL(&z_fun_srem, "SREM", 4, 0); MAKE_STD_ZVAL(z_args[0]); ZVAL_STRING(z_args[0], PHPREDIS_INDEX_NAME, 0); MAKE_STD_ZVAL(z_args[1]); ZVAL_STRINGL(z_args[1], key, key_len, 0); call_user_function(&redis_ce->function_table, &z_redis, &z_fun_srem, &z_ret, 2, z_args TSRMLS_CC); /* cleanup */ efree(z_args[0]); efree(z_args[1]); } /* delete key from source server during rehashing */ static zend_bool ra_del_key(const char *key, int key_len, zval *z_from TSRMLS_DC) { zval z_fun_del, z_ret, *z_args; /* in a transaction */ ra_index_multi(z_from, MULTI TSRMLS_CC); /* run DEL on source */ MAKE_STD_ZVAL(z_args); ZVAL_STRINGL(&z_fun_del, "DEL", 3, 0); ZVAL_STRINGL(z_args, key, key_len, 0); call_user_function(&redis_ce->function_table, &z_from, &z_fun_del, &z_ret, 1, &z_args TSRMLS_CC); efree(z_args); /* remove key from index */ ra_remove_from_index(z_from, key, key_len TSRMLS_CC); /* close transaction */ ra_index_exec(z_from, NULL, 0 TSRMLS_CC); return 1; } static zend_bool ra_expire_key(const char *key, int key_len, zval *z_to, long ttl TSRMLS_DC) { zval z_fun_expire, z_ret, *z_args[2]; if (ttl > 0) { /* run EXPIRE on target */ MAKE_STD_ZVAL(z_args[0]); MAKE_STD_ZVAL(z_args[1]); ZVAL_STRINGL(&z_fun_expire, "EXPIRE", 6, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); ZVAL_LONG(z_args[1], ttl); call_user_function(&redis_ce->function_table, &z_to, &z_fun_expire, &z_ret, 2, z_args TSRMLS_CC); /* cleanup */ efree(z_args[0]); efree(z_args[1]); } return 1; } static zend_bool ra_move_zset(const char *key, int key_len, zval *z_from, zval *z_to, long ttl TSRMLS_DC) { zval z_fun_zrange, z_fun_zadd, z_ret, *z_args[4], **z_zadd_args, **z_score_pp; int count; HashTable *h_zset_vals; char *val; unsigned int val_len; int i; unsigned long idx; /* run ZRANGE key 0 -1 WITHSCORES on source */ ZVAL_STRINGL(&z_fun_zrange, "ZRANGE", 6, 0); for(i = 0; i < 4; ++i) { MAKE_STD_ZVAL(z_args[i]); } ZVAL_STRINGL(z_args[0], key, key_len, 0); ZVAL_STRINGL(z_args[1], "0", 1, 0); ZVAL_STRINGL(z_args[2], "-1", 2, 0); ZVAL_BOOL(z_args[3], 1); call_user_function(&redis_ce->function_table, &z_from, &z_fun_zrange, &z_ret, 4, z_args TSRMLS_CC); /* cleanup zrange args */ for(i = 0; i < 4; ++i) { efree(z_args[i]); /* FIXME */ } if(Z_TYPE(z_ret) != IS_ARRAY) { /* key not found or replaced */ /* TODO: report? */ return 0; } /* we now have an array of value → score pairs in z_ret. */ h_zset_vals = Z_ARRVAL(z_ret); /* allocate argument array for ZADD */ count = zend_hash_num_elements(h_zset_vals); z_zadd_args = emalloc((1 + 2*count) * sizeof(zval*)); for(i = 1, zend_hash_internal_pointer_reset(h_zset_vals); zend_hash_has_more_elements(h_zset_vals) == SUCCESS; zend_hash_move_forward(h_zset_vals)) { if(zend_hash_get_current_data(h_zset_vals, (void**)&z_score_pp) == FAILURE) { continue; } /* add score */ convert_to_double(*z_score_pp); MAKE_STD_ZVAL(z_zadd_args[i]); ZVAL_DOUBLE(z_zadd_args[i], Z_DVAL_PP(z_score_pp)); /* add value */ MAKE_STD_ZVAL(z_zadd_args[i+1]); switch (zend_hash_get_current_key_ex(h_zset_vals, &val, &val_len, &idx, 0, NULL)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(z_zadd_args[i+1], val, (int)val_len-1, 0); /* we have to remove 1 because it is an array key. */ break; case HASH_KEY_IS_LONG: ZVAL_LONG(z_zadd_args[i+1], (long)idx); break; default: return -1; // Todo: log error break; } i += 2; } /* run ZADD on target */ ZVAL_STRINGL(&z_fun_zadd, "ZADD", 4, 0); MAKE_STD_ZVAL(z_zadd_args[0]); ZVAL_STRINGL(z_zadd_args[0], key, key_len, 0); call_user_function(&redis_ce->function_table, &z_to, &z_fun_zadd, &z_ret, 1 + 2 * count, z_zadd_args TSRMLS_CC); /* Expire if needed */ ra_expire_key(key, key_len, z_to, ttl TSRMLS_CC); /* cleanup */ for(i = 0; i < 1 + 2 * count; ++i) { efree(z_zadd_args[i]); } return 1; } static zend_bool ra_move_string(const char *key, int key_len, zval *z_from, zval *z_to, long ttl TSRMLS_DC) { zval z_fun_get, z_fun_set, z_ret, *z_args[3]; /* run GET on source */ MAKE_STD_ZVAL(z_args[0]); ZVAL_STRINGL(&z_fun_get, "GET", 3, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); call_user_function(&redis_ce->function_table, &z_from, &z_fun_get, &z_ret, 1, z_args TSRMLS_CC); if(Z_TYPE(z_ret) != IS_STRING) { /* key not found or replaced */ /* TODO: report? */ efree(z_args[0]); return 0; } /* run SET on target */ MAKE_STD_ZVAL(z_args[1]); if (ttl > 0) { MAKE_STD_ZVAL(z_args[2]); ZVAL_STRINGL(&z_fun_set, "SETEX", 5, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); ZVAL_LONG(z_args[1], ttl); ZVAL_STRINGL(z_args[2], Z_STRVAL(z_ret), Z_STRLEN(z_ret), 1); /* copy z_ret to arg 1 */ call_user_function(&redis_ce->function_table, &z_to, &z_fun_set, &z_ret, 3, z_args TSRMLS_CC); /* cleanup */ efree(z_args[1]); zval_dtor(z_args[2]); efree(z_args[2]); } else { ZVAL_STRINGL(&z_fun_set, "SET", 3, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); ZVAL_STRINGL(z_args[1], Z_STRVAL(z_ret), Z_STRLEN(z_ret), 1); /* copy z_ret to arg 1 */ call_user_function(&redis_ce->function_table, &z_to, &z_fun_set, &z_ret, 2, z_args TSRMLS_CC); /* cleanup */ zval_dtor(z_args[1]); efree(z_args[1]); } /* cleanup */ efree(z_args[0]); return 1; } static zend_bool ra_move_hash(const char *key, int key_len, zval *z_from, zval *z_to, long ttl TSRMLS_DC) { zval z_fun_hgetall, z_fun_hmset, z_ret, *z_args[2]; /* run HGETALL on source */ MAKE_STD_ZVAL(z_args[0]); ZVAL_STRINGL(&z_fun_hgetall, "HGETALL", 7, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); call_user_function(&redis_ce->function_table, &z_from, &z_fun_hgetall, &z_ret, 1, z_args TSRMLS_CC); if(Z_TYPE(z_ret) != IS_ARRAY) { /* key not found or replaced */ /* TODO: report? */ efree(z_args[0]); return 0; } /* run HMSET on target */ ZVAL_STRINGL(&z_fun_hmset, "HMSET", 5, 0); ZVAL_STRINGL(z_args[0], key, key_len, 0); z_args[1] = &z_ret; /* copy z_ret to arg 1 */ call_user_function(&redis_ce->function_table, &z_to, &z_fun_hmset, &z_ret, 2, z_args TSRMLS_CC); /* Expire if needed */ ra_expire_key(key, key_len, z_to, ttl TSRMLS_CC); /* cleanup */ efree(z_args[0]); return 1; } static zend_bool ra_move_collection(const char *key, int key_len, zval *z_from, zval *z_to, int list_count, const char **cmd_list, int add_count, const char **cmd_add, long ttl TSRMLS_DC) { zval z_fun_retrieve, z_fun_sadd, z_ret, **z_retrieve_args, **z_sadd_args, **z_data_pp; int count, i; HashTable *h_set_vals; /* run retrieval command on source */ z_retrieve_args = emalloc((1+list_count) * sizeof(zval*)); ZVAL_STRING(&z_fun_retrieve, cmd_list[0], 0); /* set the command */ /* set the key */ MAKE_STD_ZVAL(z_retrieve_args[0]); ZVAL_STRINGL(z_retrieve_args[0], key, key_len, 0); /* possibly add some other args if they were provided. */ for(i = 1; i < list_count; ++i) { MAKE_STD_ZVAL(z_retrieve_args[i]); ZVAL_STRING(z_retrieve_args[i], cmd_list[i], 0); } call_user_function(&redis_ce->function_table, &z_from, &z_fun_retrieve, &z_ret, list_count, z_retrieve_args TSRMLS_CC); /* cleanup */ for(i = 0; i < list_count; ++i) { efree(z_retrieve_args[i]); } efree(z_retrieve_args); if(Z_TYPE(z_ret) != IS_ARRAY) { /* key not found or replaced */ /* TODO: report? */ return 0; } /* run SADD/RPUSH on target */ h_set_vals = Z_ARRVAL(z_ret); count = zend_hash_num_elements(h_set_vals); z_sadd_args = emalloc((1 + count) * sizeof(zval*)); ZVAL_STRING(&z_fun_sadd, cmd_add[0], 0); MAKE_STD_ZVAL(z_sadd_args[0]); /* add key */ ZVAL_STRINGL(z_sadd_args[0], key, key_len, 0); for(i = 0, zend_hash_internal_pointer_reset(h_set_vals); zend_hash_has_more_elements(h_set_vals) == SUCCESS; zend_hash_move_forward(h_set_vals), i++) { if(zend_hash_get_current_data(h_set_vals, (void**)&z_data_pp) == FAILURE) { continue; } /* add set elements */ MAKE_STD_ZVAL(z_sadd_args[i+1]); *(z_sadd_args[i+1]) = **z_data_pp; zval_copy_ctor(z_sadd_args[i+1]); } call_user_function(&redis_ce->function_table, &z_to, &z_fun_sadd, &z_ret, count+1, z_sadd_args TSRMLS_CC); /* Expire if needed */ ra_expire_key(key, key_len, z_to, ttl TSRMLS_CC); /* cleanup */ efree(z_sadd_args[0]); /* no dtor at [0] */ for(i = 0; i < count; ++i) { zval_dtor(z_sadd_args[i + 1]); efree(z_sadd_args[i + 1]); } efree(z_sadd_args); return 1; } static zend_bool ra_move_set(const char *key, int key_len, zval *z_from, zval *z_to, long ttl TSRMLS_DC) { const char *cmd_list[] = {"SMEMBERS"}; const char *cmd_add[] = {"SADD"}; return ra_move_collection(key, key_len, z_from, z_to, 1, cmd_list, 1, cmd_add, ttl TSRMLS_CC); } static zend_bool ra_move_list(const char *key, int key_len, zval *z_from, zval *z_to, long ttl TSRMLS_DC) { const char *cmd_list[] = {"LRANGE", "0", "-1"}; const char *cmd_add[] = {"RPUSH"}; return ra_move_collection(key, key_len, z_from, z_to, 3, cmd_list, 1, cmd_add, ttl TSRMLS_CC); } void ra_move_key(const char *key, int key_len, zval *z_from, zval *z_to TSRMLS_DC) { long res[2], type, ttl; zend_bool success = 0; if (ra_get_key_type(z_from, key, key_len, z_from, res TSRMLS_CC)) { type = res[0]; ttl = res[1]; /* open transaction on target server */ ra_index_multi(z_to, MULTI TSRMLS_CC); switch(type) { case REDIS_STRING: success = ra_move_string(key, key_len, z_from, z_to, ttl TSRMLS_CC); break; case REDIS_SET: success = ra_move_set(key, key_len, z_from, z_to, ttl TSRMLS_CC); break; case REDIS_LIST: success = ra_move_list(key, key_len, z_from, z_to, ttl TSRMLS_CC); break; case REDIS_ZSET: success = ra_move_zset(key, key_len, z_from, z_to, ttl TSRMLS_CC); break; case REDIS_HASH: success = ra_move_hash(key, key_len, z_from, z_to, ttl TSRMLS_CC); break; default: /* TODO: report? */ break; } } if(success) { ra_del_key(key, key_len, z_from TSRMLS_CC); ra_index_key(key, key_len, z_to TSRMLS_CC); } /* close transaction */ ra_index_exec(z_to, NULL, 0 TSRMLS_CC); } /* callback with the current progress, with hostname and count */ static void zval_rehash_callback(zend_fcall_info *z_cb, zend_fcall_info_cache *z_cb_cache, const char *hostname, long count TSRMLS_DC) { zval *z_ret = NULL, **z_args[2]; zval *z_host, *z_count; z_cb->retval_ptr_ptr = &z_ret; z_cb->params = (struct _zval_struct ***)&z_args; z_cb->param_count = 2; z_cb->no_separation = 0; /* run cb(hostname, count) */ MAKE_STD_ZVAL(z_host); ZVAL_STRING(z_host, hostname, 0); z_args[0] = &z_host; MAKE_STD_ZVAL(z_count); ZVAL_LONG(z_count, count); z_args[1] = &z_count; zend_call_function(z_cb, z_cb_cache TSRMLS_CC); /* cleanup */ efree(z_host); efree(z_count); if(z_ret) efree(z_ret); } static void ra_rehash_server(RedisArray *ra, zval *z_redis, const char *hostname, zend_bool b_index, zend_fcall_info *z_cb, zend_fcall_info_cache *z_cb_cache TSRMLS_DC) { char **keys; int *key_lens; long count, i; int target_pos; zval *z_target; /* list all keys */ if(b_index) { count = ra_rehash_scan_index(z_redis, &keys, &key_lens TSRMLS_CC); } else { count = ra_rehash_scan_keys(z_redis, &keys, &key_lens TSRMLS_CC); } /* callback */ if(z_cb && z_cb_cache) { zval_rehash_callback(z_cb, z_cb_cache, hostname, count TSRMLS_CC); } /* for each key, redistribute */ for(i = 0; i < count; ++i) { /* check that we're not moving to the same node. */ z_target = ra_find_node(ra, keys[i], key_lens[i], &target_pos TSRMLS_CC); if(strcmp(hostname, ra->hosts[target_pos])) { /* different host */ /* php_printf("move [%s] from [%s] to [%s]\n", keys[i], hostname, ra->hosts[target_pos]); */ ra_move_key(keys[i], key_lens[i], z_redis, z_target TSRMLS_CC); } } /* cleanup */ for(i = 0; i < count; ++i) { efree(keys[i]); } efree(keys); efree(key_lens); } void ra_rehash(RedisArray *ra, zend_fcall_info *z_cb, zend_fcall_info_cache *z_cb_cache TSRMLS_DC) { int i; /* redistribute the data, server by server. */ if(!ra->prev) return; /* TODO: compare the two rings for equality */ for(i = 0; i < ra->prev->count; ++i) { ra_rehash_server(ra, ra->prev->redis[i], ra->prev->hosts[i], ra->index, z_cb, z_cb_cache TSRMLS_CC); } } redis-2.2.4/redis_array_impl.h0000664000175000017500000000277012211042406016165 0ustar nicolasnicolas#ifndef REDIS_ARRAY_IMPL_H #define REDIS_ARRAY_IMPL_H #include #include "common.h" #include "redis_array.h" RedisArray *ra_load_hosts(RedisArray *ra, HashTable *hosts, long retry_interval, zend_bool b_lazy_connect TSRMLS_DC); RedisArray *ra_load_array(const char *name TSRMLS_DC); RedisArray *ra_make_array(HashTable *hosts, zval *z_fun, zval *z_dist, HashTable *hosts_prev, zend_bool b_index, zend_bool b_pconnect, long retry_interval, zend_bool b_lazy_connect TSRMLS_DC); zval *ra_find_node_by_name(RedisArray *ra, const char *host, int host_len TSRMLS_DC); zval *ra_find_node(RedisArray *ra, const char *key, int key_len, int *out_pos TSRMLS_DC); void ra_init_function_table(RedisArray *ra); void ra_move_key(const char *key, int key_len, zval *z_from, zval *z_to TSRMLS_DC); char * ra_find_key(RedisArray *ra, zval *z_args, const char *cmd, int *key_len); void ra_index_multi(zval *z_redis, long multi_value TSRMLS_DC); void ra_index_key(const char *key, int key_len, zval *z_redis TSRMLS_DC); void ra_index_keys(zval *z_pairs, zval *z_redis TSRMLS_DC); void ra_index_del(zval *z_keys, zval *z_redis TSRMLS_DC); void ra_index_exec(zval *z_redis, zval *return_value, int keep_all TSRMLS_DC); void ra_index_discard(zval *z_redis, zval *return_value TSRMLS_DC); void ra_index_unwatch(zval *z_redis, zval *return_value TSRMLS_DC); zend_bool ra_is_write_cmd(RedisArray *ra, const char *cmd, int cmd_len); void ra_rehash(RedisArray *ra, zend_fcall_info *z_cb, zend_fcall_info_cache *z_cb_cache TSRMLS_DC); #endif redis-2.2.4/redis.c0000664000175000017500000060736512211042406013754 0ustar nicolasnicolas/* -*- Mode: C; tab-width: 4 -*- */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2009 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Original author: Alfonso Jimenez | | Maintainer: Nicolas Favre-Felix | | Maintainer: Nasreddine Bouafif | | Maintainer: Michael Grunder | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "common.h" #include "ext/standard/info.h" #include "php_ini.h" #include "php_redis.h" #include "redis_array.h" #include #ifdef PHP_SESSION #include "ext/session/php_session.h" #endif #include #include #include #include "library.h" #define R_SUB_CALLBACK_CLASS_TYPE 1 #define R_SUB_CALLBACK_FT_TYPE 2 #define R_SUB_CLOSURE_TYPE 3 int le_redis_sock; extern int le_redis_array; #ifdef PHP_SESSION extern ps_module ps_mod_redis; #endif extern zend_class_entry *redis_array_ce; zend_class_entry *redis_ce; zend_class_entry *redis_exception_ce; zend_class_entry *spl_ce_RuntimeException = NULL; extern zend_function_entry redis_array_functions[]; PHP_INI_BEGIN() /* redis arrays */ PHP_INI_ENTRY("redis.arrays.names", "", PHP_INI_ALL, NULL) PHP_INI_ENTRY("redis.arrays.hosts", "", PHP_INI_ALL, NULL) PHP_INI_ENTRY("redis.arrays.previous", "", PHP_INI_ALL, NULL) PHP_INI_ENTRY("redis.arrays.functions", "", PHP_INI_ALL, NULL) PHP_INI_ENTRY("redis.arrays.index", "", PHP_INI_ALL, NULL) PHP_INI_ENTRY("redis.arrays.autorehash", "", PHP_INI_ALL, NULL) PHP_INI_END() ZEND_DECLARE_MODULE_GLOBALS(redis) static zend_function_entry redis_functions[] = { PHP_ME(Redis, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC) PHP_ME(Redis, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC) PHP_ME(Redis, connect, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, pconnect, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, close, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, ping, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, echo, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, get, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, set, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setex, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, psetex, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setnx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getSet, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, randomKey, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, renameKey, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, renameNx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getMultiple, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, exists, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, delete, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, incr, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, incrBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, incrByFloat, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, decr, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, decrBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, type, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, append, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getRange, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setRange, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getBit, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setBit, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, strlen, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getKeys, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sort, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sortAsc, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sortAscAlpha, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sortDesc, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sortDescAlpha, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lPush, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, rPush, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lPushx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, rPushx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lPop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, rPop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, blPop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, brPop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lSize, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lRemove, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, listTrim, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lGet, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lGetRange, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lSet, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lInsert, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sAdd, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sSize, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sRemove, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sMove, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sPop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sRandMember, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sContains, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sMembers, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sInter, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sInterStore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sUnion, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sUnionStore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sDiff, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, sDiffStore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setTimeout, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, save, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, bgSave, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, lastSave, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, flushDB, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, flushAll, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, dbSize, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, auth, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, ttl, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, pttl, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, persist, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, info, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, resetStat, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, select, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, move, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, bgrewriteaof, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, slaveof, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, object, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, bitop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, bitcount, NULL, ZEND_ACC_PUBLIC) /* 1.1 */ PHP_ME(Redis, mset, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, msetnx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, rpoplpush, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, brpoplpush, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zAdd, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zDelete, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zRange, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zReverseRange, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zRangeByScore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zRevRangeByScore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zCount, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zDeleteRangeByScore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zDeleteRangeByRank, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zCard, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zScore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zRank, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zRevRank, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zInter, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zUnion, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, zIncrBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, expireAt, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, pexpire, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, pexpireAt, NULL, ZEND_ACC_PUBLIC) /* 1.2 */ PHP_ME(Redis, hGet, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hSet, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hSetNx, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hDel, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hLen, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hKeys, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hVals, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hGetAll, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hExists, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hIncrBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hIncrByFloat, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hMset, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, hMget, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, multi, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, discard, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, exec, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, pipeline, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, watch, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, unwatch, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, publish, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, subscribe, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, psubscribe, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, unsubscribe, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, punsubscribe, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, time, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, eval, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, evalsha, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, script, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, dump, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, restore, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, migrate, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getLastError, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, clearLastError, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, _prefix, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, _unserialize, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, client, NULL, ZEND_ACC_PUBLIC) /* options */ PHP_ME(Redis, getOption, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, setOption, NULL, ZEND_ACC_PUBLIC) /* config */ PHP_ME(Redis, config, NULL, ZEND_ACC_PUBLIC) /* slowlog */ PHP_ME(Redis, slowlog, NULL, ZEND_ACC_PUBLIC) /* introspection */ PHP_ME(Redis, getHost, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getPort, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getDBNum, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getTimeout, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getReadTimeout, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getPersistentID, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, getAuth, NULL, ZEND_ACC_PUBLIC) PHP_ME(Redis, isConnected, NULL, ZEND_ACC_PUBLIC) /* aliases */ PHP_MALIAS(Redis, open, connect, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, popen, pconnect, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, lLen, lSize, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, sGetMembers, sMembers, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, mget, getMultiple, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, expire, setTimeout, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zunionstore, zUnion, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zinterstore, zInter, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zRemove, zDelete, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zRem, zDelete, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zRemoveRangeByScore, zDeleteRangeByScore, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zRemRangeByScore, zDeleteRangeByScore, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zRemRangeByRank, zDeleteRangeByRank, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zSize, zCard, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, substr, getRange, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, rename, renameKey, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, del, delete, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, keys, getKeys, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, lrem, lRemove, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, ltrim, listTrim, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, lindex, lGet, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, lrange, lGetRange, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, scard, sSize, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, srem, sRemove, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, sismember, sContains, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, zrevrange, zReverseRange, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, sendEcho, echo, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, evaluate, eval, NULL, ZEND_ACC_PUBLIC) PHP_MALIAS(Redis, evaluateSha, evalsha, NULL, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; zend_module_entry redis_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "redis", NULL, PHP_MINIT(redis), PHP_MSHUTDOWN(redis), PHP_RINIT(redis), PHP_RSHUTDOWN(redis), PHP_MINFO(redis), #if ZEND_MODULE_API_NO >= 20010901 PHP_REDIS_VERSION, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_REDIS ZEND_GET_MODULE(redis) #endif PHPAPI zend_class_entry *redis_get_exception_base(int root TSRMLS_DC) { #if HAVE_SPL if (!root) { if (!spl_ce_RuntimeException) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), "runtimeexception", sizeof("RuntimeException"), (void **) &pce) == SUCCESS) { spl_ce_RuntimeException = *pce; return *pce; } } else { return spl_ce_RuntimeException; } } #endif #if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 2) return zend_exception_get_default(); #else return zend_exception_get_default(TSRMLS_C); #endif } /** * Send a static DISCARD in case we're in MULTI mode. */ static int send_discard_static(RedisSock *redis_sock TSRMLS_DC) { int result = FAILURE; char *cmd, *response; int response_len, cmd_len; /* format our discard command */ cmd_len = redis_cmd_format_static(&cmd, "DISCARD", ""); /* send our DISCARD command */ if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) >= 0 && (response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) != NULL) { /* success if we get OK */ result = (response_len == 3 && strncmp(response,"+OK", 3) == 0) ? SUCCESS : FAILURE; /* free our response */ efree(response); } /* free our command */ efree(cmd); /* return success/failure */ return result; } /** * redis_destructor_redis_sock */ static void redis_destructor_redis_sock(zend_rsrc_list_entry * rsrc TSRMLS_DC) { RedisSock *redis_sock = (RedisSock *) rsrc->ptr; redis_sock_disconnect(redis_sock TSRMLS_CC); redis_free_socket(redis_sock); } /** * redis_sock_get */ PHPAPI int redis_sock_get(zval *id, RedisSock **redis_sock TSRMLS_DC, int no_throw) { zval **socket; int resource_type; if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), "socket", sizeof("socket"), (void **) &socket) == FAILURE) { // Throw an exception unless we've been requested not to if(!no_throw) { zend_throw_exception(redis_exception_ce, "Redis server went away", 0 TSRMLS_CC); } return -1; } *redis_sock = (RedisSock *) zend_list_find(Z_LVAL_PP(socket), &resource_type); if (!*redis_sock || resource_type != le_redis_sock) { // Throw an exception unless we've been requested not to if(!no_throw) { zend_throw_exception(redis_exception_ce, "Redis server went away", 0 TSRMLS_CC); } return -1; } if ((*redis_sock)->lazy_connect) { (*redis_sock)->lazy_connect = 0; if (redis_sock_server_open(*redis_sock, 1 TSRMLS_CC) < 0) { return -1; } } return Z_LVAL_PP(socket); } /** * redis_sock_get_direct * Returns our attached RedisSock pointer if we're connected */ PHPAPI RedisSock *redis_sock_get_connected(INTERNAL_FUNCTION_PARAMETERS) { zval *object; RedisSock *redis_sock; // If we can't grab our object, or get a socket, or we're not connected, return NULL if((zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) || (redis_sock_get(object, &redis_sock TSRMLS_CC, 1) < 0) || redis_sock->status != REDIS_SOCK_STATUS_CONNECTED) { return NULL; } // Return our socket return redis_sock; } /** * PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(redis) { zend_class_entry redis_class_entry; zend_class_entry redis_array_class_entry; zend_class_entry redis_exception_class_entry; REGISTER_INI_ENTRIES(); /* Redis class */ INIT_CLASS_ENTRY(redis_class_entry, "Redis", redis_functions); redis_ce = zend_register_internal_class(&redis_class_entry TSRMLS_CC); /* RedisArray class */ INIT_CLASS_ENTRY(redis_array_class_entry, "RedisArray", redis_array_functions); redis_array_ce = zend_register_internal_class(&redis_array_class_entry TSRMLS_CC); le_redis_array = zend_register_list_destructors_ex( redis_destructor_redis_array, NULL, "Redis Array", module_number ); /* RedisException class */ INIT_CLASS_ENTRY(redis_exception_class_entry, "RedisException", NULL); redis_exception_ce = zend_register_internal_class_ex( &redis_exception_class_entry, redis_get_exception_base(0 TSRMLS_CC), NULL TSRMLS_CC ); le_redis_sock = zend_register_list_destructors_ex( redis_destructor_redis_sock, NULL, redis_sock_name, module_number ); add_constant_long(redis_ce, "REDIS_NOT_FOUND", REDIS_NOT_FOUND); add_constant_long(redis_ce, "REDIS_STRING", REDIS_STRING); add_constant_long(redis_ce, "REDIS_SET", REDIS_SET); add_constant_long(redis_ce, "REDIS_LIST", REDIS_LIST); add_constant_long(redis_ce, "REDIS_ZSET", REDIS_ZSET); add_constant_long(redis_ce, "REDIS_HASH", REDIS_HASH); add_constant_long(redis_ce, "ATOMIC", ATOMIC); add_constant_long(redis_ce, "MULTI", MULTI); add_constant_long(redis_ce, "PIPELINE", PIPELINE); /* options */ add_constant_long(redis_ce, "OPT_SERIALIZER", REDIS_OPT_SERIALIZER); add_constant_long(redis_ce, "OPT_PREFIX", REDIS_OPT_PREFIX); add_constant_long(redis_ce, "OPT_READ_TIMEOUT", REDIS_OPT_READ_TIMEOUT); /* serializer */ add_constant_long(redis_ce, "SERIALIZER_NONE", REDIS_SERIALIZER_NONE); add_constant_long(redis_ce, "SERIALIZER_PHP", REDIS_SERIALIZER_PHP); #ifdef HAVE_REDIS_IGBINARY add_constant_long(redis_ce, "SERIALIZER_IGBINARY", REDIS_SERIALIZER_IGBINARY); #endif zend_declare_class_constant_stringl(redis_ce, "AFTER", 5, "after", 5 TSRMLS_CC); zend_declare_class_constant_stringl(redis_ce, "BEFORE", 6, "before", 6 TSRMLS_CC); #ifdef PHP_SESSION /* declare session handler */ php_session_register_module(&ps_mod_redis); #endif return SUCCESS; } /** * PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(redis) { return SUCCESS; } /** * PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(redis) { return SUCCESS; } /** * PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(redis) { return SUCCESS; } /** * PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(redis) { php_info_print_table_start(); php_info_print_table_header(2, "Redis Support", "enabled"); php_info_print_table_row(2, "Redis Version", PHP_REDIS_VERSION); php_info_print_table_end(); } /* {{{ proto Redis Redis::__construct() Public constructor */ PHP_METHOD(Redis, __construct) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { RETURN_FALSE; } } /* }}} */ /* {{{ proto Redis Redis::__destruct() Public Destructor */ PHP_METHOD(Redis,__destruct) { if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { RETURN_FALSE; } // Grab our socket RedisSock *redis_sock; if (redis_sock_get(getThis(), &redis_sock TSRMLS_CC, 1) < 0) { RETURN_FALSE; } // If we think we're in MULTI mode, send a discard if(redis_sock->mode == MULTI) { // Discard any multi commands, and free any callbacks that have been queued send_discard_static(redis_sock TSRMLS_CC); free_reply_callbacks(getThis(), redis_sock); } } /* {{{ proto boolean Redis::connect(string host, int port [, double timeout [, long retry_interval]]) */ PHP_METHOD(Redis, connect) { if (redis_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0) == FAILURE) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto boolean Redis::pconnect(string host, int port [, double timeout]) */ PHP_METHOD(Redis, pconnect) { if (redis_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1) == FAILURE) { RETURN_FALSE; } else { /* reset multi/exec state if there is one. */ RedisSock *redis_sock; if (redis_sock_get(getThis(), &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } RETURN_TRUE; } } /* }}} */ PHPAPI int redis_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) { zval *object; zval **socket; int host_len, id; char *host = NULL; long port = -1; long retry_interval = 0; char *persistent_id = NULL; int persistent_id_len = -1; double timeout = 0.0; RedisSock *redis_sock = NULL; #ifdef ZTS /* not sure how in threaded mode this works so disabled persistents at first */ persistent = 0; #endif if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|ldsl", &object, redis_ce, &host, &host_len, &port, &timeout, &persistent_id, &persistent_id_len, &retry_interval) == FAILURE) { return FAILURE; } if (timeout < 0L || timeout > INT_MAX) { zend_throw_exception(redis_exception_ce, "Invalid timeout", 0 TSRMLS_CC); return FAILURE; } if (retry_interval < 0L || retry_interval > INT_MAX) { zend_throw_exception(redis_exception_ce, "Invalid retry interval", 0 TSRMLS_CC); return FAILURE; } if(port == -1 && host_len && host[0] != '/') { /* not unix socket, set to default value */ port = 6379; } /* if there is a redis sock already we have to remove it from the list */ if (redis_sock_get(object, &redis_sock TSRMLS_CC, 1) > 0) { if (zend_hash_find(Z_OBJPROP_P(object), "socket", sizeof("socket"), (void **) &socket) == FAILURE) { /* maybe there is a socket but the id isn't known.. what to do? */ } else { zend_list_delete(Z_LVAL_PP(socket)); /* the refcount should be decreased and the detructor called */ } } redis_sock = redis_sock_create(host, host_len, port, timeout, persistent, persistent_id, retry_interval, 0); if (redis_sock_server_open(redis_sock, 1 TSRMLS_CC) < 0) { redis_free_socket(redis_sock); return FAILURE; } #if PHP_VERSION_ID >= 50400 id = zend_list_insert(redis_sock, le_redis_sock TSRMLS_CC); #else id = zend_list_insert(redis_sock, le_redis_sock); #endif add_property_resource(object, "socket", id); return SUCCESS; } /* {{{ proto boolean Redis::bitop(string op, string key, ...) */ PHP_METHOD(Redis, bitop) { char *cmd; int cmd_len; zval **z_args; char **keys; int *keys_len; int argc = ZEND_NUM_ARGS(), i; RedisSock *redis_sock = NULL; smart_str buf = {0}; int key_free = 0; /* get redis socket */ if (redis_sock_get(getThis(), &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* fetch args */ z_args = emalloc(argc * sizeof(zval*)); if(zend_get_parameters_array(ht, argc, z_args) == FAILURE || argc < 3 /* 3 args min. */ || Z_TYPE_P(z_args[0]) != IS_STRING /* operation must be a string. */ ) { efree(z_args); RETURN_FALSE; } keys = emalloc(argc * sizeof(char*)); keys_len = emalloc(argc * sizeof(int)); /* prefix keys */ for(i = 0; i < argc; ++i) { convert_to_string(z_args[i]); keys[i] = Z_STRVAL_P(z_args[i]); keys_len[i] = Z_STRLEN_P(z_args[i]); if(i != 0) key_free = redis_key_prefix(redis_sock, &keys[i], &keys_len[i] TSRMLS_CC); } /* start building the command */ smart_str_appendc(&buf, '*'); smart_str_append_long(&buf, argc + 1); /* +1 for BITOP command */ smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); /* add command name */ smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, 5); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, "BITOP", 5); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); /* add keys */ for(i = 0; i < argc; ++i) { smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, keys_len[i]); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, keys[i], keys_len[i]); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); } /* end string */ smart_str_0(&buf); cmd = buf.c; cmd_len = buf.len; /* cleanup */ if(key_free) for(i = 1; i < argc; ++i) { efree(keys[i]); } efree(keys); efree(keys_len); efree(z_args); /* send */ REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::bitcount(string key, [int start], [int end]) */ PHP_METHOD(Redis, bitcount) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start = 0, end = -1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|ll", &object, redis_ce, &key, &key_len, &start, &end) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* BITCOUNT key start end */ key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "BITCOUNT", "sdd", key, key_len, (int)start, (int)end); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::close() */ PHP_METHOD(Redis, close) { zval *object; RedisSock *redis_sock = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if (redis_sock_disconnect(redis_sock TSRMLS_CC)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto boolean Redis::set(string key, mixed value, long timeout | array options) */ PHP_METHOD(Redis, set) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd, *exp_type = NULL, *set_type = NULL; int key_len, val_len, cmd_len; long expire = -1; int val_free = 0, key_free = 0; zval *z_value, *z_opts = NULL; // Make sure the arguments are correct if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz|z", &object, redis_ce, &key, &key_len, &z_value, &z_opts) == FAILURE) { RETURN_FALSE; } // Ensure we can grab our redis socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* Our optional argument can either be a long (to support legacy SETEX */ /* redirection), or an array with Redis >= 2.6.12 set options */ if(z_opts && Z_TYPE_P(z_opts) != IS_LONG && Z_TYPE_P(z_opts) != IS_ARRAY) { RETURN_FALSE; } /* Serialization, key prefixing */ val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if(z_opts && Z_TYPE_P(z_opts) == IS_ARRAY) { HashTable *kt = Z_ARRVAL_P(z_opts); int type; unsigned int ht_key_len; unsigned long idx; char *k; zval **v; /* Iterate our option array */ for(zend_hash_internal_pointer_reset(kt); zend_hash_has_more_elements(kt) == SUCCESS; zend_hash_move_forward(kt)) { // Grab key and value type = zend_hash_get_current_key_ex(kt, &k, &ht_key_len, &idx, 0, NULL); zend_hash_get_current_data(kt, (void**)&v); if(type == HASH_KEY_IS_STRING && (Z_TYPE_PP(v) == IS_LONG) && (Z_LVAL_PP(v) > 0) && IS_EX_PX_ARG(k)) { exp_type = k; expire = Z_LVAL_PP(v); } else if(Z_TYPE_PP(v) == IS_STRING && IS_NX_XX_ARG(Z_STRVAL_PP(v))) { set_type = Z_STRVAL_PP(v); } } } else if(z_opts && Z_TYPE_P(z_opts) == IS_LONG) { expire = Z_LVAL_P(z_opts); } /* Now let's construct the command we want */ if(exp_type && set_type) { /* SET NX|XX PX|EX */ cmd_len = redis_cmd_format_static(&cmd, "SET", "ssssl", key, key_len, val, val_len, set_type, 2, exp_type, 2, expire); } else if(exp_type) { /* SET PX|EX */ cmd_len = redis_cmd_format_static(&cmd, "SET", "sssl", key, key_len, val, val_len, exp_type, 2, expire); } else if(set_type) { /* SET NX|XX */ cmd_len = redis_cmd_format_static(&cmd, "SET", "sss", key, key_len, val, val_len, set_type, 2); } else if(expire > 0) { /* Backward compatible SETEX redirection */ cmd_len = redis_cmd_format_static(&cmd, "SETEX", "sds", key, key_len, expire, val, val_len); } else { /* SET */ cmd_len = redis_cmd_format_static(&cmd, "SET", "ss", key, key_len, val, val_len); } /* Free our key or value if we prefixed/serialized */ if(key_free) efree(key); if(val_free) efree(val); /* Kick off the command */ REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } PHPAPI void redis_generic_setex(INTERNAL_FUNCTION_PARAMETERS, char *keyword) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; long expire; int val_free = 0, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oslz", &object, redis_ce, &key, &key_len, &expire, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "sds", key, key_len, expire, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* {{{ proto boolean Redis::setex(string key, long expire, string value) */ PHP_METHOD(Redis, setex) { redis_generic_setex(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SETEX"); } /* {{{ proto boolean Redis::psetex(string key, long expire, string value) */ PHP_METHOD(Redis, psetex) { redis_generic_setex(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PSETEX"); } /* {{{ proto boolean Redis::setnx(string key, string value) */ PHP_METHOD(Redis, setnx) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; int val_free = 0, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SETNX", "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ /* {{{ proto string Redis::getSet(string key, string value) */ PHP_METHOD(Redis, getSet) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; int val_free = 0, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "GETSET", "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* }}} */ /* {{{ proto string Redis::randomKey() */ PHP_METHOD(Redis, randomKey) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } cmd_len = redis_cmd_format(&cmd, "*1" _NL "$9" _NL "RANDOMKEY" _NL); /* TODO: remove prefix from key */ REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_ping_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_ping_response); } /* }}} */ /* {{{ proto string Redis::echo(string key) */ PHP_METHOD(Redis, echo) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len; int key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ECHO", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* }}} */ /* {{{ proto string Redis::renameKey(string key_src, string key_dst) */ PHP_METHOD(Redis, renameKey) { zval *object; RedisSock *redis_sock; char *cmd, *src, *dst; int cmd_len, src_len, dst_len; int src_free, dst_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &src, &src_len, &dst, &dst_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } src_free = redis_key_prefix(redis_sock, &src, &src_len TSRMLS_CC); dst_free = redis_key_prefix(redis_sock, &dst, &dst_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "RENAME", "ss", src, src_len, dst, dst_len); if(src_free) efree(src); if(dst_free) efree(dst); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ /* {{{ proto string Redis::renameNx(string key_src, string key_dst) */ PHP_METHOD(Redis, renameNx) { zval *object; RedisSock *redis_sock; char *cmd, *src, *dst; int cmd_len, src_len, dst_len; int src_free, dst_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &src, &src_len, &dst, &dst_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } src_free = redis_key_prefix(redis_sock, &src, &src_len TSRMLS_CC); dst_free = redis_key_prefix(redis_sock, &dst, &dst_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "RENAMENX", "ss", src, src_len, dst, dst_len); if(src_free) efree(src); if(dst_free) efree(dst); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ /* {{{ proto string Redis::get(string key) */ PHP_METHOD(Redis, get) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len; int key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "GET", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* }}} */ /* {{{ proto string Redis::ping() */ PHP_METHOD(Redis, ping) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } cmd_len = redis_cmd_format_static(&cmd, "PING", ""); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_ping_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_ping_response); } /* }}} */ PHPAPI void redis_atomic_increment(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int count) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len; long val = 1; int key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if (val == 1) { cmd_len = redis_cmd_format_static(&cmd, keyword, "s", key, key_len); } else { cmd_len = redis_cmd_format_static(&cmd, keyword, "sl", key, key_len, val); } if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* {{{ proto boolean Redis::incr(string key [,int value]) */ PHP_METHOD(Redis, incr){ zval *object; char *key = NULL; int key_len; long val = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if(val == 1) { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCR", 1); } else { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCRBY", val); } } /* }}} */ /* {{{ proto boolean Redis::incrBy(string key ,int value) */ PHP_METHOD(Redis, incrBy){ zval *object; char *key = NULL; int key_len; long val = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osl", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if(val == 1) { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCR", 1); } else { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "INCRBY", val); } } /* }}} */ /* {{{ proto float Redis::incrByFloat(string key, float value) */ PHP_METHOD(Redis, incrByFloat) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; double val; if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osd", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Prefix our key, free it if we have key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if(key_free) efree(key); // Format our INCRBYFLOAT command cmd_len = redis_cmd_format_static(&cmd, "INCRBYFLOAT", "sf", key, key_len, val); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_bulk_double_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_bulk_double_response); } /* {{{ proto boolean Redis::decr(string key [,int value]) */ PHP_METHOD(Redis, decr) { zval *object; char *key = NULL; int key_len; long val = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if(val == 1) { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DECR", 1); } else { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DECRBY", val); } } /* }}} */ /* {{{ proto boolean Redis::decrBy(string key ,int value) */ PHP_METHOD(Redis, decrBy){ zval *object; char *key = NULL; int key_len; long val = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osl", &object, redis_ce, &key, &key_len, &val) == FAILURE) { RETURN_FALSE; } if(val == 1) { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DECR", 1); } else { redis_atomic_increment(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DECRBY", val); } } /* }}} */ /* {{{ proto array Redis::getMultiple(array keys) */ PHP_METHOD(Redis, getMultiple) { zval *object, *z_args, **z_ele; HashTable *hash; HashPosition ptr; RedisSock *redis_sock; smart_str cmd = {0}; int arg_count; // Make sure we have proper arguments if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa", &object, redis_ce, &z_args) == FAILURE) { RETURN_FALSE; } // We'll need the socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Grab our array hash = Z_ARRVAL_P(z_args); // We don't need to do anything if there aren't any keys if((arg_count = zend_hash_num_elements(hash)) == 0) { RETURN_FALSE; } // Build our command header redis_cmd_init_sstr(&cmd, arg_count, "MGET", 4); // Iterate through and grab our keys for(zend_hash_internal_pointer_reset_ex(hash, &ptr); zend_hash_get_current_data_ex(hash, (void**)&z_ele, &ptr) == SUCCESS; zend_hash_move_forward_ex(hash, &ptr)) { char *key; int key_len, key_free; zval *z_tmp = NULL; // If the key isn't a string, turn it into one if(Z_TYPE_PP(z_ele) == IS_STRING) { key = Z_STRVAL_PP(z_ele); key_len = Z_STRLEN_PP(z_ele); } else { MAKE_STD_ZVAL(z_tmp); *z_tmp = **z_ele; zval_copy_ctor(z_tmp); convert_to_string(z_tmp); key = Z_STRVAL_P(z_tmp); key_len = Z_STRLEN_P(z_tmp); } // Apply key prefix if necissary key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); // Append this key to our command redis_cmd_append_sstr(&cmd, key, key_len); // Free our key if it was prefixed if(key_free) efree(key); // Free oour temporary ZVAL if we converted from a non-string if(z_tmp) { zval_dtor(z_tmp); efree(z_tmp); z_tmp = NULL; } } // Kick off our command REDIS_PROCESS_REQUEST(redis_sock, cmd.c, cmd.len); IF_ATOMIC() { if(redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* {{{ proto boolean Redis::exists(string key) */ PHP_METHOD(Redis, exists) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len; int key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "EXISTS", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ /* {{{ proto boolean Redis::delete(string key) */ PHP_METHOD(Redis, delete) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DEL", sizeof("DEL") - 1, 1, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ PHPAPI void redis_set_watch(RedisSock *redis_sock) { redis_sock->watching = 1; } PHPAPI void redis_watch_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { redis_boolean_response_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, ctx, redis_set_watch); } /* {{{ proto boolean Redis::watch(string key1, string key2...) */ PHP_METHOD(Redis, watch) { RedisSock *redis_sock; generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "WATCH", sizeof("WATCH") - 1, 1, &redis_sock, 0, 1, 1); redis_sock->watching = 1; IF_ATOMIC() { redis_watch_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_watch_response); } /* }}} */ PHPAPI void redis_clear_watch(RedisSock *redis_sock) { redis_sock->watching = 0; } PHPAPI void redis_unwatch_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) { redis_boolean_response_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, ctx, redis_clear_watch); } /* {{{ proto boolean Redis::unwatch() */ PHP_METHOD(Redis, unwatch) { char cmd[] = "*1" _NL "$7" _NL "UNWATCH" _NL; generic_empty_cmd_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, estrdup(cmd), sizeof(cmd)-1, redis_unwatch_response); } /* }}} */ /* {{{ proto array Redis::getKeys(string pattern) */ PHP_METHOD(Redis, getKeys) { zval *object; RedisSock *redis_sock; char *pattern = NULL, *cmd; int pattern_len, cmd_len, pattern_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &pattern, &pattern_len) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } pattern_free = redis_key_prefix(redis_sock, &pattern, &pattern_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "KEYS", "s", pattern, pattern_len); if(pattern_free) efree(pattern); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if (redis_sock_read_multibulk_reply_raw(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_raw); } /* }}} */ /* {{{ proto int Redis::type(string key) */ PHP_METHOD(Redis, type) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "TYPE", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_type_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_type_response); } /* }}} */ PHP_METHOD(Redis, append) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len, key_len, val_len, key_free; char *key, *val; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &key, &key_len, &val, &val_len) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "APPEND", "ss", key, key_len, val, val_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHP_METHOD(Redis, getRange) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll", &object, redis_ce, &key, &key_len, &start, &end) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "GETRANGE", "sdd", key, key_len, (int)start, (int)end); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } PHP_METHOD(Redis, setRange) { zval *object; RedisSock *redis_sock; char *key = NULL, *val, *cmd; int key_len, val_len, cmd_len, key_free; long offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osls", &object, redis_ce, &key, &key_len, &offset, &val, &val_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SETRANGE", "sds", key, key_len, (int)offset, val, val_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHP_METHOD(Redis, getBit) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osl", &object, redis_ce, &key, &key_len, &offset) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "GETBIT", "sd", key, key_len, (int)offset); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHP_METHOD(Redis, setBit) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long offset; zend_bool val; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oslb", &object, redis_ce, &key, &key_len, &offset, &val) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SETBIT", "sdd", key, key_len, (int)offset, (int)val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHP_METHOD(Redis, strlen) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len, key_len, key_free; char *key; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "STRLEN", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHPAPI void generic_push_function(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *cmd, *key, *val; int cmd_len, key_len, val_len; zval *z_value; int val_free, key_free = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* {{{ proto boolean Redis::lPush(string key , string value) */ PHP_METHOD(Redis, lPush) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "LPUSH", sizeof("LPUSH") - 1, 2, &redis_sock, 0, 0, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::rPush(string key , string value) */ PHP_METHOD(Redis, rPush) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "RPUSH", sizeof("RPUSH") - 1, 2, &redis_sock, 0, 0, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ PHP_METHOD(Redis, lInsert) { zval *object; RedisSock *redis_sock; char *pivot, *position, *key, *val, *cmd; int pivot_len, position_len, key_len, val_len, cmd_len; int val_free, pivot_free, key_free; zval *z_value, *z_pivot; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osszz", &object, redis_ce, &key, &key_len, &position, &position_len, &z_pivot, &z_value) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if(strncasecmp(position, "after", 5) == 0 || strncasecmp(position, "before", 6) == 0) { key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); pivot_free = redis_serialize(redis_sock, z_pivot, &pivot, &pivot_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LINSERT", "ssss", key, key_len, position, position_len, pivot, pivot_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); if(pivot_free) efree(pivot); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Error on position"); } } PHP_METHOD(Redis, lPushx) { generic_push_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, "LPUSHX", sizeof("LPUSHX")-1); } PHP_METHOD(Redis, rPushx) { generic_push_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, "RPUSHX", sizeof("RPUSHX")-1); } PHPAPI void generic_pop_function(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* {{{ proto string Redis::lPOP(string key) */ PHP_METHOD(Redis, lPop) { generic_pop_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, "LPOP", sizeof("LPOP")-1); } /* }}} */ /* {{{ proto string Redis::rPOP(string key) */ PHP_METHOD(Redis, rPop) { generic_pop_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, "RPOP", sizeof("RPOP")-1); } /* }}} */ /* {{{ proto string Redis::blPop(string key1, string key2, ..., int timeout) */ PHP_METHOD(Redis, blPop) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "BLPOP", sizeof("BLPOP") - 1, 2, &redis_sock, 1, 1, 1)) return; IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto string Redis::brPop(string key1, string key2, ..., int timeout) */ PHP_METHOD(Redis, brPop) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "BRPOP", sizeof("BRPOP") - 1, 2, &redis_sock, 1, 1, 1)) return; IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto int Redis::lSize(string key) */ PHP_METHOD(Redis, lSize) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LLEN", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::lRemove(string list, string value, int count = 0) */ PHP_METHOD(Redis, lRemove) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len, key_len, val_len; char *key, *val; long count = 0; zval *z_value; int val_free, key_free = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz|l", &object, redis_ce, &key, &key_len, &z_value, &count) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* LREM key count value */ val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LREM", "sds", key, key_len, count, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::listTrim(string key , int start , int end) */ PHP_METHOD(Redis, listTrim) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll", &object, redis_ce, &key, &key_len, &start, &end) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LTRIM", "sdd", key, key_len, (int)start, (int)end); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ /* {{{ proto string Redis::lGet(string key , int index) */ PHP_METHOD(Redis, lGet) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long index; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osl", &object, redis_ce, &key, &key_len, &index) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* LINDEX key pos */ key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LINDEX", "sd", key, key_len, (int)index); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* }}} */ /* {{{ proto array Redis::lGetRange(string key, int start , int end) */ PHP_METHOD(Redis, lGetRange) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll", &object, redis_ce, &key, &key_len, &start, &end) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* LRANGE key start end */ key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LRANGE", "sdd", key, key_len, (int)start, (int)end); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto boolean Redis::sAdd(string key , mixed value) */ PHP_METHOD(Redis, sAdd) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SADD", sizeof("SADD") - 1, 2, &redis_sock, 0, 0, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto int Redis::sSize(string key) */ PHP_METHOD(Redis, sSize) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SCARD", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::sRemove(string set, string value) */ PHP_METHOD(Redis, sRemove) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SREM", sizeof("SREM") - 1, 2, &redis_sock, 0, 0, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto boolean Redis::sMove(string set_src, string set_dst, mixed value) */ PHP_METHOD(Redis, sMove) { zval *object; RedisSock *redis_sock; char *src = NULL, *dst = NULL, *val = NULL, *cmd; int src_len, dst_len, val_len, cmd_len; int val_free, src_free, dst_free; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ossz", &object, redis_ce, &src, &src_len, &dst, &dst_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); src_free = redis_key_prefix(redis_sock, &src, &src_len TSRMLS_CC); dst_free = redis_key_prefix(redis_sock, &dst, &dst_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SMOVE", "sss", src, src_len, dst, dst_len, val, val_len); if(val_free) efree(val); if(src_free) efree(src); if(dst_free) efree(dst); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ /* }}} */ /* {{{ proto string Redis::sPop(string key) */ PHP_METHOD(Redis, sPop) { generic_pop_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SPOP", 4); } /* }}} */ /* }}} */ /* {{{ proto string Redis::sRandMember(string key [int count]) */ PHP_METHOD(Redis, sRandMember) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free = 0; long count; // Parse our params if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_ce, &key, &key_len, &count) == FAILURE) { RETURN_FALSE; } // Get our redis socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Prefix our key if necissary key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); // If we have two arguments, we're running with an optional COUNT, which will return // a multibulk reply. Without the argument we'll return a string response if(ZEND_NUM_ARGS() == 2) { // Construct our command with count cmd_len = redis_cmd_format_static(&cmd, "SRANDMEMBER", "sl", key, key_len, count); } else { // Construct our command cmd_len = redis_cmd_format_static(&cmd, "SRANDMEMBER", "s", key, key_len); } // Free our key if we prefixed it if(key_free) efree(key); // Process our command REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); // Process our reply IF_ATOMIC() { // This will be bulk or multi-bulk depending if we passed the optional [COUNT] argument if(redis_read_variant_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_read_variant_reply); } /* }}} */ /* {{{ proto boolean Redis::sContains(string set, string value) */ PHP_METHOD(Redis, sContains) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; int val_free, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { return; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SISMEMBER", "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ /* {{{ proto array Redis::sMembers(string set) */ PHP_METHOD(Redis, sMembers) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "SMEMBERS", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ PHPAPI int generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len, int min_argc, RedisSock **out_sock, int has_timeout, int all_keys, int can_serialize) { zval **z_args, *z_array; char **keys, *cmd; int cmd_len, *keys_len, *keys_to_free; int i, j, argc = ZEND_NUM_ARGS(), real_argc = 0; int single_array = 0; int timeout = 0; int pos; int array_size; RedisSock *redis_sock; if(argc < min_argc) { zend_wrong_param_count(TSRMLS_C); ZVAL_BOOL(return_value, 0); return FAILURE; } /* get redis socket */ if (redis_sock_get(getThis(), out_sock TSRMLS_CC, 0) < 0) { ZVAL_BOOL(return_value, 0); return FAILURE; } redis_sock = *out_sock; z_args = emalloc(argc * sizeof(zval*)); if(zend_get_parameters_array(ht, argc, z_args) == FAILURE) { efree(z_args); ZVAL_BOOL(return_value, 0); return FAILURE; } /* case of a single array */ if(has_timeout == 0) { if(argc == 1 && Z_TYPE_P(z_args[0]) == IS_ARRAY) { single_array = 1; z_array = z_args[0]; efree(z_args); z_args = NULL; /* new count */ argc = zend_hash_num_elements(Z_ARRVAL_P(z_array)); } } else if(has_timeout == 1) { if(argc == 2 && Z_TYPE_P(z_args[0]) == IS_ARRAY && Z_TYPE_P(z_args[1]) == IS_LONG) { single_array = 1; z_array = z_args[0]; timeout = Z_LVAL_P(z_args[1]); efree(z_args); z_args = NULL; /* new count */ argc = zend_hash_num_elements(Z_ARRVAL_P(z_array)); } } /* prepare an array for the keys, one for their lengths, one to mark the keys to free. */ array_size = argc; if(has_timeout) array_size++; keys = emalloc(array_size * sizeof(char*)); keys_len = emalloc(array_size * sizeof(int)); keys_to_free = emalloc(array_size * sizeof(int)); memset(keys_to_free, 0, array_size * sizeof(int)); cmd_len = 1 + integer_length(keyword_len) + 2 +keyword_len + 2; /* start computing the command length */ if(single_array) { /* loop over the array */ HashTable *keytable = Z_ARRVAL_P(z_array); for(j = 0, zend_hash_internal_pointer_reset(keytable); zend_hash_has_more_elements(keytable) == SUCCESS; zend_hash_move_forward(keytable)) { char *key; unsigned int key_len; unsigned long idx; zval **z_value_pp; zend_hash_get_current_key_ex(keytable, &key, &key_len, &idx, 0, NULL); if(zend_hash_get_current_data(keytable, (void**)&z_value_pp) == FAILURE) { continue; /* this should never happen, according to the PHP people. */ } if(!all_keys && j != 0) { /* not just operating on keys */ if(can_serialize) { keys_to_free[j] = redis_serialize(redis_sock, *z_value_pp, &keys[j], &keys_len[j] TSRMLS_CC); } else { convert_to_string(*z_value_pp); keys[j] = Z_STRVAL_PP(z_value_pp); keys_len[j] = Z_STRLEN_PP(z_value_pp); keys_to_free[j] = 0; } } else { /* only accept strings */ if(Z_TYPE_PP(z_value_pp) != IS_STRING) { convert_to_string(*z_value_pp); } /* get current value */ keys[j] = Z_STRVAL_PP(z_value_pp); keys_len[j] = Z_STRLEN_PP(z_value_pp); keys_to_free[j] = redis_key_prefix(redis_sock, &keys[j], &keys_len[j] TSRMLS_CC); /* add optional prefix */ } cmd_len += 1 + integer_length(keys_len[j]) + 2 + keys_len[j] + 2; /* $ + size + NL + string + NL */ j++; real_argc++; } if(has_timeout) { keys_len[j] = spprintf(&keys[j], 0, "%d", timeout); cmd_len += 1 + integer_length(keys_len[j]) + 2 + keys_len[j] + 2; // $ + size + NL + string + NL j++; real_argc++; } } else { if(has_timeout && Z_TYPE_P(z_args[argc - 1]) != IS_LONG) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Syntax error on timeout"); } for(i = 0, j = 0; i < argc; ++i) { /* store each key */ if(!all_keys && j != 0) { /* not just operating on keys */ if(can_serialize) { keys_to_free[j] = redis_serialize(redis_sock, z_args[i], &keys[j], &keys_len[j] TSRMLS_CC); } else { convert_to_string(z_args[i]); keys[j] = Z_STRVAL_P(z_args[i]); keys_len[j] = Z_STRLEN_P(z_args[i]); keys_to_free[j] = 0; } } else { if(Z_TYPE_P(z_args[i]) != IS_STRING) { convert_to_string(z_args[i]); } keys[j] = Z_STRVAL_P(z_args[i]); keys_len[j] = Z_STRLEN_P(z_args[i]); // If we have a timeout it should be the last argument, which we do not want to prefix if(!has_timeout || i < argc-1) { keys_to_free[j] = redis_key_prefix(redis_sock, &keys[j], &keys_len[j] TSRMLS_CC); /* add optional prefix TSRMLS_CC*/ } } cmd_len += 1 + integer_length(keys_len[j]) + 2 + keys_len[j] + 2; /* $ + size + NL + string + NL */ j++; real_argc++; } } cmd_len += 1 + integer_length(real_argc+1) + 2; // *count NL cmd = emalloc(cmd_len+1); sprintf(cmd, "*%d" _NL "$%d" _NL "%s" _NL, 1+real_argc, keyword_len, keyword); pos = 1 +integer_length(real_argc + 1) + 2 + 1 + integer_length(keyword_len) + 2 + keyword_len + 2; /* copy each key to its destination */ for(i = 0; i < real_argc; ++i) { sprintf(cmd + pos, "$%d" _NL, keys_len[i]); // size pos += 1 + integer_length(keys_len[i]) + 2; memcpy(cmd + pos, keys[i], keys_len[i]); pos += keys_len[i]; memcpy(cmd + pos, _NL, 2); pos += 2; } /* cleanup prefixed keys. */ for(i = 0; i < real_argc + (has_timeout?-1:0); ++i) { if(keys_to_free[i]) efree(keys[i]); } if(single_array && has_timeout) { /* cleanup string created to contain timeout value */ efree(keys[real_argc-1]); } efree(keys); efree(keys_len); efree(keys_to_free); if(z_args) efree(z_args); /* call REDIS_PROCESS_REQUEST and skip void returns */ IF_MULTI_OR_ATOMIC() { if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return FAILURE; } efree(cmd); } IF_PIPELINE() { PIPELINE_ENQUEUE_COMMAND(cmd, cmd_len); efree(cmd); } return SUCCESS; } /* {{{ proto array Redis::sInter(string key0, ... string keyN) */ PHP_METHOD(Redis, sInter) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SINTER", sizeof("SINTER") - 1, 0, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto array Redis::sInterStore(string destination, string key0, ... string keyN) */ PHP_METHOD(Redis, sInterStore) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SINTERSTORE", sizeof("SINTERSTORE") - 1, 1, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto array Redis::sUnion(string key0, ... string keyN) */ PHP_METHOD(Redis, sUnion) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SUNION", sizeof("SUNION") - 1, 0, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto array Redis::sUnionStore(string destination, string key0, ... string keyN) */ PHP_METHOD(Redis, sUnionStore) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SUNIONSTORE", sizeof("SUNIONSTORE") - 1, 1, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto array Redis::sDiff(string key0, ... string keyN) */ PHP_METHOD(Redis, sDiff) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SDIFF", sizeof("SDIFF") - 1, 0, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { /* read multibulk reply */ if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* }}} */ /* {{{ proto array Redis::sDiffStore(string destination, string key0, ... string keyN) */ PHP_METHOD(Redis, sDiffStore) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "SDIFFSTORE", sizeof("SDIFFSTORE") - 1, 1, &redis_sock, 0, 1, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ PHP_METHOD(Redis, sort) { zval *object = getThis(), *z_array = NULL, **z_cur; char *cmd, *old_cmd = NULL, *key; int cmd_len, elements = 2, key_len, key_free; int using_store = 0; RedisSock *redis_sock; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|a", &object, redis_ce, &key, &key_len, &z_array) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format(&cmd, "$4" _NL "SORT" _NL "$%d" _NL "%s" _NL, key_len, key, key_len); if(key_free) efree(key); if(z_array) { if ((zend_hash_find(Z_ARRVAL_P(z_array), "by", sizeof("by"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "BY", sizeof("BY"), (void **) &z_cur) == SUCCESS) && Z_TYPE_PP(z_cur) == IS_STRING) { old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$2" _NL "BY" _NL "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(z_cur), Z_STRVAL_PP(z_cur), Z_STRLEN_PP(z_cur)); elements += 2; efree(old_cmd); } if ((zend_hash_find(Z_ARRVAL_P(z_array), "sort", sizeof("sort"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "SORT", sizeof("SORT"), (void **) &z_cur) == SUCCESS) && Z_TYPE_PP(z_cur) == IS_STRING) { old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(z_cur), Z_STRVAL_PP(z_cur), Z_STRLEN_PP(z_cur)); elements += 1; efree(old_cmd); } if ((zend_hash_find(Z_ARRVAL_P(z_array), "store", sizeof("store"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "STORE", sizeof("STORE"), (void **) &z_cur) == SUCCESS) && Z_TYPE_PP(z_cur) == IS_STRING) { using_store = 1; old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$5" _NL "STORE" _NL "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(z_cur), Z_STRVAL_PP(z_cur), Z_STRLEN_PP(z_cur)); elements += 2; efree(old_cmd); } if ((zend_hash_find(Z_ARRVAL_P(z_array), "get", sizeof("get"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "GET", sizeof("GET"), (void **) &z_cur) == SUCCESS) && (Z_TYPE_PP(z_cur) == IS_STRING || Z_TYPE_PP(z_cur) == IS_ARRAY)) { if(Z_TYPE_PP(z_cur) == IS_STRING) { old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$3" _NL "GET" _NL "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(z_cur), Z_STRVAL_PP(z_cur), Z_STRLEN_PP(z_cur)); elements += 2; efree(old_cmd); } else if(Z_TYPE_PP(z_cur) == IS_ARRAY) { // loop over the strings in that array and add them as patterns HashTable *keytable = Z_ARRVAL_PP(z_cur); for(zend_hash_internal_pointer_reset(keytable); zend_hash_has_more_elements(keytable) == SUCCESS; zend_hash_move_forward(keytable)) { char *key; unsigned int key_len; unsigned long idx; zval **z_value_pp; zend_hash_get_current_key_ex(keytable, &key, &key_len, &idx, 0, NULL); if(zend_hash_get_current_data(keytable, (void**)&z_value_pp) == FAILURE) { continue; /* this should never happen, according to the PHP people. */ } if(Z_TYPE_PP(z_value_pp) == IS_STRING) { old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$3" _NL "GET" _NL "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(z_value_pp), Z_STRVAL_PP(z_value_pp), Z_STRLEN_PP(z_value_pp)); elements += 2; efree(old_cmd); } } } } if ((zend_hash_find(Z_ARRVAL_P(z_array), "alpha", sizeof("alpha"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "ALPHA", sizeof("ALPHA"), (void **) &z_cur) == SUCCESS) && Z_TYPE_PP(z_cur) == IS_BOOL && Z_BVAL_PP(z_cur) == 1) { old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$5" _NL "ALPHA" _NL , cmd, cmd_len); elements += 1; efree(old_cmd); } if ((zend_hash_find(Z_ARRVAL_P(z_array), "limit", sizeof("limit"), (void **) &z_cur) == SUCCESS || zend_hash_find(Z_ARRVAL_P(z_array), "LIMIT", sizeof("LIMIT"), (void **) &z_cur) == SUCCESS) && Z_TYPE_PP(z_cur) == IS_ARRAY) { if(zend_hash_num_elements(Z_ARRVAL_PP(z_cur)) == 2) { zval **z_offset_pp, **z_count_pp; // get the two values from the table, check that they are indeed of LONG type if(SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(z_cur), 0, (void**)&z_offset_pp) && SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(z_cur), 1, (void**)&z_count_pp)) { long limit_low, limit_high; if((Z_TYPE_PP(z_offset_pp) == IS_LONG || Z_TYPE_PP(z_offset_pp) == IS_STRING) && (Z_TYPE_PP(z_count_pp) == IS_LONG || Z_TYPE_PP(z_count_pp) == IS_STRING)) { if(Z_TYPE_PP(z_offset_pp) == IS_LONG) { limit_low = Z_LVAL_PP(z_offset_pp); } else { limit_low = atol(Z_STRVAL_PP(z_offset_pp)); } if(Z_TYPE_PP(z_count_pp) == IS_LONG) { limit_high = Z_LVAL_PP(z_count_pp); } else { limit_high = atol(Z_STRVAL_PP(z_count_pp)); } old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "%s" "$5" _NL "LIMIT" _NL "$%d" _NL "%d" _NL "$%d" _NL "%d" _NL , cmd, cmd_len , integer_length(limit_low), limit_low , integer_length(limit_high), limit_high); elements += 3; efree(old_cmd); } } } } } /* complete with prefix */ old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "*%d" _NL "%s", elements, cmd, cmd_len); efree(old_cmd); /* run command */ REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); if(using_store) { IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } else { IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } } PHPAPI void generic_sort_cmd(INTERNAL_FUNCTION_PARAMETERS, char *sort, int use_alpha) { zval *object; RedisSock *redis_sock; char *key = NULL, *pattern = NULL, *get = NULL, *store = NULL, *cmd; int key_len, pattern_len = -1, get_len = -1, store_len = -1, cmd_len, key_free; long sort_start = -1, sort_count = -1; int cmd_elements; char *cmd_lines[30]; int cmd_sizes[30]; int sort_len; int i, pos; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|sslls", &object, redis_ce, &key, &key_len, &pattern, &pattern_len, &get, &get_len, &sort_start, &sort_count, &store, &store_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if(key_len == 0) { RETURN_FALSE; } /* first line, sort. */ cmd_lines[1] = estrdup("$4"); cmd_sizes[1] = 2; cmd_lines[2] = estrdup("SORT"); cmd_sizes[2] = 4; // Prefix our key if we need to key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); /* second line, key */ cmd_sizes[3] = redis_cmd_format(&cmd_lines[3], "$%d", key_len); cmd_lines[4] = emalloc(key_len + 1); memcpy(cmd_lines[4], key, key_len); cmd_lines[4][key_len] = 0; cmd_sizes[4] = key_len; // If we prefixed our key, free it if(key_free) efree(key); cmd_elements = 5; if(pattern && pattern_len) { /* BY */ cmd_lines[cmd_elements] = estrdup("$2"); cmd_sizes[cmd_elements] = 2; cmd_elements++; cmd_lines[cmd_elements] = estrdup("BY"); cmd_sizes[cmd_elements] = 2; cmd_elements++; /* pattern */ cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", pattern_len); cmd_elements++; cmd_lines[cmd_elements] = emalloc(pattern_len + 1); memcpy(cmd_lines[cmd_elements], pattern, pattern_len); cmd_lines[cmd_elements][pattern_len] = 0; cmd_sizes[cmd_elements] = pattern_len; cmd_elements++; } if(sort_start >= 0 && sort_count >= 0) { /* LIMIT */ cmd_lines[cmd_elements] = estrdup("$5"); cmd_sizes[cmd_elements] = 2; cmd_elements++; cmd_lines[cmd_elements] = estrdup("LIMIT"); cmd_sizes[cmd_elements] = 5; cmd_elements++; /* start */ cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", integer_length(sort_start)); cmd_elements++; cmd_sizes[cmd_elements] = spprintf(&cmd_lines[cmd_elements], 0, "%d", (int)sort_start); cmd_elements++; /* count */ cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", integer_length(sort_count)); cmd_elements++; cmd_sizes[cmd_elements] = spprintf(&cmd_lines[cmd_elements], 0, "%d", (int)sort_count); cmd_elements++; } if(get && get_len) { /* GET */ cmd_lines[cmd_elements] = estrdup("$3"); cmd_sizes[cmd_elements] = 2; cmd_elements++; cmd_lines[cmd_elements] = estrdup("GET"); cmd_sizes[cmd_elements] = 3; cmd_elements++; /* pattern */ cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", get_len); cmd_elements++; cmd_lines[cmd_elements] = emalloc(get_len + 1); memcpy(cmd_lines[cmd_elements], get, get_len); cmd_lines[cmd_elements][get_len] = 0; cmd_sizes[cmd_elements] = get_len; cmd_elements++; } /* add ASC or DESC */ sort_len = strlen(sort); cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", sort_len); cmd_elements++; cmd_lines[cmd_elements] = emalloc(sort_len + 1); memcpy(cmd_lines[cmd_elements], sort, sort_len); cmd_lines[cmd_elements][sort_len] = 0; cmd_sizes[cmd_elements] = sort_len; cmd_elements++; if(use_alpha) { /* ALPHA */ cmd_lines[cmd_elements] = estrdup("$5"); cmd_sizes[cmd_elements] = 2; cmd_elements++; cmd_lines[cmd_elements] = estrdup("ALPHA"); cmd_sizes[cmd_elements] = 5; cmd_elements++; } if(store && store_len) { /* STORE */ cmd_lines[cmd_elements] = estrdup("$5"); cmd_sizes[cmd_elements] = 2; cmd_elements++; cmd_lines[cmd_elements] = estrdup("STORE"); cmd_sizes[cmd_elements] = 5; cmd_elements++; /* store key */ cmd_sizes[cmd_elements] = redis_cmd_format(&cmd_lines[cmd_elements], "$%d", store_len); cmd_elements++; cmd_lines[cmd_elements] = emalloc(store_len + 1); memcpy(cmd_lines[cmd_elements], store, store_len); cmd_lines[cmd_elements][store_len] = 0; cmd_sizes[cmd_elements] = store_len; cmd_elements++; } /* first line has the star */ cmd_sizes[0] = spprintf(&cmd_lines[0], 0, "*%d", (cmd_elements-1)/2); /* compute the command size */ cmd_len = 0; for(i = 0; i < cmd_elements; ++i) { cmd_len += cmd_sizes[i] + sizeof(_NL) - 1; /* each line followeb by _NL */ } /* copy all lines into the final command. */ cmd = emalloc(1 + cmd_len); pos = 0; for(i = 0; i < cmd_elements; ++i) { memcpy(cmd + pos, cmd_lines[i], cmd_sizes[i]); pos += cmd_sizes[i]; memcpy(cmd + pos, _NL, sizeof(_NL) - 1); pos += sizeof(_NL) - 1; /* free every line */ efree(cmd_lines[i]); } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } /* {{{ proto array Redis::sortAsc(string key, string pattern, string get, int start, int end, bool getList]) */ PHP_METHOD(Redis, sortAsc) { generic_sort_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ASC", 0); } /* }}} */ /* {{{ proto array Redis::sortAscAlpha(string key, string pattern, string get, int start, int end, bool getList]) */ PHP_METHOD(Redis, sortAscAlpha) { generic_sort_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ASC", 1); } /* }}} */ /* {{{ proto array Redis::sortDesc(string key, string pattern, string get, int start, int end, bool getList]) */ PHP_METHOD(Redis, sortDesc) { generic_sort_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DESC", 0); } /* }}} */ /* {{{ proto array Redis::sortDescAlpha(string key, string pattern, string get, int start, int end, bool getList]) */ PHP_METHOD(Redis, sortDescAlpha) { generic_sort_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "DESC", 1); } /* }}} */ PHPAPI void generic_expire_cmd(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *t; int key_len, cmd_len, key_free, t_len; int i; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &key, &key_len, &t, &t_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* check that we have a number */ for(i = 0; i < t_len; ++i) if(t[i] < '0' || t[i] > '9') RETURN_FALSE; key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "ss", key, key_len, t, t_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* {{{ proto array Redis::setTimeout(string key, int timeout) */ PHP_METHOD(Redis, setTimeout) { generic_expire_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "EXPIRE", sizeof("EXPIRE")-1); } PHP_METHOD(Redis, pexpire) { generic_expire_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PEXPIRE", sizeof("PEXPIRE")-1); } /* }}} */ /* {{{ proto array Redis::expireAt(string key, int timestamp) */ PHP_METHOD(Redis, expireAt) { generic_expire_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "EXPIREAT", sizeof("EXPIREAT")-1); } /* }}} */ /* {{{ proto array Redis::pexpireAt(string key, int timestamp) */ PHP_METHOD(Redis, pexpireAt) { generic_expire_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PEXPIREAT", sizeof("PEXPIREAT")-1); } /* }}} */ /* {{{ proto array Redis::lSet(string key, int index, string value) */ PHP_METHOD(Redis, lSet) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len, key_len, val_len; long index; char *key, *val; int val_free, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oslz", &object, redis_ce, &key, &key_len, &index, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "LSET", "sds", key, key_len, index, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ PHPAPI void generic_empty_cmd_impl(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ResultCallback result_callback) { zval *object; RedisSock *redis_sock; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { result_callback(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(result_callback); } PHPAPI void generic_empty_cmd(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ...) { generic_empty_cmd_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len, redis_boolean_response); } /* {{{ proto string Redis::save() */ PHP_METHOD(Redis, save) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "SAVE", ""); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto string Redis::bgSave() */ PHP_METHOD(Redis, bgSave) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "BGSAVE", ""); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ PHPAPI void generic_empty_long_cmd(INTERNAL_FUNCTION_PARAMETERS, char *cmd, int cmd_len, ...) { zval *object; RedisSock *redis_sock; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* {{{ proto integer Redis::lastSave() */ PHP_METHOD(Redis, lastSave) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "LASTSAVE", ""); generic_empty_long_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto bool Redis::flushDB() */ PHP_METHOD(Redis, flushDB) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "FLUSHDB", ""); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto bool Redis::flushAll() */ PHP_METHOD(Redis, flushAll) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "FLUSHALL", ""); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto int Redis::dbSize() */ PHP_METHOD(Redis, dbSize) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "DBSIZE", ""); generic_empty_long_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto bool Redis::auth(string passwd) */ PHP_METHOD(Redis, auth) { zval *object; RedisSock *redis_sock; char *cmd, *password; int cmd_len, password_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &password, &password_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } cmd_len = redis_cmd_format_static(&cmd, "AUTH", "s", password, password_len); // Free previously stored auth if we have one, and store this password if(redis_sock->auth) efree(redis_sock->auth); redis_sock->auth = estrndup(password, password_len); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ /* {{{ proto long Redis::persist(string key) */ PHP_METHOD(Redis, persist) { zval *object; RedisSock *redis_sock; char *cmd, *key; int cmd_len, key_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "PERSIST", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ PHPAPI void generic_ttl(INTERNAL_FUNCTION_PARAMETERS, char *keyword) { zval *object; RedisSock *redis_sock; char *cmd, *key; int cmd_len, key_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* {{{ proto long Redis::ttl(string key) */ PHP_METHOD(Redis, ttl) { generic_ttl(INTERNAL_FUNCTION_PARAM_PASSTHRU, "TTL"); } /* }}} */ /* {{{ proto long Redis::pttl(string key) */ PHP_METHOD(Redis, pttl) { generic_ttl(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PTTL"); } /* }}} */ /* {{{ proto array Redis::info() */ PHP_METHOD(Redis, info) { zval *object; RedisSock *redis_sock; char *cmd, *opt = NULL; int cmd_len, opt_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|s", &object, redis_ce, &opt, &opt_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Build a standalone INFO command or one with an option if(opt != NULL) { cmd_len = redis_cmd_format_static(&cmd, "INFO", "s", opt, opt_len); } else { cmd_len = redis_cmd_format_static(&cmd, "INFO", ""); } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_info_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_info_response); } /* }}} */ /* {{{ proto string Redis::resetStat() */ PHP_METHOD(Redis, resetStat) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "CONFIG", "s", "RESETSTAT", 9); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto bool Redis::select(long dbNumber) */ PHP_METHOD(Redis, select) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len; long dbNumber; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, redis_ce, &dbNumber) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } redis_sock->dbNumber = dbNumber; cmd_len = redis_cmd_format_static(&cmd, "SELECT", "d", dbNumber); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ /* {{{ proto bool Redis::move(string key, long dbindex) */ PHP_METHOD(Redis, move) { zval *object; RedisSock *redis_sock; char *cmd, *key; int cmd_len, key_len, key_free; long dbNumber; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osl", &object, redis_ce, &key, &key_len, &dbNumber) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "MOVE", "sd", key, key_len, dbNumber); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } /* }}} */ PHPAPI void generic_mset(INTERNAL_FUNCTION_PARAMETERS, char *kw, void (*fun)(INTERNAL_FUNCTION_PARAMETERS, RedisSock *, zval *, void *)) { zval *object; RedisSock *redis_sock; char *cmd = NULL, *p = NULL; int cmd_len = 0, argc = 0, kw_len = strlen(kw); int step = 0; // 0: compute size; 1: copy strings. zval *z_array; HashTable *keytable; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa", &object, redis_ce, &z_array) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if(zend_hash_num_elements(Z_ARRVAL_P(z_array)) == 0) { RETURN_FALSE; } for(step = 0; step < 2; ++step) { if(step == 1) { cmd_len += 1 + integer_length(1 + 2 * argc) + 2; /* star + arg count + NL */ cmd_len += 1 + integer_length(kw_len) + 2; /* dollar + strlen(kw) + NL */ cmd_len += kw_len + 2; /* kw + NL */ p = cmd = emalloc(cmd_len + 1); /* alloc */ p += sprintf(cmd, "*%d" _NL "$%d" _NL "%s" _NL, 1 + 2 * argc, kw_len, kw); /* copy header */ } keytable = Z_ARRVAL_P(z_array); for(zend_hash_internal_pointer_reset(keytable); zend_hash_has_more_elements(keytable) == SUCCESS; zend_hash_move_forward(keytable)) { char *key, *val; unsigned int key_len; int val_len; unsigned long idx; int type; zval **z_value_pp; int val_free, key_free; char buf[32]; type = zend_hash_get_current_key_ex(keytable, &key, &key_len, &idx, 0, NULL); if(zend_hash_get_current_data(keytable, (void**)&z_value_pp) == FAILURE) { continue; /* this should never happen, according to the PHP people. */ } // If the key isn't a string, use the index value returned when grabbing the // key. We typecast to long, because they could actually be negative. if(type != HASH_KEY_IS_STRING) { // Create string representation of our index key_len = snprintf(buf, sizeof(buf), "%ld", (long)idx); key = (char*)buf; } else if(key_len > 0) { // When not an integer key, the length will include the \0 key_len--; } if(step == 0) argc++; /* found a valid arg */ val_free = redis_serialize(redis_sock, *z_value_pp, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, (int*)&key_len TSRMLS_CC); if(step == 0) { /* counting */ cmd_len += 1 + integer_length(key_len) + 2 + key_len + 2 + 1 + integer_length(val_len) + 2 + val_len + 2; } else { p += sprintf(p, "$%d" _NL, key_len); /* key len */ memcpy(p, key, key_len); p += key_len; /* key */ memcpy(p, _NL, 2); p += 2; p += sprintf(p, "$%d" _NL, val_len); /* val len */ memcpy(p, val, val_len); p += val_len; /* val */ memcpy(p, _NL, 2); p += 2; } if(val_free) efree(val); if(key_free) efree(key); } } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { fun(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(fun); } /* {{{ proto bool Redis::mset(array (key => value, ...)) */ PHP_METHOD(Redis, mset) { generic_mset(INTERNAL_FUNCTION_PARAM_PASSTHRU, "MSET", redis_boolean_response); } /* }}} */ /* {{{ proto bool Redis::msetnx(array (key => value, ...)) */ PHP_METHOD(Redis, msetnx) { generic_mset(INTERNAL_FUNCTION_PARAM_PASSTHRU, "MSETNX", redis_1_response); } /* }}} */ PHPAPI void common_rpoplpush(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, char *srckey, int srckey_len, char *dstkey, int dstkey_len, int timeout) { char *cmd; int cmd_len; int srckey_free = redis_key_prefix(redis_sock, &srckey, &srckey_len TSRMLS_CC); int dstkey_free = redis_key_prefix(redis_sock, &dstkey, &dstkey_len TSRMLS_CC); if(timeout < 0) { cmd_len = redis_cmd_format_static(&cmd, "RPOPLPUSH", "ss", srckey, srckey_len, dstkey, dstkey_len); } else { cmd_len = redis_cmd_format_static(&cmd, "BRPOPLPUSH", "ssd", srckey, srckey_len, dstkey, dstkey_len, timeout); } if(srckey_free) efree(srckey); if(dstkey_free) efree(dstkey); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* {{{ proto string Redis::rpoplpush(string srckey, string dstkey) */ PHP_METHOD(Redis, rpoplpush) { zval *object; RedisSock *redis_sock; char *srckey = NULL, *dstkey = NULL; int srckey_len, dstkey_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &srckey, &srckey_len, &dstkey, &dstkey_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } common_rpoplpush(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, srckey, srckey_len, dstkey, dstkey_len, -1); } /* }}} */ /* {{{ proto string Redis::brpoplpush(string srckey, string dstkey) */ PHP_METHOD(Redis, brpoplpush) { zval *object; RedisSock *redis_sock; char *srckey = NULL, *dstkey = NULL; int srckey_len, dstkey_len; long timeout = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ossl", &object, redis_ce, &srckey, &srckey_len, &dstkey, &dstkey_len, &timeout) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } common_rpoplpush(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, srckey, srckey_len, dstkey, dstkey_len, timeout); } /* }}} */ /* {{{ proto long Redis::zAdd(string key, int score, string value) */ PHP_METHOD(Redis, zAdd) { RedisSock *redis_sock; char *cmd; int cmd_len, key_len, val_len; double score; char *key, *val; int val_free, key_free = 0; char *dbl_str; int dbl_len; zval **z_args; int argc = ZEND_NUM_ARGS(), i; /* get redis socket */ if (redis_sock_get(getThis(), &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } z_args = emalloc(argc * sizeof(zval*)); if(zend_get_parameters_array(ht, argc, z_args) == FAILURE) { efree(z_args); RETURN_FALSE; } /* need key, score, value, [score, value...] */ if(argc > 1) { convert_to_string(z_args[0]); // required string } if(argc < 3 || Z_TYPE_P(z_args[0]) != IS_STRING || (argc-1) % 2 != 0) { efree(z_args); RETURN_FALSE; } /* possibly serialize key */ key = Z_STRVAL_P(z_args[0]); key_len = Z_STRLEN_P(z_args[0]); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); /* start building the command */ smart_str buf = {0}; smart_str_appendc(&buf, '*'); smart_str_append_long(&buf, argc + 1); /* +1 for ZADD command */ smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); /* add command name */ smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, 4); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, "ZADD", 4); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); /* add key */ smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, key_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, key, key_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); for(i = 1; i < argc; i +=2) { convert_to_double(z_args[i]); // convert score to double val_free = redis_serialize(redis_sock, z_args[i+1], &val, &val_len TSRMLS_CC); // possibly serialize value. /* add score */ score = Z_DVAL_P(z_args[i]); REDIS_DOUBLE_TO_STRING(dbl_str, dbl_len, score) smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, dbl_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, dbl_str, dbl_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); efree(dbl_str); /* add value */ smart_str_appendc(&buf, '$'); smart_str_append_long(&buf, val_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); smart_str_appendl(&buf, val, val_len); smart_str_appendl(&buf, _NL, sizeof(_NL) - 1); if(val_free) efree(val); } /* end string */ smart_str_0(&buf); cmd = buf.c; cmd_len = buf.len; if(key_free) efree(key); /* cleanup */ efree(z_args); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto array Redis::zRange(string key, int start , int end, bool withscores = FALSE) */ PHP_METHOD(Redis, zRange) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; long withscores = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll|b", &object, redis_ce, &key, &key_len, &start, &end, &withscores) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if(withscores) { cmd_len = redis_cmd_format_static(&cmd, "ZRANGE", "sdds", key, key_len, start, end, "WITHSCORES", 10); } else { cmd_len = redis_cmd_format_static(&cmd, "ZRANGE", "sdd", key, key_len, start, end); } if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); if(withscores) { IF_ATOMIC() { redis_sock_read_multibulk_reply_zipped(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_zipped); } else { IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } } /* }}} */ /* {{{ proto long Redis::zDelete(string key, string member) */ PHP_METHOD(Redis, zDelete) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZREM", sizeof("ZREM") - 1, 2, &redis_sock, 0, 0, 1)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto long Redis::zDeleteRangeByScore(string key, string start, string end) */ PHP_METHOD(Redis, zDeleteRangeByScore) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; char *start, *end; int start_len, end_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osss", &object, redis_ce, &key, &key_len, &start, &start_len, &end, &end_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ZREMRANGEBYSCORE", "sss", key, key_len, start, start_len, end, end_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto long Redis::zDeleteRangeByRank(string key, long start, long end) */ PHP_METHOD(Redis, zDeleteRangeByRank) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll", &object, redis_ce, &key, &key_len, &start, &end) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ZREMRANGEBYRANK", "sdd", key, key_len, (int)start, (int)end); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto array Redis::zReverseRange(string key, int start , int end, bool withscores = FALSE) */ PHP_METHOD(Redis, zReverseRange) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; long start, end; long withscores = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osll|b", &object, redis_ce, &key, &key_len, &start, &end, &withscores) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if(withscores) { cmd_len = redis_cmd_format_static(&cmd, "ZREVRANGE", "sdds", key, key_len, start, end, "WITHSCORES", 10); } else { cmd_len = redis_cmd_format_static(&cmd, "ZREVRANGE", "sdd", key, key_len, start, end); } if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); if(withscores) { IF_ATOMIC() { redis_sock_read_multibulk_reply_zipped(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_zipped); } else { IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } } /* }}} */ PHPAPI void redis_generic_zrange_by_score(INTERNAL_FUNCTION_PARAMETERS, char *keyword) { zval *object, *z_options = NULL, **z_limit_val_pp = NULL, **z_withscores_val_pp = NULL; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; zend_bool withscores = 0; char *start, *end; int start_len, end_len; int has_limit = 0; long limit_low, limit_high; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osss|a", &object, redis_ce, &key, &key_len, &start, &start_len, &end, &end_len, &z_options) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* options */ if (z_options && Z_TYPE_P(z_options) == IS_ARRAY) { /* add scores */ zend_hash_find(Z_ARRVAL_P(z_options), "withscores", sizeof("withscores"), (void**)&z_withscores_val_pp); withscores = (z_withscores_val_pp ? Z_BVAL_PP(z_withscores_val_pp) : 0); /* limit offset, count: z_limit_val_pp points to an array($longFrom, $longCount) */ if(zend_hash_find(Z_ARRVAL_P(z_options), "limit", sizeof("limit"), (void**)&z_limit_val_pp)== SUCCESS) {; if(zend_hash_num_elements(Z_ARRVAL_PP(z_limit_val_pp)) == 2) { zval **z_offset_pp, **z_count_pp; // get the two values from the table, check that they are indeed of LONG type if(SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(z_limit_val_pp), 0, (void**)&z_offset_pp) && SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(z_limit_val_pp), 1, (void**)&z_count_pp) && Z_TYPE_PP(z_offset_pp) == IS_LONG && Z_TYPE_PP(z_count_pp) == IS_LONG) { has_limit = 1; limit_low = Z_LVAL_PP(z_offset_pp); limit_high = Z_LVAL_PP(z_count_pp); } } } } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); if(withscores) { if(has_limit) { cmd_len = redis_cmd_format_static(&cmd, keyword, "ssssdds", key, key_len, start, start_len, end, end_len, "LIMIT", 5, limit_low, limit_high, "WITHSCORES", 10); } else { cmd_len = redis_cmd_format_static(&cmd, keyword, "ssss", key, key_len, start, start_len, end, end_len, "WITHSCORES", 10); } } else { if(has_limit) { cmd_len = redis_cmd_format_static(&cmd, keyword, "ssssdd", key, key_len, start, start_len, end, end_len, "LIMIT", 5, limit_low, limit_high); } else { cmd_len = redis_cmd_format_static(&cmd, keyword, "sss", key, key_len, start, start_len, end, end_len); } } if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); if(withscores) { /* with scores! we have to transform the return array. * return_value currently holds this: [elt0, val0, elt1, val1 ... ] * we want [elt0 => val0, elt1 => val1], etc. */ IF_ATOMIC() { if(redis_sock_read_multibulk_reply_zipped(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_zipped); } else { IF_ATOMIC() { if(redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } } /* {{{ proto array Redis::zRangeByScore(string key, string start , string end [,array options = NULL]) */ PHP_METHOD(Redis, zRangeByScore) { redis_generic_zrange_by_score(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZRANGEBYSCORE"); } /* }}} */ /* {{{ proto array Redis::zRevRangeByScore(string key, string start , string end [,array options = NULL]) */ PHP_METHOD(Redis, zRevRangeByScore) { redis_generic_zrange_by_score(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZREVRANGEBYSCORE"); } /* {{{ proto array Redis::zCount(string key, string start , string end) */ PHP_METHOD(Redis, zCount) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; char *start, *end; int start_len, end_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osss", &object, redis_ce, &key, &key_len, &start, &start_len, &end, &end_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ZCOUNT", "sss", key, key_len, start, start_len, end, end_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto long Redis::zCard(string key) */ PHP_METHOD(Redis, zCard) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ZCARD", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ /* {{{ proto double Redis::zScore(string key, mixed member) */ PHP_METHOD(Redis, zScore) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; int val_free, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "ZSCORE", "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_bulk_double_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_bulk_double_response); } /* }}} */ PHPAPI void generic_rank_method(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd; int key_len, val_len, cmd_len; int val_free, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osz", &object, redis_ce, &key, &key_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "ss", key, key_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* {{{ proto long Redis::zRank(string key, string member) */ PHP_METHOD(Redis, zRank) { generic_rank_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZRANK", 5); } /* }}} */ /* {{{ proto long Redis::zRevRank(string key, string member) */ PHP_METHOD(Redis, zRevRank) { generic_rank_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZREVRANK", 8); } /* }}} */ PHPAPI void generic_incrby_method(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *val; int key_len, val_len, cmd_len; double add; int val_free, key_free; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osdz", &object, redis_ce, &key, &key_len, &add, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "sfs", key, key_len, add, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_bulk_double_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_bulk_double_response); } /* {{{ proto double Redis::zIncrBy(string key, double value, mixed member) */ PHP_METHOD(Redis, zIncrBy) { generic_incrby_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZINCRBY", sizeof("ZINCRBY")-1); } /* }}} */ PHPAPI void generic_z_command(INTERNAL_FUNCTION_PARAMETERS, char *command, int command_len) { zval *object, *z_keys, *z_weights = NULL, **z_data; HashTable *ht_keys, *ht_weights = NULL; RedisSock *redis_sock; smart_str cmd = {0}; HashPosition ptr; char *store_key, *agg_op = NULL; int cmd_arg_count = 2, store_key_len, agg_op_len = 0, keys_count; // Grab our parameters if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osa|a!s", &object, redis_ce, &store_key, &store_key_len, &z_keys, &z_weights, &agg_op, &agg_op_len) == FAILURE) { RETURN_FALSE; } // We'll need our socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Grab our keys argument as an array ht_keys = Z_ARRVAL_P(z_keys); // Nothing to do if there aren't any keys if((keys_count = zend_hash_num_elements(ht_keys)) == 0) { RETURN_FALSE; } else { // Increment our overall argument count cmd_arg_count += keys_count; } // Grab and validate our weights array if(z_weights != NULL) { ht_weights = Z_ARRVAL_P(z_weights); // This command is invalid if the weights array isn't the same size // as our keys array. if(zend_hash_num_elements(ht_weights) != keys_count) { RETURN_FALSE; } // Increment our overall argument count by the number of keys // plus one, for the "WEIGHTS" argument itself cmd_arg_count += keys_count + 1; } // AGGREGATE option if(agg_op_len != 0) { // Verify our aggregation option if(strncasecmp(agg_op, "SUM", sizeof("SUM")) && strncasecmp(agg_op, "MIN", sizeof("MIN")) && strncasecmp(agg_op, "MAX", sizeof("MAX"))) { RETURN_FALSE; } // Two more arguments: "AGGREGATE" and agg_op cmd_arg_count += 2; } // Command header redis_cmd_init_sstr(&cmd, cmd_arg_count, command, command_len); // Prefix our key if necessary and add the output key int key_free = redis_key_prefix(redis_sock, &store_key, &store_key_len TSRMLS_CC); redis_cmd_append_sstr(&cmd, store_key, store_key_len); if(key_free) efree(store_key); // Number of input keys argument redis_cmd_append_sstr_int(&cmd, keys_count); // Process input keys for(zend_hash_internal_pointer_reset_ex(ht_keys, &ptr); zend_hash_get_current_data_ex(ht_keys, (void**)&z_data, &ptr)==SUCCESS; zend_hash_move_forward_ex(ht_keys, &ptr)) { char *key; int key_free, key_len; zval *z_tmp = NULL; if(Z_TYPE_PP(z_data) == IS_STRING) { key = Z_STRVAL_PP(z_data); key_len = Z_STRLEN_PP(z_data); } else { MAKE_STD_ZVAL(z_tmp); *z_tmp = **z_data; convert_to_string(z_tmp); key = Z_STRVAL_P(z_tmp); key_len = Z_STRLEN_P(z_tmp); } // Apply key prefix if necessary key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); // Append this input set redis_cmd_append_sstr(&cmd, key, key_len); // Free our key if it was prefixed if(key_free) efree(key); // Free our temporary z_val if it was converted if(z_tmp) { zval_dtor(z_tmp); efree(z_tmp); z_tmp = NULL; } } // Weights if(ht_weights != NULL) { // Append "WEIGHTS" argument redis_cmd_append_sstr(&cmd, "WEIGHTS", sizeof("WEIGHTS") - 1); // Process weights for(zend_hash_internal_pointer_reset_ex(ht_weights, &ptr); zend_hash_get_current_data_ex(ht_weights, (void**)&z_data, &ptr)==SUCCESS; zend_hash_move_forward_ex(ht_weights, &ptr)) { // Ignore non numeric arguments, unless they're special Redis numbers if (Z_TYPE_PP(z_data) != IS_LONG && Z_TYPE_PP(z_data) != IS_DOUBLE && strncasecmp(Z_STRVAL_PP(z_data), "inf", sizeof("inf")) != 0 && strncasecmp(Z_STRVAL_PP(z_data), "-inf", sizeof("-inf")) != 0 && strncasecmp(Z_STRVAL_PP(z_data), "+inf", sizeof("+inf")) != 0) { // We should abort if we have an invalid weight, rather than pass // a different number of weights than the user is expecting efree(cmd.c); RETURN_FALSE; } // Append the weight based on the input type switch(Z_TYPE_PP(z_data)) { case IS_LONG: redis_cmd_append_sstr_long(&cmd, Z_LVAL_PP(z_data)); break; case IS_DOUBLE: redis_cmd_append_sstr_dbl(&cmd, Z_DVAL_PP(z_data)); break; case IS_STRING: redis_cmd_append_sstr(&cmd, Z_STRVAL_PP(z_data), Z_STRLEN_PP(z_data)); break; } } } // Aggregation options, if we have them if(agg_op_len != 0) { redis_cmd_append_sstr(&cmd, "AGGREGATE", sizeof("AGGREGATE") - 1); redis_cmd_append_sstr(&cmd, agg_op, agg_op_len); } // Kick off our request REDIS_PROCESS_REQUEST(redis_sock, cmd.c, cmd.len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* zInter */ PHP_METHOD(Redis, zInter) { generic_z_command(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZINTERSTORE", 11); } /* zUnion */ PHP_METHOD(Redis, zUnion) { generic_z_command(INTERNAL_FUNCTION_PARAM_PASSTHRU, "ZUNIONSTORE", 11); } /* hashes */ PHPAPI void generic_hset(INTERNAL_FUNCTION_PARAMETERS, char *kw, void (*fun)(INTERNAL_FUNCTION_PARAMETERS, RedisSock *, zval *, void *)) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *member, *val; int key_len, member_len, cmd_len, val_len; int val_free, key_free = 0; zval *z_value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ossz", &object, redis_ce, &key, &key_len, &member, &member_len, &z_value) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } val_free = redis_serialize(redis_sock, z_value, &val, &val_len TSRMLS_CC); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, kw, "sss", key, key_len, member, member_len, val, val_len); if(val_free) efree(val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { fun(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(fun); } /* hSet */ PHP_METHOD(Redis, hSet) { generic_hset(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HSET", redis_long_response); } /* }}} */ /* hSetNx */ PHP_METHOD(Redis, hSetNx) { generic_hset(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HSETNX", redis_1_response); } /* }}} */ /* hGet */ PHP_METHOD(Redis, hGet) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *member; int key_len, member_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &key, &key_len, &member, &member_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "HGET", "ss", key, key_len, member, member_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } /* }}} */ /* hLen */ PHP_METHOD(Redis, hLen) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "HLEN", "s", key, key_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* }}} */ PHPAPI RedisSock* generic_hash_command_2(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len, char **out_cmd, int *out_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *member; int key_len, cmd_len, member_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &key, &key_len, &member, &member_len) == FAILURE) { ZVAL_BOOL(return_value, 0); return NULL; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { ZVAL_BOOL(return_value, 0); return NULL; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "ss", key, key_len, member, member_len); if(key_free) efree(key); *out_cmd = cmd; *out_len = cmd_len; return redis_sock; } /* hDel */ PHP_METHOD(Redis, hDel) { RedisSock *redis_sock; if(FAILURE == generic_multiple_args_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HDEL", sizeof("HDEL") - 1, 2, &redis_sock, 0, 0, 0)) return; IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } /* hExists */ PHP_METHOD(Redis, hExists) { char *cmd; int cmd_len; RedisSock *redis_sock = generic_hash_command_2(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HEXISTS", 7, &cmd, &cmd_len); if(!redis_sock) RETURN_FALSE; REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_1_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_1_response); } PHPAPI RedisSock* generic_hash_command_1(INTERNAL_FUNCTION_PARAMETERS, char *keyword, int keyword_len) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &key, &key_len) == FAILURE) { ZVAL_BOOL(return_value, 0); return NULL; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { ZVAL_BOOL(return_value, 0); return NULL; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, keyword, "s", key, key_len); if(key_free) efree(key); /* call REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len) without breaking the return value */ IF_MULTI_OR_ATOMIC() { if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return NULL; } efree(cmd); } IF_PIPELINE() { PIPELINE_ENQUEUE_COMMAND(cmd, cmd_len); efree(cmd); } return redis_sock; } /* hKeys */ PHP_METHOD(Redis, hKeys) { RedisSock *redis_sock = generic_hash_command_1(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HKEYS", sizeof("HKEYS")-1); if(!redis_sock) RETURN_FALSE; IF_ATOMIC() { if (redis_sock_read_multibulk_reply_raw(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_raw); } /* hVals */ PHP_METHOD(Redis, hVals) { RedisSock *redis_sock = generic_hash_command_1(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HVALS", sizeof("HVALS")-1); if(!redis_sock) RETURN_FALSE; IF_ATOMIC() { if (redis_sock_read_multibulk_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply); } PHP_METHOD(Redis, hGetAll) { RedisSock *redis_sock = generic_hash_command_1(INTERNAL_FUNCTION_PARAM_PASSTHRU, "HGETALL", sizeof("HGETALL")-1); if(!redis_sock) RETURN_FALSE; IF_ATOMIC() { if (redis_sock_read_multibulk_reply_zipped_strings(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_zipped_strings); } PHPAPI void array_zip_values_and_scores(RedisSock *redis_sock, zval *z_tab, int use_atof TSRMLS_DC) { zval *z_ret; HashTable *keytable; MAKE_STD_ZVAL(z_ret); array_init(z_ret); keytable = Z_ARRVAL_P(z_tab); for(zend_hash_internal_pointer_reset(keytable); zend_hash_has_more_elements(keytable) == SUCCESS; zend_hash_move_forward(keytable)) { char *tablekey, *hkey, *hval; unsigned int tablekey_len; int hkey_len; unsigned long idx; zval **z_key_pp, **z_value_pp; zend_hash_get_current_key_ex(keytable, &tablekey, &tablekey_len, &idx, 0, NULL); if(zend_hash_get_current_data(keytable, (void**)&z_key_pp) == FAILURE) { continue; /* this should never happen, according to the PHP people. */ } /* get current value, a key */ convert_to_string(*z_key_pp); hkey = Z_STRVAL_PP(z_key_pp); hkey_len = Z_STRLEN_PP(z_key_pp); /* move forward */ zend_hash_move_forward(keytable); /* fetch again */ zend_hash_get_current_key_ex(keytable, &tablekey, &tablekey_len, &idx, 0, NULL); if(zend_hash_get_current_data(keytable, (void**)&z_value_pp) == FAILURE) { continue; /* this should never happen, according to the PHP people. */ } /* get current value, a hash value now. */ hval = Z_STRVAL_PP(z_value_pp); if(use_atof) { /* zipping a score */ add_assoc_double_ex(z_ret, hkey, 1+hkey_len, atof(hval)); } else { /* add raw copy */ zval *z = NULL; MAKE_STD_ZVAL(z); *z = **z_value_pp; zval_copy_ctor(z); add_assoc_zval_ex(z_ret, hkey, 1+hkey_len, z); } } /* replace */ zval_dtor(z_tab); *z_tab = *z_ret; zval_copy_ctor(z_tab); zval_dtor(z_ret); efree(z_ret); } PHP_METHOD(Redis, hIncrByFloat) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *member; int key_len, member_len, cmd_len, key_free; double val; // Validate we have the right number of arguments if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ossd", &object, redis_ce, &key, &key_len, &member, &member_len, &val) == FAILURE) { RETURN_FALSE; } // Grab our socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "HINCRBYFLOAT", "ssf", key, key_len, member, member_len, val); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_bulk_double_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_bulk_double_response); } PHP_METHOD(Redis, hIncrBy) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *member, *val; int key_len, member_len, cmd_len, val_len, key_free; int i; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osss", &object, redis_ce, &key, &key_len, &member, &member_len, &val, &val_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } /* check for validity of numeric string */ i = 0; if(val_len && val[0] == '-') { /* negative case */ i++; } for(; i < val_len; ++i) { if(val[i] < '0' || val[i] > '9') { RETURN_FALSE; } } /* HINCRBY key member amount */ key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "HINCRBY", "sss", key, key_len, member, member_len, val, val_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHP_METHOD(Redis, hMget) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd; int key_len, cmd_len, key_free; zval *z_array; zval **z_keys; int nb_fields, i; char *old_cmd = NULL; zval **data; HashTable *arr_hash; HashPosition pointer; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osa", &object, redis_ce, &key, &key_len, &z_array) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } nb_fields = zend_hash_num_elements(Z_ARRVAL_P(z_array)); if( nb_fields == 0) { RETURN_FALSE; } z_keys = ecalloc(nb_fields, sizeof(zval *)); key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format(&cmd, "*%d" _NL "$5" _NL "HMGET" _NL "$%d" _NL /* key */ "%s" _NL , nb_fields + 2 , key_len, key, key_len); if(key_free) efree(key); arr_hash = Z_ARRVAL_P(z_array); for (i = 0, zend_hash_internal_pointer_reset_ex(arr_hash, &pointer); zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS; zend_hash_move_forward_ex(arr_hash, &pointer)) { if (Z_TYPE_PP(data) == IS_LONG || Z_TYPE_PP(data) == IS_STRING) { old_cmd = cmd; if (Z_TYPE_PP(data) == IS_LONG) { cmd_len = redis_cmd_format(&cmd, "%s" "$%d" _NL "%d" _NL , cmd, cmd_len , integer_length(Z_LVAL_PP(data)), (int)Z_LVAL_PP(data)); } else if (Z_TYPE_PP(data) == IS_STRING) { cmd_len = redis_cmd_format(&cmd, "%s" "$%d" _NL "%s" _NL , cmd, cmd_len , Z_STRLEN_PP(data), Z_STRVAL_PP(data), Z_STRLEN_PP(data)); } efree(old_cmd); /* save context */ MAKE_STD_ZVAL(z_keys[i]); *z_keys[i] = **data; zval_copy_ctor(z_keys[i]); convert_to_string(z_keys[i]); i++; } } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_sock_read_multibulk_reply_assoc(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, z_keys); } REDIS_PROCESS_RESPONSE_CLOSURE(redis_sock_read_multibulk_reply_assoc, z_keys); } PHP_METHOD(Redis, hMset) { zval *object; RedisSock *redis_sock; char *key = NULL, *cmd, *old_cmd = NULL; int key_len, cmd_len, key_free, i, element_count = 2; zval *z_hash; HashTable *ht_hash; smart_str set_cmds = {0}; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Osa", &object, redis_ce, &key, &key_len, &z_hash) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } ht_hash = Z_ARRVAL_P(z_hash); if (zend_hash_num_elements(ht_hash) == 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format(&cmd, "$5" _NL "HMSET" _NL "$%d" _NL "%s" _NL , key_len, key, key_len); if(key_free) efree(key); /* looping on each item of the array */ for(i =0, zend_hash_internal_pointer_reset(ht_hash); zend_hash_has_more_elements(ht_hash) == SUCCESS; i++, zend_hash_move_forward(ht_hash)) { char *hkey, hkey_str[40]; unsigned int hkey_len; unsigned long idx; int type; zval **z_value_p; char *hval; int hval_len, hval_free; type = zend_hash_get_current_key_ex(ht_hash, &hkey, &hkey_len, &idx, 0, NULL); if(zend_hash_get_current_data(ht_hash, (void**)&z_value_p) == FAILURE) { continue; /* this should never happen */ } if(type != HASH_KEY_IS_STRING) { /* convert to string */ hkey_len = 1 + sprintf(hkey_str, "%ld", idx); hkey = (char*)hkey_str; } element_count += 2; /* key is set. */ hval_free = redis_serialize(redis_sock, *z_value_p, &hval, &hval_len TSRMLS_CC); // Append our member and value in place redis_cmd_append_sstr(&set_cmds, hkey, hkey_len - 1); redis_cmd_append_sstr(&set_cmds, hval, hval_len); if(hval_free) efree(hval); } // Now construct the entire command old_cmd = cmd; cmd_len = redis_cmd_format(&cmd, "*%d" _NL "%s%s", element_count, cmd, cmd_len, set_cmds.c, set_cmds.len); efree(old_cmd); // Free the HMSET bits efree(set_cmds.c); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } PHPAPI int redis_response_enqueued(RedisSock *redis_sock TSRMLS_DC) { char *response; int response_len, ret = 0; if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { return 0; } if(strncmp(response, "+QUEUED", 7) == 0) { ret = 1; } efree(response); return ret; } /* flag : get, set {ATOMIC, MULTI, PIPELINE} */ PHP_METHOD(Redis, multi) { RedisSock *redis_sock; char *cmd; int response_len, cmd_len; char * response; zval *object; long multi_value = MULTI; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &object, redis_ce, &multi_value) == FAILURE) { RETURN_FALSE; } /* if the flag is activated, send the command, the reply will be "QUEUED" or -ERR */ if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if(multi_value == MULTI || multi_value == PIPELINE) { redis_sock->mode = multi_value; } else { RETURN_FALSE; } redis_sock->current = NULL; IF_MULTI() { cmd_len = redis_cmd_format_static(&cmd, "MULTI", ""); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); RETURN_FALSE; } efree(cmd); if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { RETURN_FALSE; } if(strncmp(response, "+OK", 3) == 0) { efree(response); RETURN_ZVAL(getThis(), 1, 0); } efree(response); RETURN_FALSE; } IF_PIPELINE() { free_reply_callbacks(getThis(), redis_sock); RETURN_ZVAL(getThis(), 1, 0); } } /* discard */ PHP_METHOD(Redis, discard) { RedisSock *redis_sock; zval *object; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } redis_sock->mode = ATOMIC; redis_send_discard(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock); } PHPAPI int redis_sock_read_multibulk_pipeline_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock) { zval *z_tab; MAKE_STD_ZVAL(z_tab); array_init(z_tab); redis_sock_read_multibulk_multi_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, 0); *return_value = *z_tab; efree(z_tab); /* free allocated function/request memory */ free_reply_callbacks(getThis(), redis_sock); return 0; } /* redis_sock_read_multibulk_multi_reply */ PHPAPI int redis_sock_read_multibulk_multi_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock) { char inbuf[1024]; int numElems; zval *z_tab; redis_check_eof(redis_sock TSRMLS_CC); php_stream_gets(redis_sock->stream, inbuf, 1024); if(inbuf[0] != '*') { return -1; } /* number of responses */ numElems = atoi(inbuf+1); if(numElems < 0) { return -1; } zval_dtor(return_value); MAKE_STD_ZVAL(z_tab); array_init(z_tab); redis_sock_read_multibulk_multi_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, numElems); *return_value = *z_tab; efree(z_tab); return 0; } void free_reply_callbacks(zval *z_this, RedisSock *redis_sock) { fold_item *fi; fold_item *head = redis_sock->head; request_item *ri; for(fi = head; fi; ) { fold_item *fi_next = fi->next; free(fi); fi = fi_next; } redis_sock->head = NULL; redis_sock->current = NULL; for(ri = redis_sock->pipeline_head; ri; ) { struct request_item *ri_next = ri->next; free(ri->request_str); free(ri); ri = ri_next; } redis_sock->pipeline_head = NULL; redis_sock->pipeline_current = NULL; } /* exec */ PHP_METHOD(Redis, exec) { RedisSock *redis_sock; char *cmd; int cmd_len; zval *object; struct request_item *ri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } IF_MULTI() { cmd_len = redis_cmd_format_static(&cmd, "EXEC", ""); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); RETURN_FALSE; } efree(cmd); if (redis_sock_read_multibulk_multi_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock) < 0) { zval_dtor(return_value); free_reply_callbacks(object, redis_sock); redis_sock->mode = ATOMIC; redis_sock->watching = 0; RETURN_FALSE; } free_reply_callbacks(object, redis_sock); redis_sock->mode = ATOMIC; redis_sock->watching = 0; } IF_PIPELINE() { char *request = NULL; int total = 0; int offset = 0; /* compute the total request size */ for(ri = redis_sock->pipeline_head; ri; ri = ri->next) { total += ri->request_size; } if(total) { request = malloc(total); } /* concatenate individual elements one by one in the target buffer */ for(ri = redis_sock->pipeline_head; ri; ri = ri->next) { memcpy(request + offset, ri->request_str, ri->request_size); offset += ri->request_size; } if(request != NULL) { if (redis_sock_write(redis_sock, request, total TSRMLS_CC) < 0) { free(request); free_reply_callbacks(object, redis_sock); redis_sock->mode = ATOMIC; RETURN_FALSE; } free(request); } else { redis_sock->mode = ATOMIC; free_reply_callbacks(object, redis_sock); array_init(return_value); /* empty array when no command was run. */ return; } if (redis_sock_read_multibulk_pipeline_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock) < 0) { redis_sock->mode = ATOMIC; free_reply_callbacks(object, redis_sock); RETURN_FALSE; } redis_sock->mode = ATOMIC; free_reply_callbacks(object, redis_sock); } } PHPAPI void fold_this_item(INTERNAL_FUNCTION_PARAMETERS, fold_item *item, RedisSock *redis_sock, zval *z_tab) { item->fun(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab, item->ctx TSRMLS_CC); } PHPAPI int redis_sock_read_multibulk_multi_reply_loop(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, int numElems) { fold_item *head = redis_sock->head; fold_item *current = redis_sock->current; for(current = head; current; current = current->next) { fold_this_item(INTERNAL_FUNCTION_PARAM_PASSTHRU, current, redis_sock, z_tab); } redis_sock->current = current; return 0; } PHP_METHOD(Redis, pipeline) { RedisSock *redis_sock; zval *object; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } /* if the flag is activated, send the command, the reply will be "QUEUED" or -ERR */ if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } redis_sock->mode = PIPELINE; /* NB : we keep the function fold, to detect the last function. We need the response format of the n - 1 command. So, we can delete when n > 2, the { 1 .. n - 2} commands */ free_reply_callbacks(getThis(), redis_sock); RETURN_ZVAL(getThis(), 1, 0); } /* publish channel message @return the number of subscribers */ PHP_METHOD(Redis, publish) { zval *object; RedisSock *redis_sock; char *cmd, *key, *val; int cmd_len, key_len, val_len, key_free; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &key, &key_len, &val, &val_len) == FAILURE) { RETURN_NULL(); } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = redis_cmd_format_static(&cmd, "PUBLISH", "ss", key, key_len, val, val_len); if(key_free) efree(key); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } PHPAPI void generic_subscribe_cmd(INTERNAL_FUNCTION_PARAMETERS, char *sub_cmd) { zval *object, *array, **data; HashTable *arr_hash; HashPosition pointer; RedisSock *redis_sock; char *cmd = "", *old_cmd = NULL, *key; int cmd_len, array_count, key_len, key_free; zval *z_tab, **tmp; char *type_response; // Function call information zend_fcall_info z_callback; zend_fcall_info_cache z_callback_cache; zval *z_ret, **z_args[4]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oaf", &object, redis_ce, &array, &z_callback, &z_callback_cache) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } arr_hash = Z_ARRVAL_P(array); array_count = zend_hash_num_elements(arr_hash); if (array_count == 0) { RETURN_FALSE; } for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer); zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS; zend_hash_move_forward_ex(arr_hash, &pointer)) { if (Z_TYPE_PP(data) == IS_STRING) { char *old_cmd = NULL; if(*cmd) { old_cmd = cmd; } // Grab our key and len key = Z_STRVAL_PP(data); key_len = Z_STRLEN_PP(data); // Prefix our key if neccisary key_free = redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); cmd_len = spprintf(&cmd, 0, "%s %s", cmd, key); if(old_cmd) { efree(old_cmd); } // Free our key if it was prefixed if(key_free) { efree(key); } } } old_cmd = cmd; cmd_len = spprintf(&cmd, 0, "%s %s\r\n", sub_cmd, cmd); efree(old_cmd); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); RETURN_FALSE; } efree(cmd); /* read the status of the execution of the command `subscribe` */ z_tab = redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock); if(z_tab == NULL) { RETURN_FALSE; } if (zend_hash_index_find(Z_ARRVAL_P(z_tab), 0, (void**)&tmp) == SUCCESS) { type_response = Z_STRVAL_PP(tmp); if(strcmp(type_response, sub_cmd) != 0) { efree(tmp); efree(z_tab); RETURN_FALSE; } } else { efree(z_tab); RETURN_FALSE; } efree(z_tab); // Set a pointer to our return value and to our arguments. z_callback.retval_ptr_ptr = &z_ret; z_callback.params = z_args; z_callback.no_separation = 0; /* Multibulk Response, format : {message type, originating channel, message payload} */ while(1) { /* call the callback with this z_tab in argument */ zval **type, **channel, **pattern, **data; z_tab = redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock); int is_pmsg, tab_idx = 1; if(z_tab == NULL || Z_TYPE_P(z_tab) != IS_ARRAY) { //ERROR break; } if (zend_hash_index_find(Z_ARRVAL_P(z_tab), 0, (void**)&type) == FAILURE || Z_TYPE_PP(type) != IS_STRING) { break; } // Make sure we have a message or pmessage if(!strncmp(Z_STRVAL_PP(type), "message", 7) || !strncmp(Z_STRVAL_PP(type), "pmessage", 8)) { // Is this a pmessage is_pmsg = *Z_STRVAL_PP(type) == 'p'; } else { continue; // It's not a message or pmessage } // If this is a pmessage, we'll want to extract the pattern first if(is_pmsg) { // Extract pattern if(zend_hash_index_find(Z_ARRVAL_P(z_tab), tab_idx++, (void**)&pattern) == FAILURE) { break; } } // Extract channel and data if (zend_hash_index_find(Z_ARRVAL_P(z_tab), tab_idx++, (void**)&channel) == FAILURE) { break; } if (zend_hash_index_find(Z_ARRVAL_P(z_tab), tab_idx++, (void**)&data) == FAILURE) { break; } // Always pass the Redis object through z_args[0] = &getThis(); // Set up our callback args depending on the message type if(is_pmsg) { z_args[1] = pattern; z_args[2] = channel; z_args[3] = data; } else { z_args[1] = channel; z_args[2] = data; } // Set our argument information z_callback.param_count = tab_idx; // Break if we can't call the function if(zend_call_function(&z_callback, &z_callback_cache TSRMLS_CC) != SUCCESS) { break; } // If we have a return value, free it. Note, we could use the return value to break the subscribe loop if(z_ret) zval_ptr_dtor(&z_ret); /* TODO: provide a way to break out of the loop. */ zval_dtor(z_tab); efree(z_tab); } } /* {{{ proto void Redis::psubscribe(Array(pattern1, pattern2, ... patternN)) */ PHP_METHOD(Redis, psubscribe) { generic_subscribe_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "psubscribe"); } /* {{{ proto void Redis::subscribe(Array(channel1, channel2, ... channelN)) */ PHP_METHOD(Redis, subscribe) { generic_subscribe_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "subscribe"); } /** * [p]unsubscribe channel_0 channel_1 ... channel_n * [p]unsubscribe(array(channel_0, channel_1, ..., channel_n)) * response format : * array( * channel_0 => TRUE|FALSE, * channel_1 => TRUE|FALSE, * ... * channel_n => TRUE|FALSE * ); **/ PHPAPI void generic_unsubscribe_cmd(INTERNAL_FUNCTION_PARAMETERS, char *unsub_cmd) { zval *object, *array, **data; HashTable *arr_hash; HashPosition pointer; RedisSock *redis_sock; char *cmd = "", *old_cmd = NULL; int cmd_len, array_count; int i; zval *z_tab, **z_channel; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oa", &object, redis_ce, &array) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } arr_hash = Z_ARRVAL_P(array); array_count = zend_hash_num_elements(arr_hash); if (array_count == 0) { RETURN_FALSE; } for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer); zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS; zend_hash_move_forward_ex(arr_hash, &pointer)) { if (Z_TYPE_PP(data) == IS_STRING) { char *old_cmd = NULL; if(*cmd) { old_cmd = cmd; } cmd_len = spprintf(&cmd, 0, "%s %s", cmd, Z_STRVAL_PP(data)); if(old_cmd) { efree(old_cmd); } } } old_cmd = cmd; cmd_len = spprintf(&cmd, 0, "%s %s\r\n", unsub_cmd, cmd); efree(old_cmd); if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); RETURN_FALSE; } efree(cmd); i = 1; array_init(return_value); while( i <= array_count) { z_tab = redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock); if(Z_TYPE_P(z_tab) == IS_ARRAY) { if (zend_hash_index_find(Z_ARRVAL_P(z_tab), 1, (void**)&z_channel) == FAILURE) { RETURN_FALSE; } add_assoc_bool(return_value, Z_STRVAL_PP(z_channel), 1); } else { //error efree(z_tab); RETURN_FALSE; } efree(z_tab); i ++; } } PHP_METHOD(Redis, unsubscribe) { generic_unsubscribe_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "UNSUBSCRIBE"); } PHP_METHOD(Redis, punsubscribe) { generic_unsubscribe_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, "PUNSUBSCRIBE"); } /* {{{ proto string Redis::bgrewriteaof() */ PHP_METHOD(Redis, bgrewriteaof) { char *cmd; int cmd_len = redis_cmd_format_static(&cmd, "BGREWRITEAOF", ""); generic_empty_cmd(INTERNAL_FUNCTION_PARAM_PASSTHRU, cmd, cmd_len); } /* }}} */ /* {{{ proto string Redis::slaveof([host, port]) */ PHP_METHOD(Redis, slaveof) { zval *object; RedisSock *redis_sock; char *cmd = "", *host = NULL; int cmd_len, host_len; long port = 6379; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|sl", &object, redis_ce, &host, &host_len, &port) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if(host && host_len) { cmd_len = redis_cmd_format_static(&cmd, "SLAVEOF", "sd", host, host_len, (int)port); } else { cmd_len = redis_cmd_format_static(&cmd, "SLAVEOF", "ss", "NO", 2, "ONE", 3); } REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } /* }}} */ /* {{{ proto string Redis::object(key) */ PHP_METHOD(Redis, object) { zval *object; RedisSock *redis_sock; char *cmd = "", *info = NULL, *key = NULL; int cmd_len, info_len, key_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &object, redis_ce, &info, &info_len, &key, &key_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } cmd_len = redis_cmd_format_static(&cmd, "OBJECT", "ss", info, info_len, key, key_len); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); if(info_len == 8 && (strncasecmp(info, "refcount", 8) == 0 || strncasecmp(info, "idletime", 8) == 0)) { IF_ATOMIC() { redis_long_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_long_response); } else if(info_len == 8 && strncasecmp(info, "encoding", 8) == 0) { IF_ATOMIC() { redis_string_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_string_response); } else { /* fail */ IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } } /* }}} */ /* {{{ proto string Redis::getOption($option) */ PHP_METHOD(Redis, getOption) { RedisSock *redis_sock; zval *object; long option; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, redis_ce, &option) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } switch(option) { case REDIS_OPT_SERIALIZER: RETURN_LONG(redis_sock->serializer); case REDIS_OPT_PREFIX: if(redis_sock->prefix) { RETURN_STRINGL(redis_sock->prefix, redis_sock->prefix_len, 1); } RETURN_NULL(); case REDIS_OPT_READ_TIMEOUT: RETURN_DOUBLE(redis_sock->read_timeout); default: RETURN_FALSE; } } /* }}} */ /* {{{ proto string Redis::setOption(string $option, mixed $value) */ PHP_METHOD(Redis, setOption) { RedisSock *redis_sock; zval *object; long option, val_long; char *val_str; int val_len; struct timeval read_tv; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ols", &object, redis_ce, &option, &val_str, &val_len) == FAILURE) { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } switch(option) { case REDIS_OPT_SERIALIZER: val_long = atol(val_str); if(val_long == REDIS_SERIALIZER_NONE #ifdef HAVE_REDIS_IGBINARY || val_long == REDIS_SERIALIZER_IGBINARY #endif || val_long == REDIS_SERIALIZER_PHP) { redis_sock->serializer = val_long; RETURN_TRUE; } else { RETURN_FALSE; } break; case REDIS_OPT_PREFIX: if(redis_sock->prefix) { efree(redis_sock->prefix); } if(val_len == 0) { redis_sock->prefix = NULL; redis_sock->prefix_len = 0; } else { redis_sock->prefix_len = val_len; redis_sock->prefix = ecalloc(1+val_len, 1); memcpy(redis_sock->prefix, val_str, val_len); } RETURN_TRUE; case REDIS_OPT_READ_TIMEOUT: redis_sock->read_timeout = atof(val_str); if(redis_sock->stream) { read_tv.tv_sec = (time_t)redis_sock->read_timeout; read_tv.tv_usec = (int)((redis_sock->read_timeout - read_tv.tv_sec) * 1000000); php_stream_set_option(redis_sock->stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &read_tv); } RETURN_TRUE; default: RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean Redis::config(string op, string key [, mixed value]) */ PHP_METHOD(Redis, config) { zval *object; RedisSock *redis_sock; char *key = NULL, *val = NULL, *cmd, *op = NULL; int key_len, val_len, cmd_len, op_len; enum {CFG_GET, CFG_SET} mode; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss|s", &object, redis_ce, &op, &op_len, &key, &key_len, &val, &val_len) == FAILURE) { RETURN_FALSE; } /* op must be GET or SET */ if(strncasecmp(op, "GET", 3) == 0) { mode = CFG_GET; } else if(strncasecmp(op, "SET", 3) == 0) { mode = CFG_SET; } else { RETURN_FALSE; } if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } if (mode == CFG_GET && val == NULL) { cmd_len = redis_cmd_format_static(&cmd, "CONFIG", "ss", op, op_len, key, key_len); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len) IF_ATOMIC() { redis_sock_read_multibulk_reply_zipped_strings(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_zipped_strings); } else if(mode == CFG_SET && val != NULL) { cmd_len = redis_cmd_format_static(&cmd, "CONFIG", "sss", op, op_len, key, key_len, val, val_len); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len) IF_ATOMIC() { redis_boolean_response(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL); } REDIS_PROCESS_RESPONSE(redis_boolean_response); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean Redis::slowlog(string arg, [int option]) */ PHP_METHOD(Redis, slowlog) { zval *object; RedisSock *redis_sock; char *arg, *cmd; int arg_len, cmd_len; long option; enum {SLOWLOG_GET, SLOWLOG_LEN, SLOWLOG_RESET} mode; // Make sure we can get parameters if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &object, redis_ce, &arg, &arg_len, &option) == FAILURE) { RETURN_FALSE; } // Figure out what kind of slowlog command we're executing if(!strncasecmp(arg, "GET", 3)) { mode = SLOWLOG_GET; } else if(!strncasecmp(arg, "LEN", 3)) { mode = SLOWLOG_LEN; } else if(!strncasecmp(arg, "RESET", 5)) { mode = SLOWLOG_RESET; } else { // This command is not valid RETURN_FALSE; } // Make sure we can grab our redis socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Create our command. For everything except SLOWLOG GET (with an arg) it's just two parts if(mode == SLOWLOG_GET && ZEND_NUM_ARGS() == 2) { cmd_len = redis_cmd_format_static(&cmd, "SLOWLOG", "sl", arg, arg_len, option); } else { cmd_len = redis_cmd_format_static(&cmd, "SLOWLOG", "s", arg, arg_len); } // Kick off our command REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if(redis_read_variant_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_read_variant_reply); } // Construct an EVAL or EVALSHA command, with option argument array and number of arguments that are keys parameter PHPAPI int redis_build_eval_cmd(RedisSock *redis_sock, char **ret, char *keyword, char *value, int val_len, zval *args, int keys_count TSRMLS_DC) { zval **elem; HashTable *args_hash; HashPosition hash_pos; int cmd_len, args_count = 0; int eval_cmd_count = 2; // If we've been provided arguments, we'll want to include those in our eval command if(args != NULL) { // Init our hash array value, and grab the count args_hash = Z_ARRVAL_P(args); args_count = zend_hash_num_elements(args_hash); // We only need to process the arguments if the array is non empty if(args_count > 0) { // Header for our EVAL command cmd_len = redis_cmd_format_header(ret, keyword, eval_cmd_count + args_count); // Now append the script itself, and the number of arguments to treat as keys cmd_len = redis_cmd_append_str(ret, cmd_len, value, val_len); cmd_len = redis_cmd_append_int(ret, cmd_len, keys_count); // Iterate the values in our "keys" array for(zend_hash_internal_pointer_reset_ex(args_hash, &hash_pos); zend_hash_get_current_data_ex(args_hash, (void **)&elem, &hash_pos) == SUCCESS; zend_hash_move_forward_ex(args_hash, &hash_pos)) { zval *z_tmp = NULL; char *key, *old_cmd; int key_len, key_free; if(Z_TYPE_PP(elem) == IS_STRING) { key = Z_STRVAL_PP(elem); key_len = Z_STRLEN_PP(elem); } else { // Convert it to a string MAKE_STD_ZVAL(z_tmp); *z_tmp = **elem; zval_copy_ctor(z_tmp); convert_to_string(z_tmp); key = Z_STRVAL_P(z_tmp); key_len = Z_STRLEN_P(z_tmp); } // Keep track of the old command pointer old_cmd = *ret; // If this is still a key argument, prefix it if we've been set up to prefix keys key_free = keys_count-- > 0 ? redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC) : 0; // Append this key to our EVAL command, free our old command cmd_len = redis_cmd_format(ret, "%s$%d" _NL "%s" _NL, *ret, cmd_len, key_len, key, key_len); efree(old_cmd); // Free our key, old command if we need to if(key_free) efree(key); // Free our temporary zval (converted from non string) if we've got one if(z_tmp) { zval_dtor(z_tmp); efree(z_tmp); } } } } // If there weren't any arguments (none passed, or an empty array), construct a standard no args command if(args_count < 1) { cmd_len = redis_cmd_format_static(ret, keyword, "sd", value, val_len, 0); } // Return our command length return cmd_len; } /* {{{ proto variant Redis::evalsha(string script_sha1, [array keys, int num_key_args]) */ PHP_METHOD(Redis, evalsha) { zval *object, *args= NULL; char *cmd, *sha; int cmd_len, sha_len; long keys_count = 0; RedisSock *redis_sock; if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|al", &object, redis_ce, &sha, &sha_len, &args, &keys_count) == FAILURE) { RETURN_FALSE; } // Attempt to grab socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Construct our EVALSHA command cmd_len = redis_build_eval_cmd(redis_sock, &cmd, "EVALSHA", sha, sha_len, args, keys_count TSRMLS_CC); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if(redis_read_variant_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_read_variant_reply); } /* {{{ proto variant Redis::eval(string script, [array keys, int num_key_args]) */ PHP_METHOD(Redis, eval) { zval *object, *args = NULL; RedisSock *redis_sock; char *script, *cmd = ""; int script_len, cmd_len; long keys_count = 0; // Attempt to parse parameters if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|al", &object, redis_ce, &script, &script_len, &args, &keys_count) == FAILURE) { RETURN_FALSE; } // Attempt to grab socket if (redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Construct our EVAL command cmd_len = redis_build_eval_cmd(redis_sock, &cmd, "EVAL", script, script_len, args, keys_count TSRMLS_CC); REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if(redis_read_variant_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_read_variant_reply); } PHPAPI int redis_build_script_exists_cmd(char **ret, zval **argv, int argc) { // Our command length and iterator int cmd_len = 0, i; // Start building our command cmd_len = redis_cmd_format_header(ret, "SCRIPT", argc + 1); // +1 for "EXISTS" cmd_len = redis_cmd_append_str(ret, cmd_len, "EXISTS", 6); // Iterate our arguments for(i=0;iprefix != NULL && redis_sock->prefix_len > 0) { redis_key_prefix(redis_sock, &key, &key_len TSRMLS_CC); RETURN_STRINGL(key, key_len, 0); } else { RETURN_STRINGL(key, key_len, 1); } } /* * {{{ proto Redis::_unserialize(value) */ PHP_METHOD(Redis, _unserialize) { zval *object; RedisSock *redis_sock; char *value; int value_len; // Parse our arguments if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, redis_ce, &value, &value_len) == FAILURE) { RETURN_FALSE; } // Grab socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // We only need to attempt unserialization if we have a serializer running if(redis_sock->serializer != REDIS_SERIALIZER_NONE) { zval *z_ret = NULL; if(redis_unserialize(redis_sock, value, value_len, &z_ret TSRMLS_CC) == 0) { // Badly formed input, throw an execption zend_throw_exception(redis_exception_ce, "Invalid serialized data, or unserialization error", 0 TSRMLS_CC); RETURN_FALSE; } RETURN_ZVAL(z_ret, 0, 1); } else { // Just return the value that was passed to us RETURN_STRINGL(value, value_len, 1); } } /* * {{{ proto Redis::getLastError() */ PHP_METHOD(Redis, getLastError) { zval *object; RedisSock *redis_sock; // Grab our object if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } // Grab socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Return our last error or NULL if we don't have one if(redis_sock->err != NULL && redis_sock->err_len > 0) { RETURN_STRINGL(redis_sock->err, redis_sock->err_len, 1); } else { RETURN_NULL(); } } /* * {{{ proto Redis::clearLastError() */ PHP_METHOD(Redis, clearLastError) { zval *object; RedisSock *redis_sock; // Grab our object if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } // Grab socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Clear error message if(redis_sock->err) { efree(redis_sock->err); } redis_sock->err = NULL; RETURN_TRUE; } /* * {{{ proto Redis::time() */ PHP_METHOD(Redis, time) { zval *object; RedisSock *redis_sock; char *cmd; int cmd_len; // Grab our object if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, redis_ce) == FAILURE) { RETURN_FALSE; } // Grab socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Build TIME command cmd_len = redis_cmd_format_static(&cmd, "TIME", ""); // Execute or queue command REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); IF_ATOMIC() { if(redis_sock_read_multibulk_reply_raw(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL) < 0) { RETURN_FALSE; } } REDIS_PROCESS_RESPONSE(redis_sock_read_multibulk_reply_raw); } /* * Introspection stuff */ /* * {{{ proto Redis::IsConnected */ PHP_METHOD(Redis, isConnected) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { RETURN_TRUE; } else { RETURN_FALSE; } } /* * {{{ proto Redis::getHost() */ PHP_METHOD(Redis, getHost) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { RETURN_STRING(redis_sock->host, 1); } else { RETURN_FALSE; } } /* * {{{ proto Redis::getPort() */ PHP_METHOD(Redis, getPort) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { // Return our port RETURN_LONG(redis_sock->port); } else { RETURN_FALSE; } } /* * {{{ proto Redis::getDBNum */ PHP_METHOD(Redis, getDBNum) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { // Return our db number RETURN_LONG(redis_sock->dbNumber); } else { RETURN_FALSE; } } /* * {{{ proto Redis::getTimeout */ PHP_METHOD(Redis, getTimeout) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { RETURN_DOUBLE(redis_sock->timeout); } else { RETURN_FALSE; } } /* * {{{ proto Redis::getReadTimeout */ PHP_METHOD(Redis, getReadTimeout) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { RETURN_DOUBLE(redis_sock->read_timeout); } else { RETURN_FALSE; } } /* * {{{ proto Redis::getPersistentID */ PHP_METHOD(Redis, getPersistentID) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { if(redis_sock->persistent_id != NULL) { RETURN_STRING(redis_sock->persistent_id, 1); } else { RETURN_NULL(); } } else { RETURN_FALSE; } } /* * {{{ proto Redis::getAuth */ PHP_METHOD(Redis, getAuth) { RedisSock *redis_sock; if((redis_sock = redis_sock_get_connected(INTERNAL_FUNCTION_PARAM_PASSTHRU))) { if(redis_sock->auth != NULL) { RETURN_STRING(redis_sock->auth, 1); } else { RETURN_NULL(); } } else { RETURN_FALSE; } } /* * $redis->client('list'); * $redis->client('kill', ); * $redis->client('setname', ); * $redis->client('getname'); */ PHP_METHOD(Redis, client) { zval *object; RedisSock *redis_sock; char *cmd, *opt=NULL, *arg=NULL; int cmd_len, opt_len, arg_len; // Parse our method parameters if(zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &object, redis_ce, &opt, &opt_len, &arg, &arg_len) == FAILURE) { RETURN_FALSE; } // Grab our socket if(redis_sock_get(object, &redis_sock TSRMLS_CC, 0) < 0) { RETURN_FALSE; } // Build our CLIENT command if(ZEND_NUM_ARGS() == 2) { cmd_len = redis_cmd_format_static(&cmd, "CLIENT", "ss", opt, opt_len, arg, arg_len); } else { cmd_len = redis_cmd_format_static(&cmd, "CLIENT", "s", opt, opt_len); } // Execute our queue command REDIS_PROCESS_REQUEST(redis_sock, cmd, cmd_len); // We handle CLIENT LIST with a custom response function if(!strncasecmp(opt, "list", 4)) { IF_ATOMIC() { redis_client_list_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU,redis_sock,NULL); } REDIS_PROCESS_RESPONSE(redis_client_list_reply); } else { IF_ATOMIC() { redis_read_variant_reply(INTERNAL_FUNCTION_PARAM_PASSTHRU,redis_sock,NULL); } REDIS_PROCESS_RESPONSE(redis_read_variant_reply); } } /* vim: set tabstop=4 softtabstops=4 noexpandtab shiftwidth=4: */ redis-2.2.4/redis_session.c0000664000175000017500000002772112211042406015507 0ustar nicolasnicolas/* -*- Mode: C; tab-width: 4 -*- */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2009 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Original author: Alfonso Jimenez | | Maintainer: Nicolas Favre-Felix | | Maintainer: Nasreddine Bouafif | | Maintainer: Michael Grunder | +----------------------------------------------------------------------+ */ #include "common.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef PHP_SESSION #include "common.h" #include "ext/standard/info.h" #include "php_redis.h" #include "redis_session.h" #include #include "library.h" #include "php.h" #include "php_ini.h" #include "php_variables.h" #include "SAPI.h" #include "ext/standard/url.h" ps_module ps_mod_redis = { PS_MOD(redis) }; typedef struct redis_pool_member_ { RedisSock *redis_sock; int weight; int database; char *prefix; size_t prefix_len; char *auth; size_t auth_len; struct redis_pool_member_ *next; } redis_pool_member; typedef struct { int totalWeight; int count; redis_pool_member *head; } redis_pool; PHPAPI redis_pool* redis_pool_new(TSRMLS_D) { return ecalloc(1, sizeof(redis_pool)); } PHPAPI void redis_pool_add(redis_pool *pool, RedisSock *redis_sock, int weight, int database, char *prefix, char *auth TSRMLS_DC) { redis_pool_member *rpm = ecalloc(1, sizeof(redis_pool_member)); rpm->redis_sock = redis_sock; rpm->weight = weight; rpm->database = database; rpm->prefix = prefix; rpm->prefix_len = (prefix?strlen(prefix):0); rpm->auth = auth; rpm->auth_len = (auth?strlen(auth):0); rpm->next = pool->head; pool->head = rpm; pool->totalWeight += weight; } PHPAPI void redis_pool_free(redis_pool *pool TSRMLS_DC) { redis_pool_member *rpm, *next; rpm = pool->head; while(rpm) { next = rpm->next; redis_sock_disconnect(rpm->redis_sock TSRMLS_CC); efree(rpm->redis_sock); if(rpm->prefix) efree(rpm->prefix); if(rpm->auth) efree(rpm->auth); efree(rpm); rpm = next; } efree(pool); } void redis_pool_member_auth(redis_pool_member *rpm TSRMLS_DC) { RedisSock *redis_sock = rpm->redis_sock; char *response, *cmd; int response_len, cmd_len; if(!rpm->auth || !rpm->auth_len) { /* no password given. */ return; } cmd_len = redis_cmd_format_static(&cmd, "AUTH", "s", rpm->auth, rpm->auth_len); if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) >= 0) { if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC))) { efree(response); } } efree(cmd); } static void redis_pool_member_select(redis_pool_member *rpm TSRMLS_DC) { RedisSock *redis_sock = rpm->redis_sock; char *response, *cmd; int response_len, cmd_len; cmd_len = redis_cmd_format_static(&cmd, "SELECT", "d", rpm->database); if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) >= 0) { if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC))) { efree(response); } } efree(cmd); } PHPAPI redis_pool_member * redis_pool_get_sock(redis_pool *pool, const char *key TSRMLS_DC) { unsigned int pos, i; memcpy(&pos, key, sizeof(pos)); pos %= pool->totalWeight; redis_pool_member *rpm = pool->head; for(i = 0; i < pool->totalWeight;) { if(pos >= i && pos < i + rpm->weight) { int needs_auth = 0; if(rpm->auth && rpm->auth_len && rpm->redis_sock->status != REDIS_SOCK_STATUS_CONNECTED) { needs_auth = 1; } redis_sock_server_open(rpm->redis_sock, 0 TSRMLS_CC); if(needs_auth) { redis_pool_member_auth(rpm TSRMLS_CC); } if(rpm->database >= 0) { /* default is -1 which leaves the choice to redis. */ redis_pool_member_select(rpm TSRMLS_CC); } return rpm; } i += rpm->weight; rpm = rpm->next; } return NULL; } /* {{{ PS_OPEN_FUNC */ PS_OPEN_FUNC(redis) { php_url *url; zval *params, **param; int i, j, path_len; redis_pool *pool = redis_pool_new(TSRMLS_C); for (i=0,j=0,path_len=strlen(save_path); iquery != NULL) { MAKE_STD_ZVAL(params); array_init(params); sapi_module.treat_data(PARSE_STRING, estrdup(url->query), params TSRMLS_CC); if (zend_hash_find(Z_ARRVAL_P(params), "weight", sizeof("weight"), (void **) ¶m) != FAILURE) { convert_to_long_ex(param); weight = Z_LVAL_PP(param); } if (zend_hash_find(Z_ARRVAL_P(params), "timeout", sizeof("timeout"), (void **) ¶m) != FAILURE) { timeout = atof(Z_STRVAL_PP(param)); } if (zend_hash_find(Z_ARRVAL_P(params), "persistent", sizeof("persistent"), (void **) ¶m) != FAILURE) { persistent = (atol(Z_STRVAL_PP(param)) == 1 ? 1 : 0); } if (zend_hash_find(Z_ARRVAL_P(params), "persistent_id", sizeof("persistent_id"), (void **) ¶m) != FAILURE) { persistent_id = estrndup(Z_STRVAL_PP(param), Z_STRLEN_PP(param)); } if (zend_hash_find(Z_ARRVAL_P(params), "prefix", sizeof("prefix"), (void **) ¶m) != FAILURE) { prefix = estrndup(Z_STRVAL_PP(param), Z_STRLEN_PP(param)); } if (zend_hash_find(Z_ARRVAL_P(params), "auth", sizeof("auth"), (void **) ¶m) != FAILURE) { auth = estrndup(Z_STRVAL_PP(param), Z_STRLEN_PP(param)); } if (zend_hash_find(Z_ARRVAL_P(params), "database", sizeof("database"), (void **) ¶m) != FAILURE) { convert_to_long_ex(param); database = Z_LVAL_PP(param); } if (zend_hash_find(Z_ARRVAL_P(params), "retry_interval", sizeof("retry_interval"), (void **) ¶m) != FAILURE) { convert_to_long_ex(param); retry_interval = Z_LVAL_PP(param); } zval_ptr_dtor(¶ms); } if ((url->path == NULL && url->host == NULL) || weight <= 0 || timeout <= 0) { php_url_free(url); redis_pool_free(pool TSRMLS_CC); PS_SET_MOD_DATA(NULL); return FAILURE; } RedisSock *redis_sock; if(url->host) { redis_sock = redis_sock_create(url->host, strlen(url->host), url->port, timeout, persistent, persistent_id, retry_interval, 0); } else { /* unix */ redis_sock = redis_sock_create(url->path, strlen(url->path), 0, timeout, persistent, persistent_id, retry_interval, 0); } redis_pool_add(pool, redis_sock, weight, database, prefix, auth TSRMLS_CC); php_url_free(url); } } if (pool->head) { PS_SET_MOD_DATA(pool); return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ PS_CLOSE_FUNC */ PS_CLOSE_FUNC(redis) { redis_pool *pool = PS_GET_MOD_DATA(); if(pool){ redis_pool_free(pool TSRMLS_CC); PS_SET_MOD_DATA(NULL); } return SUCCESS; } /* }}} */ static char * redis_session_key(redis_pool_member *rpm, const char *key, int key_len, int *session_len) { char *session; char default_prefix[] = "PHPREDIS_SESSION:"; char *prefix = default_prefix; size_t prefix_len = sizeof(default_prefix)-1; if(rpm->prefix) { prefix = rpm->prefix; prefix_len = rpm->prefix_len; } /* build session key */ *session_len = key_len + prefix_len; session = emalloc(*session_len); memcpy(session, prefix, prefix_len); memcpy(session + prefix_len, key, key_len); return session; } /* {{{ PS_READ_FUNC */ PS_READ_FUNC(redis) { char *session, *cmd; int session_len, cmd_len; redis_pool *pool = PS_GET_MOD_DATA(); redis_pool_member *rpm = redis_pool_get_sock(pool, key TSRMLS_CC); RedisSock *redis_sock = rpm?rpm->redis_sock:NULL; if(!rpm || !redis_sock){ return FAILURE; } /* send GET command */ session = redis_session_key(rpm, key, strlen(key), &session_len); cmd_len = redis_cmd_format_static(&cmd, "GET", "s", session, session_len); efree(session); if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return FAILURE; } efree(cmd); /* read response */ if ((*val = redis_sock_read(redis_sock, vallen TSRMLS_CC)) == NULL) { return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ PS_WRITE_FUNC */ PS_WRITE_FUNC(redis) { char *cmd, *response, *session; int cmd_len, response_len, session_len; redis_pool *pool = PS_GET_MOD_DATA(); redis_pool_member *rpm = redis_pool_get_sock(pool, key TSRMLS_CC); RedisSock *redis_sock = rpm?rpm->redis_sock:NULL; if(!rpm || !redis_sock){ return FAILURE; } /* send SET command */ session = redis_session_key(rpm, key, strlen(key), &session_len); cmd_len = redis_cmd_format_static(&cmd, "SETEX", "sds", session, session_len, INI_INT("session.gc_maxlifetime"), val, vallen); efree(session); if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return FAILURE; } efree(cmd); /* read response */ if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { return FAILURE; } if(response_len == 3 && strncmp(response, "+OK", 3) == 0) { efree(response); return SUCCESS; } else { efree(response); return FAILURE; } } /* }}} */ /* {{{ PS_DESTROY_FUNC */ PS_DESTROY_FUNC(redis) { char *cmd, *response, *session; int cmd_len, response_len, session_len; redis_pool *pool = PS_GET_MOD_DATA(); redis_pool_member *rpm = redis_pool_get_sock(pool, key TSRMLS_CC); RedisSock *redis_sock = rpm?rpm->redis_sock:NULL; if(!rpm || !redis_sock){ return FAILURE; } /* send DEL command */ session = redis_session_key(rpm, key, strlen(key), &session_len); cmd_len = redis_cmd_format_static(&cmd, "DEL", "s", session, session_len); efree(session); if(redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) { efree(cmd); return FAILURE; } efree(cmd); /* read response */ if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) { return FAILURE; } if(response_len == 2 && response[0] == ':' && (response[1] == '0' || response[1] == '1')) { efree(response); return SUCCESS; } else { efree(response); return FAILURE; } } /* }}} */ /* {{{ PS_GC_FUNC */ PS_GC_FUNC(redis) { return SUCCESS; } /* }}} */ #endif /* vim: set tabstop=4 expandtab: */ redis-2.2.4/redis_session.h0000664000175000017500000000037312211042406015506 0ustar nicolasnicolas#ifndef REDIS_SESSION_H #define REDIS_SESSION_H #ifdef PHP_SESSION #include "ext/session/php_session.h" PS_OPEN_FUNC(redis); PS_CLOSE_FUNC(redis); PS_READ_FUNC(redis); PS_WRITE_FUNC(redis); PS_DESTROY_FUNC(redis); PS_GC_FUNC(redis); #endif #endif