Commit 24a8cc36 authored by w3challs's avatar w3challs
Browse files

init repo

parents
## Web/Misc challs source
This repository contains the source code of some (not all!) of the Web & Misc challenges.
<?php
include('config.php');
include('util.php');
require 'credis/Client.php';
$redis = new Credis_Client($redis_host, $redis_port, null, '', $redis_db);
$url = $redis->hget('trainer:'.$_GET['value'], 'url');
if($url){
$baseUrl = substr($url, 0, strrpos($url, '/'));
$result = get_web_page($baseUrl.'/Badge.php', $trainerName);
echo $result;
}
else{
echo '{"error": "Trainer unknown"}';
}
?>
<?php
include('config.php');
require 'credis/Client.php';
$redis = new Credis_Client($redis_host, $redis_port, null, '', $redis_db);
$win = $redis->hget('trainer:'.$_SERVER['HTTP_USER_AGENT'], 'win');
if($win === "1"){
echo '"'.$badge.'"';
}
else{
echo '"You never won against me"';
}
?>
<?php
include('config.php');
require 'credis/Client.php';
$redis = new Credis_Client($redis_host, $redis_port, null, '', $redis_db);
$redis->hset('trainer:'.$_SERVER['HTTP_USER_AGENT'], 'win', '0');
$result = $redis->keys('pokemon:*');
$pokemons = array();
for($i=0; $i<count($result); $i++){
array_push($pokemons, json_decode($redis->get($result[$i])));
}
$result = new stdClass();
$result->trainer = $trainerName;
$result->pokemons = $pokemons;
echo json_encode($result);
?>
<?php
include('config.php');
include('util.php');
require 'credis/Client.php';
$api = 'http://pokeapi.co/api/v2/pokemon/';
$pokemon_name = strtolower($_GET['value']);
if(ctype_alpha($pokemon_name)){
$redis = new Credis_Client($redis_host, $redis_port, null, '', $redis_db);
$result = $redis->get('pokemon:'.$pokemon_name);
if(!$result){
$pokemon_full = json_decode(get_web_page($api.$pokemon_name.'/', $trainerName));
if(@$pokemon_full->detail){
$result = '{"error": "Pokemon unknown"}';
}
else{
$pokemon = new stdClass();
$pokemon->name = $pokemon_full->name;
$pokemon->id = $pokemon_full->id;
$pokemon->height = $pokemon_full->height;
$pokemon->weight = $pokemon_full->weight;
$pokemon->img = base64_encode(get_web_page($pokemon_full->sprites->front_default, $trainerName));
$pokemon->type = $pokemon_full->types[0]->type->name;
$result = json_encode($pokemon);
$redis->set('pokemon:'.$pokemon_name, $result);
}
}
echo $result;
}
else{
echo '{"error": "Bad value"}';
}
?>
<?php
include('config.php');
include('util.php');
require 'credis/Client.php';
$result = get_web_page($_GET['value'], $trainerName);
$d_result = json_decode($result);
$redis = new Credis_Client($redis_host, $redis_port, null, '', $redis_db);
$redis->hset('trainer:'.$d_result->trainer, 'url', $_GET['value']);
echo $result;
?>
<?php
$trainerName = 'Gary';
$badge = 'The flag will be here!';
$redis_host = '127.0.0.1';
$redis_port = 6379;
$redis_db = 15;
?>
<?php
/**
* Credis_Client (a fork of Redisent)
*
* Most commands are compatible with phpredis library:
* - use "pipeline()" to start a pipeline of commands instead of multi(Redis::PIPELINE)
* - any arrays passed as arguments will be flattened automatically
* - setOption and getOption are not supported in standalone mode
* - order of arguments follows redis-cli instead of phpredis where they differ (lrem)
*
* - Uses phpredis library if extension is installed for better performance.
* - Establishes connection lazily.
* - Supports tcp and unix sockets.
* - Reconnects automatically unless a watch or transaction is in progress.
* - Can set automatic retry connection attempts for iffy Redis connections.
*
* @author Colin Mollenhour <colin@mollenhour.com>
* @copyright 2011 Colin Mollenhour <colin@mollenhour.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @package Credis_Client
*/
if( ! defined('CRLF')) define('CRLF', sprintf('%s%s', chr(13), chr(10)));
/**
* Credis-specific errors, wraps native Redis errors
*/
class CredisException extends Exception
{
const CODE_TIMED_OUT = 1;
const CODE_DISCONNECTED = 2;
public function __construct($message, $code = 0, $exception = NULL)
{
if ($exception && get_class($exception) == 'RedisException' && $message == 'read error on connection') {
$code = CredisException::CODE_DISCONNECTED;
}
parent::__construct($message, $code, $exception);
}
}
/**
* Credis_Client, a lightweight Redis PHP standalone client and phpredis wrapper
*
* Server/Connection:
* @method Credis_Client pipeline()
* @method Credis_Client multi()
* @method array exec()
* @method string flushAll()
* @method string flushDb()
* @method array info()
* @method bool|array config(string $setGet, string $key, string $value = null)
*
* Keys:
* @method int del(string $key)
* @method int exists(string $key)
* @method int expire(string $key, int $seconds)
* @method int expireAt(string $key, int $timestamp)
* @method array keys(string $key)
* @method int persist(string $key)
* @method bool rename(string $key, string $newKey)
* @method bool renameNx(string $key, string $newKey)
* @method array sort(string $key, string $arg1, string $valueN = null)
* @method int ttl(string $key)
* @method string type(string $key)
*
* Scalars:
* @method int append(string $key, string $value)
* @method int decr(string $key)
* @method int decrBy(string $key, int $decrement)
* @method bool|string get(string $key)
* @method int getBit(string $key, int $offset)
* @method string getRange(string $key, int $start, int $end)
* @method string getSet(string $key, string $value)
* @method int incr(string $key)
* @method int incrBy(string $key, int $decrement)
* @method array mGet(array $keys)
* @method bool mSet(array $keysValues)
* @method int mSetNx(array $keysValues)
* @method bool set(string $key, string $value)
* @method int setBit(string $key, int $offset, int $value)
* @method bool setEx(string $key, int $seconds, string $value)
* @method int setNx(string $key, string $value)
* @method int setRange(string $key, int $offset, int $value)
* @method int strLen(string $key)
*
* Sets:
* @method int sAdd(string $key, mixed $value, string $valueN = null)
* @method int sRem(string $key, mixed $value, string $valueN = null)
* @method array sMembers(string $key)
* @method array sUnion(mixed $keyOrArray, string $valueN = null)
* @method array sInter(mixed $keyOrArray, string $valueN = null)
* @method array sDiff(mixed $keyOrArray, string $valueN = null)
* @method string sPop(string $key)
* @method int sCard(string $key)
* @method int sIsMember(string $key, string $member)
* @method int sMove(string $source, string $dest, string $member)
* @method string|array sRandMember(string $key, int $count = null)
* @method int sUnionStore(string $dest, string $key1, string $key2 = null)
* @method int sInterStore(string $dest, string $key1, string $key2 = null)
* @method int sDiffStore(string $dest, string $key1, string $key2 = null)
*
* Hashes:
* @method bool|int hSet(string $key, string $field, string $value)
* @method bool hSetNx(string $key, string $field, string $value)
* @method bool|string hGet(string $key, string $field)
* @method bool|int hLen(string $key)
* @method bool hDel(string $key, string $field)
* @method array hKeys(string $key, string $field)
* @method array hVals(string $key)
* @method array hGetAll(string $key)
* @method bool hExists(string $key, string $field)
* @method int hIncrBy(string $key, string $field, int $value)
* @method bool hMSet(string $key, array $keysValues)
* @method array hMGet(string $key, array $fields)
*
* Lists:
* @method array|null blPop(string $keyN, int $timeout)
* @method array|null brPop(string $keyN, int $timeout)
* @method array|null brPoplPush(string $source, string $destination, int $timeout)
* @method string|null lIndex(string $key, int $index)
* @method int lInsert(string $key, string $beforeAfter, string $pivot, string $value)
* @method int lLen(string $key)
* @method string|null lPop(string $key)
* @method int lPush(string $key, mixed $value, mixed $valueN = null)
* @method int lPushX(string $key, mixed $value)
* @method array lRange(string $key, int $start, int $stop)
* @method int lRem(string $key, int $count, mixed $value)
* @method bool lSet(string $key, int $index, mixed $value)
* @method bool lTrim(string $key, int $start, int $stop)
* @method string|null rPop(string $key)
* @method string|null rPoplPush(string $source, string $destination)
* @method int rPush(string $key, mixed $value, mixed $valueN = null)
* @method int rPushX(string $key, mixed $value)
*
* Sorted Sets:
* @method array zrangebyscore(string $key, mixed $start, mixed $stop, array $args = null)
* TODO
*
* Pub/Sub
* @method int publish(string $channel, string $message)
* @method int|array pubsub(string $subCommand, $arg = NULL)
*
* Scripting:
* @method string|int script(string $command, string $arg1 = null)
* @method string|int|array|bool eval(string $script, array $keys = NULL, array $args = NULL)
* @method string|int|array|bool evalSha(string $script, array $keys = NULL, array $args = NULL)
*/
class Credis_Client {
const TYPE_STRING = 'string';
const TYPE_LIST = 'list';
const TYPE_SET = 'set';
const TYPE_ZSET = 'zset';
const TYPE_HASH = 'hash';
const TYPE_NONE = 'none';
const FREAD_BLOCK_SIZE = 8192;
/**
* Socket connection to the Redis server or Redis library instance
* @var resource|Redis
*/
protected $redis;
protected $redisMulti;
/**
* Host of the Redis server
* @var string
*/
protected $host;
/**
* Port on which the Redis server is running
* @var integer
*/
protected $port;
/**
* Timeout for connecting to Redis server
* @var float
*/
protected $timeout;
/**
* Timeout for reading response from Redis server
* @var float
*/
protected $readTimeout;
/**
* Unique identifier for persistent connections
* @var string
*/
protected $persistent;
/**
* @var bool
*/
protected $closeOnDestruct = TRUE;
/**
* @var bool
*/
protected $connected = FALSE;
/**
* @var bool
*/
protected $standalone;
/**
* @var int
*/
protected $maxConnectRetries = 0;
/**
* @var int
*/
protected $connectFailures = 0;
/**
* @var bool
*/
protected $usePipeline = FALSE;
/**
* @var array
*/
protected $commandNames;
/**
* @var string
*/
protected $commands;
/**
* @var bool
*/
protected $isMulti = FALSE;
/**
* @var bool
*/
protected $isWatching = FALSE;
/**
* @var string
*/
protected $authPassword;
/**
* @var int
*/
protected $selectedDb = 0;
/**
* Aliases for backwards compatibility with phpredis
* @var array
*/
protected $wrapperMethods = array('delete' => 'del', 'getkeys' => 'keys', 'sremove' => 'srem');
/**
* @var array
*/
protected $renamedCommands;
/**
* @var int
*/
protected $requests = 0;
/**
* @var bool
*/
protected $subscribed = false;
/**
* Creates a Redisent connection to the Redis server on host {@link $host} and port {@link $port}.
* $host may also be a path to a unix socket or a string in the form of tcp://[hostname]:[port] or unix://[path]
*
* @param string $host The hostname of the Redis server
* @param integer $port The port number of the Redis server
* @param float $timeout Timeout period in seconds
* @param string $persistent Flag to establish persistent connection
* @param int $db The selected datbase of the Redis server
* @param string $password The authentication password of the Redis server
*/
public function __construct($host = '127.0.0.1', $port = 6379, $timeout = null, $persistent = '', $db = 0, $password = null)
{
$this->host = (string) $host;
$this->port = (int) $port;
$this->timeout = $timeout;
$this->persistent = (string) $persistent;
$this->standalone = ! extension_loaded('redis');
$this->authPassword = $password;
$this->selectedDb = (int)$db;
$this->convertHost();
}
public function __destruct()
{
if ($this->closeOnDestruct) {
$this->close();
}
}
/**
* @return bool
*/
public function isSubscribed()
{
return $this->subscribed;
}
/**
* Return the host of the Redis instance
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Return the port of the Redis instance
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* Return the selected database
* @return int
*/
public function getSelectedDb()
{
return $this->selectedDb;
}
/**
* @return string
*/
public function getPersistence()
{
return $this->persistent;
}
/**
* @throws CredisException
* @return Credis_Client
*/
public function forceStandalone()
{
if ($this->standalone) {
return $this;
}
if($this->connected) {
throw new CredisException('Cannot force Credis_Client to use standalone PHP driver after a connection has already been established.');
}
$this->standalone = TRUE;
return $this;
}
/**
* @param int $retries
* @return Credis_Client
*/
public function setMaxConnectRetries($retries)
{
$this->maxConnectRetries = $retries;
return $this;
}
/**
* @param bool $flag
* @return Credis_Client
*/
public function setCloseOnDestruct($flag)
{
$this->closeOnDestruct = $flag;
return $this;
}
protected function convertHost()
{
if (preg_match('#^(tcp|unix)://(.*)$#', $this->host, $matches)) {
if($matches[1] == 'tcp') {
if ( ! preg_match('#^([^:]+)(:([0-9]+))?(/(.+))?$#', $matches[2], $matches)) {
throw new CredisException('Invalid host format; expected tcp://host[:port][/persistence_identifier]');
}
$this->host = $matches[1];
$this->port = (int) (isset($matches[3]) ? $matches[3] : 6379);
$this->persistent = isset($matches[5]) ? $matches[5] : '';
} else {
$this->host = $matches[2];
$this->port = NULL;
if (substr($this->host,0,1) != '/') {
throw new CredisException('Invalid unix socket format; expected unix:///path/to/redis.sock');
}
}
}
if ($this->port !== NULL && substr($this->host,0,1) == '/') {
$this->port = NULL;
}
}
/**
* @throws CredisException
* @return Credis_Client
*/
public function connect()
{
if ($this->connected) {
return $this;
}
if ($this->standalone) {
$flags = STREAM_CLIENT_CONNECT;
$remote_socket = $this->port === NULL
? 'unix://'.$this->host
: 'tcp://'.$this->host.':'.$this->port;
if ($this->persistent) {
if ($this->port === NULL) { // Unix socket
throw new CredisException('Persistent connections to UNIX sockets are not supported in standalone mode.');
}
$remote_socket .= '/'.$this->persistent;
$flags = $flags | STREAM_CLIENT_PERSISTENT;
}
$result = $this->redis = @stream_socket_client($remote_socket, $errno, $errstr, $this->timeout !== null ? $this->timeout : 2.5, $flags);
}
else {
if ( ! $this->redis) {
$this->redis = new Redis;
}
$result = $this->persistent
? $this->redis->pconnect($this->host, $this->port, $this->timeout, $this->persistent)
: $this->redis->connect($this->host, $this->port, $this->timeout);
}
// Use recursion for connection retries
if ( ! $result) {
$this->connectFailures++;
if ($this->connectFailures <= $this->maxConnectRetries) {
return $this->connect();
}
$failures = $this->connectFailures;
$this->connectFailures = 0;
throw new CredisException("Connection to Redis failed after $failures failures." . (isset($errno) && isset($errstr) ? "Last Error : ({$errno}) {$errstr}" : ""));
}
$this->connectFailures = 0;
$this->connected = TRUE;
// Set read timeout
if ($this->readTimeout) {
$this->setReadTimeout($this->readTimeout);
}
if($this->authPassword) {
$this->auth($this->authPassword);
}
if($this->selectedDb !== 0) {
$this->select($this->selectedDb);
}
return $this;
}
/**
* @return bool
*/
public function isConnected()
{
return $this->connected;
}
/**
* Set the read timeout for the connection. Use 0 to disable timeouts entirely (or use a very long timeout
* if not supported).
*
* @param int $timeout 0 (or -1) for no timeout, otherwise number of seconds
* @throws CredisException
* @return Credis_Client
*/
public function setReadTimeout($timeout)
{
if ($timeout < -1) {
throw new CredisException('Timeout values less than -1 are not accepted.');
}
$this->readTimeout = $timeout;
if ($this->connected) {
if ($this->standalone) {
$timeout = $timeout <= 0 ? 315360000 : $timeout; // Ten-year timeout
stream_set_blocking($this->redis, TRUE);
stream_set_timeout($this->redis, (int) floor($timeout), ($timeout - floor($timeout)) * 1000000);
} else if (defined('Redis::OPT_READ_TIMEOUT')) {
// supported in phpredis 2.2.3
// a timeout value of -1 means reads will not timeout
$timeout = $timeout == 0 ? -1 : $timeout;
$this->redis->setOption(Redis::OPT_READ_TIMEOUT, $timeout);