function clear_wp_redis_cache() { include_once "predis5.2.php"; //we need this to use Redis inside of PHP $args = array('post_type' => 'any', 'posts_per_page' => -1); $wp_query = new WP_Query($args); // to get all Posts $redis = new Predis_Client(); // Loop all posts and clear the cache $i = 0; while ($wp_query->have_posts()) { $wp_query->the_post(); $incremented = false; $permalink = get_permalink(); $redis_key = md5($permalink); $redis_ssl_key = 'ssl_' . $redis_key; if ($redis->exists($redis_key) == true) { $redis->del($redis_key); $i++; $incremented = true; } if ($redis->exists($redis_ssl_key) == true) { $redis->del($redis_ssl_key); if (!$incremented) { $i++; } } } echo $i . " of " . $wp_query->found_posts . " posts was cleared in cache"; die; }
protected function Write($desc, $data) { try { $obj = new stdClass(); $obj->group = $this->group; $obj->desc = $desc; $obj->time = microtime(); $obj->data = $data; $time = time(); $md5 = md5($this->group); $guid = $this->GetGuid(); /* @var $p Predis_CommandPipeline */ $p = $this->predis->pipeline(); $p->hset($this->redis_prefix . '.groups.name', $md5, $this->group); $p->hset($this->redis_prefix . '.groups.last', $md5, $time); if (!$this->requestStarted) { $p->lpush($this->redis_prefix . '.group:' . $md5 . '.log', $guid); $details = array(); $details['start'] = microtime(true); if (isset($_SERVER['REQUEST_URI'])) { $details['url'] = $_SERVER['REQUEST_URI']; $details['method'] = $_SERVER['REQUEST_METHOD']; $details['ip'] = $_SERVER['REMOTE_HOST']; } $p->set($this->redis_prefix . '.group:' . $md5 . '.request:' . $guid . '.details', json_encode($details)); $this->requestStarted = true; } $p->lpush($this->redis_prefix . '.group:' . $md5 . '.request:' . $guid . '.logs', json_encode($data)); $p->execute(); } catch (Exception $ex) { $this->HandleException($ex); } }
/** * __construct function. * * @access public * @param mixed $redisServer * @param mixed $redisPort. (default: 6379) * @return void */ public function __construct() { try { parent::__construct(array('host' => self::REDIS_HOST, 'port' => self::REDIS_PORT, 'database' => self::REDIS_DB, 'password' => self::REDIS_PASSWORD)); } catch (Exception $e) { $this->redisError = $e->getMessage() . '- Initial Conection'; } }
/** * Required to pass unit tests * * @param string $id * @return void */ public function ___expire($id) { $this->_redis->del(self::PREFIX_KEY . $id); }
<?php require 'predis/lib/Predis.php'; // simple set and get scenario $single_server = array('host' => '10.174.178.235', 'port' => 6379, 'database' => 15); $redis = new Predis_Client($single_server); $retval = $redis->get('user_data'); /* $raw = gzuncompress($retval); $document = json_decode($raw, true); $document['TWIDDLE'] = mt_rand(0, 10000); for($i = 0; $i < 100; $i++){ for($j = 0; $j < 100; $j++){ $k = sin($i) * tan($j); } } */ //echo "Len: " . strlen($raw) . " new val : " . $document['TWIDDLE']; //print_r(json_encode($document)); //$retval = $redis->set('user_data', gzcompress(json_encode($document))); $redis->set('user_data', $retval); echo "OK\n"; //print_r($retval);
public static function zsetAddAndReturn(Predis_Client $client, $keyName, array $values, $wipeOut = 0) { // $values: array(SCORE => VALUE, ...); if ($wipeOut == true) { $client->del($keyName); } foreach ($values as $value => $score) { $client->zadd($keyName, $score, $value); } return $values; }
<?php require_once 'SharedConfigurations.php'; // When you have a whole set of consecutive commands to send to // a redis server, you can use a pipeline to improve performances. $redis = new Predis_Client($single_server); $pipe = $redis->pipeline(); $pipe->ping(); $pipe->flushdb(); $pipe->incrby('counter', 10); $pipe->incrby('counter', 30); $pipe->exists('counter'); $pipe->get('counter'); $pipe->mget('does_not_exist', 'counter'); $replies = $pipe->execute(); print_r($replies); /* OUTPUT: Array ( [0] => 1 [1] => 1 [2] => 10 [3] => 40 [4] => 1 [5] => 40 [6] => Array ( [0] => [1] => 40 )
public function getClientFor($connectionAlias) { if (!Predis_Shared_Utils::isCluster($this->_connection)) { throw new Predis_ClientException('This method is supported only when the client is connected to a cluster of connections'); } $connection = $this->_connection->getConnectionById($connectionAlias); if ($connection === null) { throw new InvalidArgumentException("Invalid connection alias: '{$connectionAlias}'"); } $newClient = new Predis_Client(); $newClient->setupClient($this->_options); $newClient->setConnection($this->getConnection($connectionAlias)); return $newClient; }
} } return $newArray; } public function remove($node) { $this->_nodes = self::array_remove($this->_nodes, $node); $this->_nodesCount = count($this->_nodes); } public function get($key) { $count = $this->_nodesCount; if ($count === 0) { throw new RuntimeException('No connections'); } return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0]; } public function generateKey($value) { return crc32($value); } } $options = array('key_distribution' => new NaiveDistributionStrategy()); $redis = new Predis_Client($multiple_servers, $options); for ($i = 0; $i < 100; $i++) { $redis->set("key:{$i}", str_pad($i, 4, '0', 0)); $redis->get("key:{$i}"); } $server1 = $redis->getClientFor('first')->info(); $server2 = $redis->getClientFor('second')->info(); printf("Server '%s' has %d keys while server '%s' has %d keys.\n", 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']);
<?php require_once 'SharedConfigurations.php'; // Redis 2.0 features new commands that allow clients to subscribe for // events published on certain channels (PUBSUB). // Create a client and disable r/w timeout on the socket $redis = new Predis_Client($single_server + array('read_write_timeout' => 0)); // Initialize a new pubsub context $pubsub = $redis->pubSubContext(); // Subscribe to your channels $pubsub->subscribe('control_channel'); $pubsub->subscribe('notifications'); // Start processing the pubsup messages. Open a terminal and use redis-cli // to push messages to the channels. Examples: // ./redis-cli PUBLISH notifications "this is a test" // ./redis-cli PUBLISH control_channel quit_loop foreach ($pubsub as $message) { switch ($message->kind) { case 'subscribe': echo "Subscribed to {$message->channel}\n"; break; case 'message': if ($message->channel == 'control_channel') { if ($message->payload == 'quit_loop') { echo "Aborting pubsub loop...\n"; $pubsub->unsubscribe(); } else { echo "Received an unrecognized command: {$message->payload}.\n"; } } else { echo "Received the following message from {$message->channel}:\n", " {$message->payload}\n\n";
<?php require_once 'SharedConfigurations.php'; // redis can set keys and their relative values in one go // using MSET, then the same values can be retrieved with // a single command using MGET. $mkv = array('usr:0001' => 'First user', 'usr:0002' => 'Second user', 'usr:0003' => 'Third user'); $redis = new Predis_Client($single_server); $redis->mset($mkv); $retval = $redis->mget(array_keys($mkv)); print_r($retval); /* OUTPUT: Array ( [0] => First user [1] => Second user [2] => Third user ) */
<?php require_once 'SharedConfigurations.php'; // simple set and get scenario $redis = new Predis_Client($single_server); $redis->set('library', 'predis'); $retval = $redis->get('library'); print_r($retval); /* OUTPUT predis */
function redis() { return Predis_Client::GetInstance(); }
<?php require '../php/predis/lib/Predis.php'; //$document = json_decode(file_get_contents("tiny.json"), true); $document = json_decode(file_get_contents("document.json"), true); // simple set and get scenario $single_server = array('host' => '10.174.178.235', 'port' => 6379, 'database' => 0); $redis = new Predis_Client($single_server); //print_r($document); $redis->set('user_data_node', json_encode($document)); //print_r($retval);
/** * Optimized getMany with Redis mget method * * @param array $keys * @access public * @return array */ public function getMany($keys) { $cache_keys = array_map(array($this, 'getKey'), $keys); return array_combine($keys, $this->redis->getMultiple($cache_keys)); }
$redis = new Redis(); // Sockets can be used as well. Documentation @ https://github.com/nicolasff/phpredis/#connection $redis->connect($redis_server); } else { // Fallback to predis5.2.php if ($debug) { echo "<!-- using predis as a backup -->\n"; } include_once dirname($wp_blog_header_path) . "/wp-content/plugins/wp-redis-cache/predis5.2.php"; //we need this to use Redis inside of PHP // try the client first try { if ($sockets) { $redis = new Predis_Client(array('scheme' => 'unix', 'path' => $redis_server)); } else { $redis = new Predis_Client(); } } catch (Predis_ClientException $e) { // catch predis-thrown exception die("Predis not found on your server or was unable to run. Error message: " . $e->getMessage()); } catch (Exception $e) { // catch other exceptions require $wp_blog_header_path; die("Error occurred. Error message: " . $e->getMessage()); } } //Either manual refresh cache by adding ?refresh=secret_string after the URL or somebody posting a comment if (refreshHasSecret($secret_string) || requestHasSecret($secret_string) || isRemotePageLoad($current_url, $websiteIp)) { if ($debug) { echo "<!-- manual refresh was required -->\n"; }
<?php require '../php/predis/lib/Predis.php'; // simple set and get scenario $single_server = array('host' => '10.174.178.235', 'port' => 6379, 'database' => 0); $redis = new Predis_Client($single_server); $result = $redis->get('user_data_2'); echo strlen($result) . "\n";
function do_header($title, $id = 'home') { global $current_user, $dblang, $globals, $greetings, $db; // escolhe norma $stdRow = false; // if change by request if ($_REQUEST['standard']) { $stdRow = $globals['standards'][$_REQUEST['standard']]; if ($current_user->authenticated) { // authenticated users store that in their profile $user = new User($current_user->user_id); $user->standard = (int) $_REQUEST['standard']; $user->store(); } else { // if not authenticated, store on cookie setcookie("chuza_current_standard", (int) $_REQUEST['standard'], time() + 3600 * 24 * 365 * 3); // 3 anos de cookie } } elseif ($current_user->authenticated) { // user authenticated but NOT request change $stdRow = $globals['standards'][(int) $current_user->standard]; } else { // set default standard for non authenticated users // search in redis $check_ip = $globals['user_ip_int']; $redis = new Predis_Client(); $r = $redis->zrevrangebyscore($globals['enviroment'] . 'ips', $check_ip, '0', 'WITHSCORES', 'LIMIT', '0', '1'); preg_match('/(^[^-]*)/', $r[0], $matches); if (in_array($matches[0], $globals['lusophonia'])) { $stdRow = 1; } else { if (!$_COOKIE['chuza_current_standard']) { $_COOKIE['chuza_current_standard'] = 1; } $stdRow = $globals['standards'][$_COOKIE['chuza_current_standard']]; } } if ($stdRow) { putenv('LANGUAGE=' . $stdRow['short_name']); setlocale(LC_MESSAGES, $stdRow['short_name']); $current_user->standard = $stdRow['id']; } else { // default standard putenv('LANGUAGE=gl_ES.utf8'); setlocale(LC_MESSAGES, 'gl_ES.utf8'); $current_user->standard = 1; } bindtextdomain('meneame', mnminclude . '/languages'); textdomain('meneame'); // fim de escolher norma check_auth_page(); header('Content-Type: text/html; charset=utf-8'); http_cache(); if (!empty($globals['link_id'])) { // Pingback autodiscovery // http://www.hixie.ch/specs/pingback/pingback header('X-Pingback: http://' . get_server_name() . $globals['base_url'] . 'xmlrpc.php'); } echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n"; //echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n"; echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $dblang . '" lang="' . $dblang . '">' . "\n"; echo '<head>' . "\n"; echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n"; echo '<meta name="ROBOTS" content="NOARCHIVE" />' . "\n"; echo "<title>{$title}</title>\n"; do_css_includes(); echo '<meta name="generator" content="meneame" />' . "\n"; if ($globals['noindex']) { echo '<meta name="robots" content="noindex,follow"/>' . "\n"; } if ($globals['tags']) { echo '<meta name="keywords" content="' . $globals['tags'] . '" />' . "\n"; } if ($globals['description']) { echo '<meta name="description" content="' . $globals['description'] . '" />' . "\n"; } if ($globals['link']) { echo '<link rel="pingback" href="http://' . get_server_name() . $globals['base_url'] . 'xmlrpc.php"/>' . "\n"; } echo '<link rel="microsummary" type="application/x.microsummary+xml" href="' . $globals['base_url'] . 'microsummary.xml" />' . "\n"; echo '<link rel="search" type="application/opensearchdescription+xml" title="' . _("menéame search") . '" href="http://' . get_server_name() . $globals['base_url'] . 'opensearch_plugin.php"/>' . "\n"; echo '<link rel="alternate" type="application/rss+xml" title="' . _('publicadas') . '" href="http://' . get_server_name() . $globals['base_url'] . 'rss2.php" />' . "\n"; echo '<link rel="alternate" type="application/rss+xml" title="' . _('pendientes') . '" href="http://' . get_server_name() . $globals['base_url'] . 'rss2.php?status=queued" />' . "\n"; echo '<link rel="alternate" type="application/rss+xml" title="' . _('comentarios') . '" href="http://' . get_server_name() . $globals['base_url'] . 'comments_rss2.php" />' . "\n"; if (!$globals['favicon']) { $globals['favicon'] = 'favicon.ico'; } echo '<link rel="shortcut icon" href="' . $globals['base_static'] . $globals['favicon'] . '" type="image/x-icon"/>' . "\n"; do_js_includes(); if ($globals['thumbnail']) { // WARN: It's assumed a thumbanil comes with base_url included $thumb = $globals['thumbnail']; } else { $thumb = 'http://' . get_static_server_name() . $globals['base_url'] . $globals['thumbnail_logo']; } echo '<meta name="thumbnail_url" content="' . $thumb . "\"/>\n"; echo '<link rel="image_src" href="' . $thumb . "\"/>\n"; if ($globals['extra_head']) { echo $globals['extra_head']; } echo '</head>' . "\n"; echo "<body id=\"{$id}\" " . $globals['body_args'] . ">\n"; if ($globals["news"]) { echo '<div style="background-color:red;padding:8px;font-color:white;font-weigth:bold;" >' . $globals["news"] . '</div>'; } echo '<div id="wrap">' . "\n"; echo '<div id="header">' . "\n"; echo '<a href="' . $globals['base_url'] . '" title="' . _('inicio') . '" id="logo">' . _("menéame") . '</a>' . "\n"; echo '<ul id="headtools">' . "\n"; // Main search form echo '<li class="searchbox">' . "\n"; echo '<form action="' . $globals['base_url'] . 'search.php" method="get" name="top_search">' . "\n"; echo '<img src="' . $globals['base_static'] . 'img/common/search-left-04.png" width="6" height="22" alt=""/>'; if (!empty($_REQUEST['q'])) { echo '<input type="text" name="q" value="' . htmlspecialchars($_REQUEST['q']) . '" />'; } else { echo '<input name="q" value="' . _('buscar') . '..." type="text" onblur="if(this.value==\'\') this.value=\'' . _('buscar') . '...\';" onfocus="if(this.value==\'' . _('buscar') . '...\') this.value=\'\';"/>'; } echo '<a href="javascript:document.top_search.submit()"><img class="searchIcon" alt="' . _('buscar') . '" src="' . $globals['base_static'] . 'img/common/search-04.png" id="submit_image" width="28" height="22"/></a>' . "\n"; if ($globals['search_options']) { foreach ($globals['search_options'] as $name => $value) { echo '<input type="hidden" name="' . $name . '" value="' . $value . '"/>' . "\n"; } } echo '</form>'; echo '</li>' . "\n"; // form echo '<li><a href="' . $globals["base_url"] . 'equipa/index.php?page=axuda">' . _('ayuda') . ' <img src="' . $globals['base_static'] . 'img/common/help-bt-02.png" alt="help button" title="' . _('ayuda') . '" width="13" height="16" /></a></li>'; echo '<li><a href="' . $globals["base_url"] . 'equipa/index.php?page=o-novo-chuza">O novo chuza</a></li>'; if ($globals["show_blog"]) { echo '<li><a href="' . $globals["base_url"] . 'blog">blog</a></li>'; } if ($globals["show_wiki"]) { echo '<li><a href="' . $globals["base_url"] . 'wiki">wiki</a></li>'; } if ($current_user->admin) { echo '<li><a href="' . $globals['base_url'] . 'admin/bans.php">admin <img src="' . $globals['base_static'] . 'img/common/tools-bt-02.png" alt="tools button" title="herramientas" width="16" height="16" /> </a></li>' . "\n"; } // choose standard change link $next_standard = $current_user->standard % count($globals['standards']) + 1; $this_page = basename($_SERVER['REQUEST_URL']); if (strpos($this_page, "?") !== false) { $this_page = reset(explode("?", $this_page)); } //echo '<li><a href="'.$this_page.'?standard='.$next_standard.'" >'.$globals['standards'][$current_user->standard]['name'].'</a></li>'."\n"; echo '<li><a href="' . $this_page . '?standard=' . $next_standard . '" >' . $globals['standards'][$next_standard]['name'] . '</a></li>' . "\n"; if ($current_user->authenticated) { //$randhello = array_rand($greetings, 1); // deprecated in Chuza echo '<li><a href="' . get_user_uri($current_user->user_login) . '" title="' . _('Ver perfil de usuario') . '">' . ' ' . $current_user->user_login . ' <img src="' . get_avatar_url($current_user->user_id, $current_user->user_avatar, 20) . '" width="20" height="20" alt="' . $current_user->user_login . '"/></a></li>' . "\n"; echo '<li><a href="' . $globals['base_url'] . 'login.php?op=logout&return=' . urlencode($_SERVER['REQUEST_URI']) . '">' . _('cerrar sesión') . ' <img src="' . $globals['base_static'] . 'img/common/logout-bt-02.png" alt="" title="logout" width="22" height="16" /></a></li>' . "\n"; } else { echo '<li><a href="' . $globals['base_url'] . 'register.php">' . _('registrarse') . ' <img src="' . $globals['base_static'] . 'img/common/register-bt-02.png" alt="" title="register" width="16" height="18" /></a></li>' . "\n"; echo '<li><a href="' . $globals['base_url'] . 'login.php?return=' . urlencode($_SERVER['REQUEST_URI']) . '">' . _('login') . ' <img src="' . $globals['base_static'] . 'img/common/login-bt-02.png" alt="" title="login" width="22" height="16" /></a></li>' . "\n"; } //echo '<li><a href="'.$globals['base_url'].'faq-'.$dblang.'.php">' . _('acerca de menéame').'</a></li>' . "\n"; $s = $_SERVER['SCRIPT_NAME']; $matches = array(); preg_match('/\\/([^\\/]*)$/', $s, $matches); switch ($matches[1]) { case "topstories.php": $classTopstories = "enfatized"; break; case "index.php": $classCover = "enfatized"; break; case "shakeit.php": $classPendent = "enfatized"; break; case "sneak.php": $classSneak = "enfatized"; break; } if (strpos($_SERVER['REQUEST_URI'], 'chios') !== FALSE) { $classChios = "enfatized"; $classCover = ""; // previously assigned wrongly } echo '</ul>' . "\n"; echo '</div>' . "\n"; echo '<div id="newnavbar" >' . "\n"; echo '<ul class="first">' . "\n"; //echo '<li style=""><a href="'.$globals['base_url'].'shakeit.php">'._('pendientes').'</a></li>'."\n"; echo '<li class="' . $classCover . '"><a href="' . $globals['base_url'] . '">' . _('portada') . '</a></li>' . "\n"; echo '<li class="' . $classPendent . '"><a href="' . $globals['base_url'] . 'shakeit.php">' . _('pendientes') . '</a></li>' . "\n"; echo '<li class="' . $classTopstories . '"><a href="' . $globals['base_url'] . 'topstories.php">' . _('Populares') . '</a></li>' . "\n"; //Novas populares echo '<li class="' . $classSneak . '"><a href="' . $globals['base_url'] . 'sneak.php">' . _('fisgona') . '</a></li>' . "\n"; echo '<li class="' . $classChios . '" ><a href="' . $globals['base_url'] . 'chios/">' . _('nótame') . '</a></li>' . "\n"; echo '<li id="lastlititle" ><a href="' . $globals['base_url'] . 'equipa/?page=calendario">' . _('calendario') . '</a></li>' . "\n"; echo '</ul>'; echo '<ul class="last">' . "\n"; if ($current_user->user_login) { $u = get_user_uri($current_user->user_login, 'categories'); echo '<li><a href="' . $u . '">' . _('personalizar') . '</a></li>' . "\n"; echo '<li><a href="' . $globals['base_url'] . 'submit.php">' . _('enviar noticia') . '</a></li>' . "\n"; } //echo '<li style=""><a href="'.$globals['base_url'].'shakeit.php">'._('pendientes').'</a></li>'."\n"; //echo '<li><a href="'.$globals['base_url'].'sneak.php">'._('fisgona').'</a></li>'."\n"; //echo '<li><a href="'.$globals['base_url'].'chios/">'._('nótame').'</a></li>'."\n"; echo '</ul>'; echo ' </div>' . "\n"; //do_banner_top(); echo '<div id="container">' . "\n"; }
private function checkCapabilities(Predis_Client $redisClient) { if (Predis_Shared_Utils::isCluster($redisClient->getConnection())) { throw new Predis_ClientException('Cannot initialize a PUB/SUB context over a cluster of connections'); } $profile = $redisClient->getProfile(); $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe'); if ($profile->supportsCommands($commands) === false) { throw new Predis_ClientException('The current profile does not support PUB/SUB related commands'); } }
<?php // get ip table from http://software77.net/geo-ip/ include '../config.php'; include mnminclude . 'external_post.php'; include_once mnminclude . 'log.php'; include_once mnminclude . 'ban.php'; include_once mnminclude . '/predis/Predis.php'; include_once mnminclude . '/predis/Predis_Compatibility.php'; $redis = new Predis_Client(); $TYPE = 2; $file = "IpToCountry.csv"; echo "<pre>"; $f = fopen($file, "r"); $iptable = array(); $k = 0; while ($csv = fgetcsv($f, 255)) { if ($csv[0][0] != '#') { print_r($csv[0] . $csv[6] . "/n"); $redis->zadd($globals['enviroment'] . 'ips', $csv[0], $csv[6] . '-' . $k); $k++; } else { } } fclose($f); die; print_r($iptable[0]); print_r($iptable[1]); print_r($iptable[2]); switch ($TYPE) { case 1: