Exemple #1
0
 public function load($group_name = 'default')
 {
     $obj_couchbase_name = 'MYCOUCHBASE' . $group_name;
     if ($this->{$obj_couchbase_name}) {
         return $this->{$obj_couchbase_name};
     }
     $cfg = $this->cfg[$group_name];
     $this->CI->load->library('monitor');
     $random = FALSE;
     if (is_array($cfg) === FALSE) {
         log_message('error', 'The Memcached config is not array');
         exit;
     }
     $this->CI->load->library('monitor');
     $random = FALSE;
     if ($cfg['cfg']['random'] == TRUE) {
         $random = TRUE;
     }
     if ($random === TRUE) {
         $this->CI->load->helper('random');
         $fail = array();
         getCouchbase:
         $rnd = randomExcept(0, count($cfg['data']) - 1, $fail);
         if (is_numeric($rnd)) {
             if ($this->CI->monitor->check_status('COUCHBASE', array('position' => $rnd, 'group' => $group_name)) === true) {
                 $couchbase_position = $rnd;
             } else {
                 $fail[] = $rnd;
                 goto getCouchbase;
             }
         }
     } else {
         for ($i = 0, $c = count($cfg['data']); $i < $c; $i++) {
             if ($this->CI->monitor->check_status('COUCHBASE', array('position' => $i, 'group' => $group_name)) === true) {
                 $couchbase_position = $i;
                 break;
             }
         }
     }
     if ($cfg['data'][$couchbase_position]) {
         $cbcfg = $cfg['data'][$couchbase_position];
         $status = TRUE;
     } else {
         $status = FALSE;
     }
     if (is_array($cbcfg)) {
         $cb = new Couchbase($cbcfg['ip'], $cbcfg['username'], $cbcfg['password'], $cbcfg['db_name']);
         if ($cb->getResultCode() != COUCHBASE_SUCCESS) {
             $this->CI->monitor->increment_fail('COUCHBASE', array('position' => $couchbase_position, 'group' => $group_name));
             $cb = new CouchBaseInterface();
         }
         $this->{$obj_couchbase_name} = $cb;
     } else {
         $cb = new CouchBaseInterface();
     }
     return $cb;
 }
Exemple #2
0
 public static function setUpBeforeClass()
 {
     if (!extension_loaded('couchbase') || !class_exists('Couchbase')) {
         static::$cache = null;
         return;
     }
     $couchbase = new \Couchbase('127.0.0.1', '', '', 'cachalot-test');
     $couchbase->flush();
     static::$cache = new \Cachalot\CouchbaseCache($couchbase);
 }
 /**
  * Return an array of Document from a Couchbase view.
  *
  * @see Couchbase::view
  *
  * @SuppressWarnings(PHPMD.StaticAccess)
  */
 public function view($document, $view = '', $options = array(), $returnErrors = false)
 {
     $cbResults = $this->connection->view($document, $view, $options, $returnErrors);
     if (0 == $cbResults['total_rows']) {
         return array();
     }
     // Convert couchbase raw results to Document collection
     $func = function ($rawResult) {
         return new Document($rawResult['id'], $rawResult['value']);
     };
     return array_map($func, $cbResults['rows']);
 }
 /**
  * Utility function that waits for bucket creation.
  * Bucket creation is async, for the time being, we need to poll until
  * it is there.
  * @param Couchbase $cb Couchbase client library object.
  * @param constant Expected memcached result code.
  */
 function _waitForBucket($cb, $resultCode = Memcached::RES_SUCCESS)
 {
     // var_dump("--waitForBucket");
     do {
         $cb->set("f", 1);
         usleep(500000);
         // 1/2 second
         // var_dump($cb->getResultMessage());
     } while ($cb->getResultCode() !== $resultCode);
     $cb->delete("f");
     // var_dump("--done waiting");
 }
 /**
  * {@inheritDoc}
  */
 public function find($storageName, $key)
 {
     $value = $this->client->get($key);
     if ($value === null) {
         throw new NotFoundException();
     }
     return $value;
 }
Exemple #6
0
 /**
  * Deletes all cache entries
  *
  * @return bool
  */
 public function clear()
 {
     try {
         return $this->cache->flush();
     } catch (\CouchbaseException $e) {
         return false;
     }
 }
 /**
  * @param int|string $sessionId
  *
  * @return bool
  */
 public function destroy($sessionId)
 {
     $key = $this->keyPrefix . $sessionId;
     $startTime = microtime(true);
     $result = $this->connection->delete($key);
     $this->newRelicApi->addCustomMetric(self::METRIC_SESSION_DELETE_TIME, microtime(true) - $startTime);
     return true;
 }
<?php

echo "--------------------------------------------------------------------------\n";
echo "\t Couchbase Atomic Counters\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
echo "Set Counter to 0\n";
$cb->set("counter", 0);
echo "Get counter: ";
echo $cb->get("counter");
echo "\n";
$cb->increment("counter");
echo "Get counter: ";
echo $cb->get("counter");
echo "\n";
echo "Increment by 10\n";
$cb->increment("counter", 10);
echo "Get counter: ";
echo $cb->get("counter");
echo "\n";
echo "\nDelete the counter\n";
$cb->delete("counter");
echo "\nInit the value to 10\n";
// create an set an initial
$cb->increment("counter", 1, true, 0, 10);
echo "Get counter: ";
echo $cb->get("counter");
echo "\n";
// does not decrease below 0
$cb->set("counter", 0);
$cb->decrement("counter");
Exemple #9
0
require_once 'finebase/FineTimer.php';
require_once 'finebase/FineDatasource.php';
require_once 'finebase/FineDatabase.php';
require_once 'finebase/FineNDB.php';
require_once 'finebase/FineCache.php';
const FINEDB_HOST = 'localhost';
const FINEDB_PORT = 11138;
const REDIS_DSN = 'redis://*****:*****@localhost/finedb';
$nbrLoops = 45;
$dataList = array('aaa' => "{\"type\":\"question\",\"ip\":\"\",\"text\":\"<p>Bonjour,\\n<br \\/>Je voudrais savoir qu'elle est la diff\\u00e9rence entre un vitrage de 4:16:4 et un de 4:20:4 (gaz argon en tr\\u00e8s les deux vitres, et l'int\\u00e9r\\u00eat de mettre un vitrage de 6:16:4) ?<\\/p>\\n\\n<p>Merci de vos r\\u00e9ponses<\\/p>\\n\\n<p>Mick<\\/p>\",\"tags\":\"fen\\u00eatre argon double vitrage gaz argon dimension \\u00e9paisseur\"}", 'trululu pouet pouet' => "{\"type\":\"question\",\"ip\":\"2.8.152.24\",\"text\":\"<p>Bonjour,<br \\/>Nous venons d'acheter une maison sur laquelle il reste encore quelques travaux \\u00e0 faire.<br \\/>Nous nous sommes rendu compte qu'il n'y avait pas de grille ou baguette d'a\\u00e9ration aux fen\\u00eatres.D'apr\\u00e8s certaines personnes, ce n'est pas obligatoire, mais \\u00e7a d\\u00e9pend de la maison.<br \\/>Voici un bref r\\u00e9sum\\u00e9 des lieux :<br \\/>Chambre 1 : 1 fen\\u00eatre, pas de grille d'a\\u00e9rationChambre 2 : 1 fen\\u00eatre, 1 salle d'eau ouverte sur la chambre avec VMCSalle de bain : VMCWC : VMCSalon : 1 fen\\u00eatre et une baie vitr\\u00e9e coulissante sans grille d'a\\u00e9ration donnant sur une cuisine am\\u00e9ricaine avec une fen\\u00eatre et une porte fen\\u00eatre sans grille d'a\\u00e9ration non plus, mais VMC et hotte dans la cuisine.<br \\/>Faut-il que l'on rajoute des grilles d'a\\u00e9ration \\u00e0 nos fen\\u00eatres ?<br \\/>Merci pour vos r\\u00e9ponse.<\\/p>\",\"tags\":\"fenetre grille aeration obligatoire\"}", 'foobar' => "{\"type\":\"question\",\"ip\":\"82.225.215.131\",\"text\":\"<p>Bonjour,<\\/p>\\n\\n<p><br \\/>Je souhaite changer les fen\\u00eatres de mon appartement et obtenir ainsi une bonne isolation thermique et phonique et dans le m\\u00eame temps il faut mettre des grilles d'a\\u00e9ration, puisque j'ai une VMC simple flux.Est-ce qu'il existe des fen\\u00eatres avec une isolation phonique et des grilles de ventilations?Merci d'avance pour vos r\\u00e9ponses.<\\/p>\"}", 'Pere Noel' => "{\"type\":\"question\",\"ip\":\"86.193.36.153\",\"text\":\"<p>Bonjour,<\\/p>\\n\\n<p><br \\/>je dois changer des cales anti d\\u00e9gondage sur deux vitrages coulissants en alu datant des ann\\u00e9es 1970. Ceux que je dois changer sont en plastique blanc sans marque mentionn\\u00e9e hormis le chiffre 077.Je n'en connais pas la marque. O\\u00f9 peut on se procurer ces cales svp merci ?<\\/p>\",\"tags\":\"fen\\u00eatre baie vitr\\u00e9e coulissante\"}");
$timer = new FineTimer();
$ndb = FineNDB::factory(REDIS_DSN);
$cache = FineCache::factory(MEMCACHE_DSN);
$couch = new Couchbase('localhost:8091', '', '', 'default');
$db = FineDatabase::factory(MYSQL_DSN);
$mongo = new MongoClient();
$mongodb = $mongo->selectDB('finedb');
// ---------- FineDB
print Ansi::bold("FineDB\n");
$timer->start();
for ($i = 0; $i < $nbrLoops; $i++) {
    foreach ($dataList as $key => $data) {
        $sock = fsockopen(FINEDB_HOST, FINEDB_PORT);
        commandPut($sock, false, false, "{$key}-x{$i}", $data);
        fclose($sock);
    }
}
$timer->stop();
print "PUT ASYNC : " . $timer->getTime() . "\n";
Exemple #10
0
 private function clearCouchbase(\Couchbase $cb)
 {
     $cb->delete('oauth_authorization_codes-new-openid-code');
     $cb->delete('oauth_access_tokens-newtoken');
     $cb->delete('oauth_authorization_codes-newcode');
     $cb->delete('oauth_refresh_tokens-refreshtoken');
 }
Exemple #11
0
<?php

// This example file shows you how to create, get and delete a view
try {
    $cb = new Couchbase("localhost", "Administrator", "asdasd");
    $viewname = "myview";
    $designdoc = "mydesign";
    // Create the map function.
    $func = "function (doc, meta) { emit(meta.id, NULL); }";
    // Create document containing the map function
    $ddoc = json_encode('{"views":{"' . $viewname . '":{"map":"' . $func . '"}}}');
    // Create the design document on the server
    $ret = $cb->setDesignDoc($designdoc, json_decode($ddoc));
    if ($ret) {
        print "View successfully created" . PHP_EOL;
    } else {
        print "Failed to create view: " . $cb->getResultMessage() . PHP_EOL;
    }
    // Try to retrieve the desgin document:
    $ddoc = $cb->getDesignDoc($designdoc);
    print "The design document looks like: " . PHP_EOL;
    var_dump($ddoc);
    // Delete the design document:
    $ret = $cb->deleteDesignDoc($designdoc);
    if ($ret) {
        print "View successfully deleted" . PHP_EOL;
    } else {
        print "Failed to delete view: " . $cb->getResultMessage() . PHP_EOL;
    }
} catch (CouchbaseException $exp) {
    print "Failed to create view: " . $exp->getMessage() . PHP_EOL;
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Non-JSON Ops\n";
echo "--------------------------------------------------------------------------\n";
if (file_exists("./output.jpg")) {
    unlink("./output.jpg");
}
$cb = new Couchbase();
echo "Store Strings, Floats, Integers\n";
$cb->set("store_strings", "The quick brown fox jumped over the lazy dog.", 10);
$cb->set("store_floats", 3.14159265358979, 10);
$cb->set("store_integers", -42, 10);
echo "get 'store_strings => '";
echo $cb->get("store_strings");
echo "\n\n";
echo "get 'store_floats' => ";
echo $cb->get("store_floats");
echo "\n\n";
echo "get 'store_integers' => ";
echo $cb->get("store_integers");
echo "\n\n";
echo "--------------------------------------------------------------------------\n";
echo "Append/Prepend Ops\n";
echo "Create a list, start with one item\n";
$cb->set("mylist", "oranges", 30);
echo "Add an item...\n\n";
$cb->prepend("mylist", "apples,");
echo "Add an item...\n\n";
$cb->append("mylist", ",bananas");
echo "Add an item...\n\n";
Exemple #13
0
 /**
  * @return array
  */
 public function get_stat()
 {
     return $this->Couchbase->getStats();
 }
Exemple #14
0
<?php

$cb = new Couchbase("http://counterstrikevm.cloudapp.net:8091/", "", "", "default");
$email = $_POST["email"];
$password = $_POST["password"];
$password2 = $_POST["confirm"];
//Sanitize DATA HERE
if ($password == $_POST["confirm"]) {
    $user = $cb->get($email);
    if ($user == false) {
        $cb->set($email, $password);
        echo "<SCRIPT LANGUAGE='JavaScript'>\n\t\twindow.alert('Registered!')\n\t\twindow.location.href='http://localhost/';\n\t\t</SCRIPT>";
    } else {
        echo "<SCRIPT LANGUAGE='JavaScript'>\n\t\twindow.alert('User already exist!')\n\t\twindow.location.href='http://localhost/';\n\t\t</SCRIPT>";
    }
} else {
    echo "<SCRIPT LANGUAGE='JavaScript'>\n    window.alert('Password does not match!')\n    window.location.href='http://localhost/';\n    </SCRIPT>";
}
Exemple #15
0
<?php

session_start();
if (!isset($_SESSION["email"])) {
    header("location: index.php");
}
$cb = new Couchbase("http://counterstrikevm.cloudapp.net:8091/", "", "", "default");
$email = $_SESSION["email"];
$password = $cb->get($email);
?>
<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
    <style>
        body        { padding-top:80px; word-wrap:break-word; }
    </style>
</head>
<body>
<div class="container">

    <div class="page-header text-center">
        <h1><span class="fa fa-anchor"></span> Profile Page</h1>
        <a href="logout.php?logout">Sign Out</a>
    </div>

    <div class="row">

        <!-- LOCAL INFORMATION -->
 /**
  * Partial Update: Update/Add individual fields in a JSON Document safely
  * Complete Update: Create/Replace the entire Document,
  *                      the given object is encoded to JSON
  * @param $key Document Identifier
  * @param $obj Either Entire Document object for complete update OR
  *      An array with partial updates as keys where
  *          key is an index for an array otherwise the field name.
  *      Each key is associated with path and val properties.
  *      Path is an array of the field path from the root (doc's parent object) and
  *          Val is the new value of the field.
  * @param $is_partial Boolean to identify a partial update
  * @params $cas, $persist_to, $replicate_to function similar to SET operation
  * @return Boolean true on SUCCESS else false
  */
 public function update($key, $obj, $is_partial = false, $expiry = 0, $persist_to = 0, $replicate_to = 0)
 {
     $counter = 1;
     $n_json = NULL;
     do {
         $v_json = parent::get($key, NULL, $cas);
         if ($obj) {
             if ($is_partial == true) {
                 if (!$cas) {
                     throw new Exception("No existing document for partial update");
                 }
                 $valGet = json_decode($v_json);
                 $val = self::_merge($valGet, $obj);
                 $n_json = json_encode($val);
             } else {
                 $cas = 0;
                 $n_json = json_encode($obj);
             }
         }
         $rv = parent::set($key, $n_json, $expiry, $cas, $persist_to, $replicate_to);
     } while ($rv == false && ++$counter <= $this->max_retries);
     return $rv;
 }
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Views\n";
echo "--------------------------------------------------------------------------\n";
// Create the view as documented here:
// http://www.couchbase.com/docs/couchbase-sdk-php-1.1/tutorial-preparations-cb-server.html
$cb = new Couchbase("127.0.0.1:8091", "", "", "beer-sample");
echo "\n--------------------------------------------------------------------------\n";
$views = $cb->getDesignDoc('brewery');
var_export(json_decode($views));
echo "\n--------------------------------------------------------------------------\n";
echo "Breweries (by_name)\n";
$results = $cb->view("brewery", "by_name", array('limit' => 10));
foreach ($results['rows'] as $row) {
    $doc = $cb->get($row['id']);
    if ($doc) {
        $doc = json_decode($doc, true);
        echo "\nName : ";
        echo $doc["name"];
    }
}
echo "\n--------------------------------------------------------------------------\n";
echo "Breweries (by_name), and output country\n";
$results = $cb->view("brewery", "by_name", array('limit' => 10));
foreach ($results['rows'] as $row) {
    $doc = $cb->get($row['id']);
    if ($doc) {
        $doc = json_decode($doc, true);
        echo "\nname : ";
        echo $doc["name"];
Exemple #18
0
 private function _initCb()
 {
     $this->_cb = new Couchbase();
     $this->_cb->addCouchbaseServer($this->_host, $this->_port, $this->_couchport);
 }
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Retrieval Operations\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
/** 
 * Simple Entity with decode logic.
 */
class Person
{
    public $doctype;
    public $username;
    public $name;
    public $email;
    public $password;
    public $logins;
    public static function fromJSON($json)
    {
        $decoded = json_decode($json, true);
        $person = new Person();
        foreach ($decoded as $type => $value) {
            $person->{$type} = $value;
        }
        return $person;
    }
}
$user_data1 = new Person();
$user_data1->doctype = "learn";
$user_data1->username = "******";
$user_data1->name = "John Smith";
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Storage Operations\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
// Create a key
$cb->set("mytest", 1);
echo "\n--------------\n";
echo "Get mytest: ";
echo $cb->get("mytest");
// try to add a key that exists
$result = $cb->add("mytest", 2);
if ($result) {
    echo "\n--------------\n";
    echo "Add succeeded";
} else {
    echo "\n--------------\n";
    echo "Add failed: key exists";
}
// success
$result = $cb->replace("mytest", 2);
echo "\n--------------\n";
echo "Get mytest: ";
echo $cb->get("mytest");
// try to replace a key that does not exist
$result = $cb->add("mytest4", 2);
if ($result) {
    echo "\n--------------\n";
    echo "Replace succeeded";
} else {
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase JSON Doc Storage\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
$mydoc = array("doctype" => "test", "name" => "John Smith");
echo "Original Document:\n";
var_dump($mydoc);
echo "\nSet Document (Hash -> JSON)\n";
// store a json doc (encode it)
$cb->set("mydoc", json_encode($mydoc));
echo "Retrieve Document (JSON -> Hash), also set a 10 second TTL\n";
// retrieve and decode json doc
$doc = $cb->getAndTouch("mydoc", 10);
echo "\n--------------\n";
echo "JSON String: " . $doc;
echo "\n--------------\n";
var_dump(json_decode($doc, true));
// (as array, not object)
echo "--------------------------------------------------------------------------\n";
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Observe/Durability\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
$user_data1 = new stdClass();
$user_data1->doctype = "learn";
$user_data1->username = "******";
$user_data1->name = "John Smith";
$user_data1->email = "*****@*****.**";
$user_data1->password = "******";
$user_data1->logins = 0;
$key = $user_data1->email;
$document = json_encode($user_data1);
//Store a key, but don't return success until it is written
//to disk on the master (or times out)
echo "\n--------------\n";
echo "Set Document with Observe Asynchronously, Returns when Persisted, and output return values\n";
try {
    $status = $cb->set($key, $document, 0, $cas = "", $persist_to = 1);
    echo "status/cas: {$status}";
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "";
}
//Store a key, but don't return success until it is
//replicated to 2 nodes (or times out)
//will fail on a single or two node cluster
echo "\n--------------\n";
try {
    $status = $cb->set($key, $document, 0, $cas = "", $replicate_to = 2);
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase Connections\n";
echo "--------------------------------------------------------------------------\n";
// Connecto to beer sample bucket
$beers = new Couchbase("127.0.0.1:8091", "", "", "beer-sample");
// Connext to default bucket
$default = new Couchbase();
// will raise an error
$dummy = new Couchbase("127.0.0.1:8091", "beer-sample", "password", "beer-sample");
echo "--- Beers Bucket ---\n";
var_dump($beers->getStats());
//dump some infos from the bucket
echo "\n--- Default Bucket ---\n";
var_dump($default->getStats());
//dump some infos from the bucket
echo "\n--- 'No' Bucket ---\n";
var_dump($dummy->getStats());
//error
echo "--------------------------------------------------------------------------\n";
Exemple #24
0
<?php

$cb = new Couchbase("ec2-50-112-3-209.us-west-2.compute.amazonaws.com:8091");
// uses the default bucket
// or specify a specific bucket like so:
//$cb = new Couchbase("127.0.0.1:8091", "bucket", "pass", "bucket");
$cb->set("rami", 1);
var_dump($cb->get("rami"));
Exemple #25
0
<?php

echo "--------------------------------------------------------------------------\n";
echo "\tCouchbase - Compare and Swap\n";
echo "--------------------------------------------------------------------------\n";
$cb = new Couchbase();
$user_data1 = new stdClass();
$user_data1->doctype = "learn";
$user_data1->username = "******";
$user_data1->name = "John Smith";
$user_data1->email = "*****@*****.**";
$user_data1->password = "******";
$user_data1->logins = 0;
echo "--------------------------------------------------------------------------\n";
echo "Set the Data, then Retrieve Two Copies of the Document\n";
// initialize the documents
$cb->set($user_data1->email, json_encode($user_data1));
// retrieve the document and output
$v1 = json_decode($cb->get($user_data1->email, null, $cas));
echo "--------------------------------------------------------------------------\n";
echo "CAS : {$cas}\n";
$cas1 = $cas;
$v2 = json_decode($cb->get($user_data1->email, null, $cas));
$cas2 = $cas;
echo "--------------------------------------------------------------------------\n";
echo "Both v1 and v2 are identical and have identical CAS [(cas1) {$cas1} == (cas2) {$cas2}]\n";
echo "\n--------------\n";
echo "Now We'll update the document which results in a new CAS";
$v1->logins += 1;
$cas1 = $cb->set($v1->email, json_encode($v1));
echo "Now CAS as changed [(cas1) {$cas1} != (cas2) {$cas2}]";