Esempio n. 1
0
 /**
  */
 protected function _set($key, $val, $opts)
 {
     if (!empty($opts['replace']) && !$this->_predis->exists($key)) {
         return false;
     }
     /* Can't use SETEX, since 2.0 server is not guaranteed. */
     if (!$this->_predis->set($key, $val)) {
         return false;
     }
     if (!empty($opts['expire'])) {
         $this->_predis->expire($key, $opts['expire']);
     }
     return true;
 }
Esempio n. 2
0
    echo $redis->hget($dkey, $ukey);
    if (!$debug) {
        exit(0);
    }
    $msg = 'this is a cache';
    // if a comment was submitted or clear page cache request was made delete cache of page
} else {
    if ($submit || substr($_SERVER['REQUEST_URI'], -4) == '?r=y') {
        require './blog/wp-blog-header.php';
        $redis->hdel($dkey, $ukey);
        $msg = 'cache of page deleted';
        // delete entire cache, works only if logged in
    } else {
        if ($loggedin && substr($_SERVER['REQUEST_URI'], -4) == '?c=y') {
            require './blog/wp-blog-header.php';
            if ($redis->exists($dkey)) {
                $redis->del($dkey);
                $msg = 'domain cache flushed';
            } else {
                $msg = 'no cache to flush';
            }
            // if logged in don't cache anything
        } else {
            if ($loggedin) {
                require './blog/wp-blog-header.php';
                $msg = 'not cached';
                // cache the page
            } else {
                // turn on output buffering
                ob_start();
                require './blog/wp-blog-header.php';
Esempio n. 3
0
// scenarios. The only but relevant difference with a basic replication scenario
// is that sentinel servers can manage the master server and its slaves based on
// their state, which means that they are able to provide an authoritative and
// updated configuration to clients thus avoiding static configurations for the
// replication servers and their roles.
// Instead of connection parameters pointing to redis nodes, we provide a list
// of instances of redis-sentinel. Users should always provide a timeout value
// low enough to not hinder operations just in case a sentinel is unreachable
// but Predis uses a default value of 100 milliseconds for sentinel parameters
// without an explicit timeout value.
//
// NOTE: in real-world scenarios sentinels should be running on different hosts!
$sentinels = array('tcp://127.0.0.1:5380?timeout=0.100', 'tcp://127.0.0.1:5381?timeout=0.100', 'tcp://127.0.0.1:5382?timeout=0.100');
$client = new Predis\Client($sentinels, array('replication' => 'sentinel', 'service' => 'mymaster'));
// Read operation.
$exists = $client->exists('foo') ? 'yes' : 'no';
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Does 'foo' exist on {$current->role}? {$exists}.", PHP_EOL;
// Write operation.
$client->set('foo', 'bar');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Now 'foo' has been set to 'bar' on {$current->role}!", PHP_EOL;
// Read operation.
$bar = $client->get('foo');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "We fetched 'foo' from {$current->role} and its value is '{$bar}'.", PHP_EOL;
/* OUTPUT:
Does 'foo' exist on slave-127.0.0.1:6381? yes.
Now 'foo' has been set to 'bar' on master!
We fetched 'foo' from master and its value is 'bar'.
*/
 /**
  * Add or replace a value in the cache.
  *
  * Add does not set the value if the key exists; replace does not replace if the value doesn't exist.
  *
  * @param   bool   $add            True if should only add if value doesn't exist, false to only add when value already exists
  * @param   string $key            The key under which to store the value.
  * @param   mixed  $value          The value to store.
  * @param   string $group          The group value appended to the $key.
  * @param   int    $expiration     The expiration time, defaults to 0.
  * @return  bool                   Returns TRUE on success or FALSE on failure.
  */
 protected function add_or_replace($add, $key, $value, $group = 'default', $expiration = 0)
 {
     $derived_key = $this->build_key($key, $group);
     $result = true;
     // save if group not excluded and redis is up
     if (!in_array($group, $this->no_redis_groups) && $this->redis_status()) {
         $exists = $this->redis->exists($derived_key);
         if ($add === $exists) {
             return false;
         }
         $expiration = $this->validate_expiration($expiration);
         if ($expiration) {
             $result = $this->parse_predis_response($this->redis->setex($derived_key, $expiration, maybe_serialize($value)));
         } else {
             $result = $this->parse_predis_response($this->redis->set($derived_key, maybe_serialize($value)));
         }
     }
     $exists = isset($this->cache[$derived_key]);
     if ($add === $exists) {
         return false;
     }
     if ($result) {
         $this->add_to_internal_cache($derived_key, $value);
     }
     return $result;
 }
Esempio n. 5
0
/**
 * @api {get} /color/key/:key/ball/:ballId/red/:red/green/:green/blue/:blue
 * @apiName ColorBall
 * @apiGroup SpheroCommands
 *
 * @apiParam {String} client api key 
 * @apiParam {Number} ball id number 0 - first ball, 1 - second ball, 2 - both balls
 * @apiParam {Number} angle from opposite backlight to travel 0-359
 * @apiParam {Number} speed 0-1000 increments of 10 on how fast ball should travel
 *
 * @apiSuccess {String} Success
 */
$app->get('/color/key/{key}/ball/{ball}/red/{red}/green/{green}/blue/{blue}', function ($key, $ball, $red, $green, $blue) {
    try {
        $redis = new Predis\Client();
        if (!$redis->exists($key)) {
            return 'This is not a registered key. Please register <a href="http://sphero-api.hopto.org">here</a>';
        }
        $validBalls = array('0', '1', '2');
        if (!in_array($ball, $validBalls)) {
            return 'Invalid ballId';
        }
        $min = 0;
        $max = 255;
        if ($red < $min || $red > $max) {
            return 'Invalid red value...should be between 0 and 255';
        }
        if ($green < $min || $green > $max) {
            return 'Invalid green value...should be between 0 and 255';
        }
        if ($blue < $min || $blue > $max) {
Esempio n. 6
0
}
switch ($mod) {
    case 'order':
        require_once ROOT_PATH . 'lib/order.php';
        if ($action == 'step1') {
            $order_list = MES_Order::get_order_list();
            $smarty->assign('order_list', $order_list);
            $smarty->display('shoppingcar_new.dwt');
            return;
        } else {
            if ($action == 'step2') {
                //每次结算要记录一个ip防止被刷
                $current_ip = GET_IP();
                $_key = 'checkout_times_' . $current_ip;
                $checkout_times = 0;
                if ($REDIS_CLIENT->exists($_key)) {
                    $checkout_times = intval($REDIS_CLIENT->get($_key));
                }
                $_token = GEN_MES_TOKEN();
                $_SESSION['order_token'] = $_token;
                $smarty->assign('order_token', $_token);
                $smarty->assign('checkout_times', $checkout_times);
                date_default_timezone_set("Etc/GMT-8");
                $time = date('Y-m-d H:i:s', time());
                $smarty->assign('current_time', $time);
                unset($_SESSION['flow_order']['surplus']);
                unset($_SESSION['flow_order']['bonus']);
                unset($_SESSION['flow_order']['bonus_id']);
                unset($_SESSION['flow_order']['bonus_sn']);
                $smarty->display('order_new.dwt');
                return;
Esempio n. 7
0
 /**
  * @param string $key
  * @return bool
  */
 public function exists($key)
 {
     return $this->_redis->exists($key);
 }
Esempio n. 8
0
    }
    $app->response->headers->set('Content-Type', 'application/json');
    $app->response->setBody(json_encode($responseData));
});
// B) Enqueue in service queue
//    Request: (URL encoded)
//    *  `session_id`: The session which is ready to be enqueued
//
//    Response: (JSON encoded)
//    *  `queueId`: An identifier for the session's position in the queue
$app->post('/help/queue', function () use($app, $redis) {
    $sessionId = $app->request->params('session_id');
    $helpSessionKey = PREFIX_HELP_SESSION_KEY . $sessionId;
    // Validation
    // Check to see that the help session exists
    $redisResponse = $redis->exists($helpSessionKey);
    if (!handleRedisError($redisResponse, $app, 'Não foi possível verificar se a sessão de vídeo chat já existe.')) {
        return;
    }
    $exists = (bool) $redisResponse;
    if (!$exists) {
        $app->response->setStatus(400);
        $app->response->setBody('Uma session_id inválida foi criada.');
        return;
    }
    // Add the help session to the queue
    $redisResponse = $redis->rpush(HELP_QUEUE_KEY, $helpSessionKey);
    if (!handleRedisError($redisResponse, $app, 'Não foi possível adicionar a sessão à fila de atendimento.')) {
        return;
    }
    $queueId = $helpSessionKey;
Esempio n. 9
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/ClashAPI/API.class.php';
date_default_timezone_set('Europe/Berlin');
$redis = new Predis\Client(getenv('REDIS_URL'));
if ($redis->exists('timer')) {
    echo 'Just wait another hour...';
} else {
    $timestamp = date("d.m.Y - H:i");
    $clan = new CoC_Clan("#QVQRYYG");
    $tottroph = 0;
    $totlvl = 0;
    foreach ($clan->getAllMembers() as $clanmember) {
        $member = new CoC_Member($clanmember);
        $league = new CoC_League($member->getLeague());
        $donationsReceivedCalc = $member->getDonationsReceived();
        if ($donationsReceivedCalc == 0) {
            $donationsReceivedCalc++;
        }
        $ratio = $member->getDonations() / $donationsReceivedCalc;
        $tottroph = $tottroph + $member->getTrophies();
        $totlvl = $totlvl + $member->getLevel();
        $clanmem[$member->getClanRank()] = ["rank" => $member->getClanRank(), "prevrank" => $member->getPreviousClanRank(), "name" => $member->getName(), "role" => $member->getRole(), "trophies" => $member->getTrophies(), "donations" => $member->getDonations(), "received" => $member->getDonationsReceived(), "ratio" => number_format($ratio, 2), "level" => $member->getLevel(), "leaguename" => $league->getLeagueName(), "leagueid" => $league->getLeagueId(), "leagueicontn" => $league->getLeagueIcon("tiny"), "leagueiconsm" => $league->getLeagueIcon("small"), "leagueiconmd" => $league->getLeagueIcon("medium")];
    }
    $avgtroph = round($tottroph / $clan->getMemberCount(), 0);
    $avglvl = round($totlvl / $clan->getMemberCount(), 0);
    $clandetails = ["badgesm" => $clan->getBadgeUrl("small"), "badgemd" => $clan->getBadgeUrl("medium"), "badgelg" => $clan->getBadgeUrl("large"), "name" => $clan->getName(), "level" => $clan->getLevel(), "description" => $clan->getDescription(), "wins" => $clan->getWarWins(), "ties" => $clan->getWarTies(), "losses" => $clan->getWarLosses(), "streak" => $clan->getWarWinStreak(), "points" => $clan->getPoints(), "freq" => $clan->getWarFrequency(), "membercount" => $clan->getMemberCount(), "avgtroph" => $avgtroph, "avglvl" => $avglvl, "timestamp" => $timestamp];
    $redis->set('clandetails', serialize($clandetails));
    $redis->set('clanmem', serialize($clanmem));
    $redis->setEx('timer', 5400, '');
 /**
  * Retrieve object from cache.
  *
  * Gets an object from cache based on $key and $group.
  *
  * @param   string        $key        The key under which to store the value.
  * @param   string        $group      The group value appended to the $key.
  * @return  bool|mixed                Cached object value.
  */
 public function get($key, $group = 'default')
 {
     $derived_key = $this->build_key($key, $group);
     if (in_array($group, $this->no_redis_groups) || !$this->can_redis()) {
         if (isset($this->cache[$derived_key])) {
             $this->cache_hits++;
             return is_object($this->cache[$derived_key]) ? clone $this->cache[$derived_key] : $this->cache[$derived_key];
         } else {
             $this->cache_misses++;
             return false;
         }
     }
     if ($this->redis->exists($derived_key)) {
         $this->cache_hits++;
         $value = $this->redis->get($derived_key);
     } else {
         $this->cache_misses;
         return false;
     }
     $this->add_to_internal_cache($derived_key, $value);
     return is_object($value) ? clone $value : $value;
 }
Esempio n. 11
0
 if (empty($content)) {
     $result['status'] = 0;
     $result['msg'] = '这条可怜的消息木有了,再来一发吧';
     echo json_encode($result);
     exit;
 }
 $subject = '';
 $return = 0;
 if ($touid) {
     $return = uc_pm_send($_SGLOBAL['supe_uid'], $touid, $subject, $content, 1, $pmid, 0);
     if ($return > 0) {
         require 'Predis/Autoloader.php';
         Predis\Autoloader::register();
         $client = new Predis\Client();
         $keyT = 'ihome_T' . $touid;
         if ($client->exists($keyT)) {
             $keyR = 'ihome_R' . $touid;
             if ($client->exists($keyR)) {
                 $value = intval($client->get($keyR));
                 $return = $value > $return ? $value : $return;
             }
             $client->set($keyR, $return);
         }
         smail($touid, '', cplang('friend_pm', array($_SN[$space['uid']], getsiteurl() . 'space.php?do=pm')), '', 'friend_pm');
     }
 } else {
     $result['status'] = 0;
     $result['msg'] = '自言自语是不对滴~';
     echo json_encode($result);
     exit;
 }
Esempio n. 12
0
/**
* AJAX Gateway
*
* This is the long description for a DocBlock. This text may contain
* multiple lines and even some _markdown_.
*
* * Markdown style lists function too
* * Just try this out once
*
* The section after the long description contains the tags; which provide
* structured meta-data concerning the given element.
*
* @since 0.0.1
* @package jCore
* 
*/
function ajaxGateway()
{
    /*
     * Sanitizes res id.
     *
     * Removes all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=
     */
    $resId = filter_input(INPUT_GET | INPUT_POST, "res", FILTER_SANITIZE_URL);
    $batchPullRequest = array();
    if (isset($_POST['pull'])) {
        $batchPullRequest = json_decode($_POST['pull']);
    }
    //error_log(print_r($batchPullRequest, 1));
    $batchResponse = array();
    try {
        require_once JCORE_PROJECT . "libs/php/predis/autoload.php";
        Predis\Autoloader::register();
        require_once 'db-connect.php';
        //	$redis = new Predis\Client();
        $redis = new Predis\Client(array("scheme" => DB_SCHEME, "host" => DB_HOST, "port" => DB_PORT, "password" => DB_PASSWORD));
        //	$redis->set('/hello-world', 'Hello, jCore!');
        // "Successfully connected to Redis";
        // Since we connect to default setting localhost and 6379 port there is no need for extra configuration.
        // If not then you can specify the scheme, host and port to connect as an array to the constructor.
        //
        require_once "sha256.inc.php";
        foreach ($batchPullRequest as $uri => $pullRequest) {
            $resource = array();
            // Look up uri in redis.
            $resourcePrefix = '/jc/resources';
            $resKey = $resourcePrefix . $uri;
            if ($redis->exists($resKey)) {
                $value = $redis->get($resKey);
                if (isset($pullRequest->value)) {
                    $clientRes = json_encode($pullRequest->value);
                    $serverRes = $value;
                    // Compare resource values.
                    if (strcasecmp($clientRes, $serverRes) != 0) {
                        $resource['value'] = $value;
                    } else {
                        $resource['_'] = JC_NO_ERROR;
                    }
                } else {
                    if (isset($pullRequest->hash)) {
                        $clientRes = $pullRequest->hash;
                        // Without caching.
                        $hash = hash('sha256', $value);
                        /*
                        					// With caching.
                        					// Get the server-side hash, generating one if it hasn't been cached.
                        					// This only works if the only resource changes are going through the jCore gateway.
                        					// Otherwise, we have to assume that resources might have been changed since 
                        					// last we checked.
                        					$hashPrefix = '/jc/hashes';
                        					$hashKey = $hashPrefix.$uri;
                        					$hash = '';
                        
                        					if ($redis->exists($hashKey)) {
                        						// Server-side hash exists.
                        						$hash = $redis->get($hashKey);
                        					}
                        					else {
                        						// Server-side hash doesn't exist and needs to be generated.
                        						$hash = hash('sha256', $value);
                        						$redis->set($hashKey, $hash);
                        					}
                        */
                        $serverRes = $hash;
                        // Compare resource values.
                        if (strcasecmp($clientRes, $serverRes) != 0) {
                            $resource['value'] = $value;
                        } else {
                            $resource['_'] = JC_NO_ERROR;
                        }
                    } else {
                        // No value or hash means this is an improperly formed request.
                        $resource['_'] = JC_INVALID_REQUEST;
                    }
                }
            } else {
                // Specified uri does not exist.
                $resource['_'] = HTTP_NOT_FOUND;
            }
            $batchResponse[$uri] = $resource;
        }
    } catch (Exception $e) {
        //	echo "Couldn't connect to Redis";
        $batchResponse['_'] = JC_DB_CONNECT_ERROR . ' Could not connect to database';
        $batchResponse['desc'] = $e->getMessage();
    }
    //error_log(print_r($batchResponse, 1));
    // This should be the only thing we echo on this page.
    echo json_encode($batchResponse);
    exit(0);
}
Esempio n. 13
0
<?php

require "/opt/app-root/src/predis/autoload.php";
Predis\Autoloader::register();
// since we connect to default setting localhost
// and 6379 port there is no need for extra
// configuration. If not then you can specify the
// scheme, host and port to connect as an array
// to the constructor.
try {
    //    $redis = new Predis\Client();
    $redis = new Predis\Client(array("scheme" => "tcp", "host" => "172.30.104.84", "port" => 6379));
    echo "Successfully connected to Redis";
    $redis->set("hello_world", "Hi from php!");
    $value = $redis->get("hello_world");
    var_dump($value);
    echo $redis->exists("Santa Claus") ? "true" : "false";
} catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}
Esempio n. 14
0
header("Cache-Control: private, max-age={$seconds_of_caching}");
header("Expires: " . gmdate('r', time() + $seconds_of_caching));
$con = mysqli_connect("host", "username", "password", "dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con, 'SET CHARACTER SET utf8');
//a single quote could break the json
include "predis.php";
//php version 5.3+
$redis = new Predis\Client('');
// require_once("predis5.2.php");   //use this if you are using php version 5.2 or lower
// $redis = new Predis_Client();
$redis_key = md5('someUniqueRandomString');
if ($redis->exists($redis_key)) {
    //if it exists display the cache to the user
    $cache = $redis->get($redis_key);
    echo $cache;
    mysqli_close($con);
    exit;
} else {
    //did not find the cache in redis, lets fetch the catch
    $rs = array();
    /*your query should be whatever images you want to pull in for the screen saver. 
         This query specifically looks for posts that have over 800 likes on Facebook
      */
    $result = mysqli_query($con, "SELECT ID,post_title,post_content FROM wp_jthmm2_posts,wp_jthmm2_postmeta WHERE post_type = 'post' AND post_status = 'publish' and  wp_jthmm2_posts.ID=wp_jthmm2_postmeta.post_id and wp_jthmm2_postmeta.meta_key ='_mn_fb_likes' and wp_jthmm2_postmeta.meta_value > 800 order by rand() LIMIT 40 ");
    while ($row = mysqli_fetch_assoc($result)) {
        $tmp = array();
        $content = $row['post_content'];
Esempio n. 15
0
<?php

/* 
* =====================================
* Website: http://netkiller.github.com
* Author: neo <*****@*****.**>
* Email: netkiller@msn.com
* =====================================
*/
require 'SharedConfigurations.php';
$single_server = array('host' => '127.0.0.1', 'port' => 6379, 'database' => 0);
$multiple_servers = array(array('host' => '127.0.0.1', 'port' => 6379, 'database' => 15, 'alias' => 'first'), array('host' => '127.0.0.1', 'port' => 6380, 'database' => 15, 'alias' => 'second'));
$client = new Predis\Client($single_server, array('prefix' => 'fw:'));
$key = $_SERVER['REMOTE_ADDR'];
if (!$client->exists($key)) {
    $client->setex($key, 20, 1);
} else {
    $client->incrby($key, 1);
}
$counter = $client->get($key);
if ($counter > 10) {
    echo 'Deny';
}
print_r($client->get($key));
//var_dump($client->keys('*'));