/**
  * @depends testCreateBulkUpdater
  */
 public function testGetChanges()
 {
     $updater = $this->couchClient->createBulkUpdater();
     $updater->updateDocument(array("_id" => "test1", "foo" => "bar"));
     $updater->updateDocument(array("_id" => "test2", "bar" => "baz"));
     $updater->execute();
     $changes = $this->couchClient->getChanges();
     $this->assertArrayHasKey('results', $changes);
     $this->assertEquals(2, count($changes['results']));
     $this->assertEquals(2, $changes['last_seq']);
     // Check the limit parameter.
     $changes = $this->couchClient->getChanges(array('limit' => 1));
     $this->assertArrayHasKey('results', $changes);
     $this->assertEquals(1, count($changes['results']));
     $this->assertEquals(1, $changes['last_seq']);
     // Checks the descending parameter.
     $changes = $this->couchClient->getChanges(array('descending' => true));
     $this->assertArrayHasKey('results', $changes);
     $this->assertEquals(2, count($changes['results']));
     $this->assertEquals(1, $changes['last_seq']);
     // Checks the since parameter.
     $changes = $this->couchClient->getChanges(array('since' => 1));
     $this->assertArrayHasKey('results', $changes);
     $this->assertEquals(1, count($changes['results']));
     $this->assertEquals(2, $changes['last_seq']);
     // Checks the filter parameter.
     $designDocPath = __DIR__ . "/../../Models/CMS/_files";
     // Create a filter, that filters the only doc with {"_id":"test1"}
     $client = $this->couchClient;
     $client->createDesignDocument('test-filter', new FolderDesignDocument($designDocPath));
     $changes = $this->couchClient->getChanges(array('filter' => 'test-filter/my_filter'));
     $this->assertEquals(1, count($changes['results']));
     $this->assertEquals(3, $changes['last_seq']);
 }
Beispiel #2
0
 private function queryView($namespace)
 {
     $translations = array();
     $query = $this->db->createViewQuery('main', 'translations');
     if (is_array($namespace)) {
         $query->setKeys(array_values($namespace));
     } else {
         $query->setKey($namespace);
     }
     foreach ($query->execute() as $record) {
         $doc = $record['value'];
         $translations = array_merge($translations, self::singleTranslation($doc));
     }
     return $translations;
 }
 /**
  * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
  * @return \Doctrine\CouchDB\Connection
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /** @var $options \DoctrineCouchODMModule\Options\Connection */
     $options = $this->getOptions($serviceLocator, 'connection');
     $optionsArray = $options->toArray();
     $optionsArray['logging'] = $options->getLogging();
     return CouchDBClient::create($optionsArray);
 }
Beispiel #4
0
 /**
  * Create a CouchDB-Lucene Query.
  *
  * @param string $designDocName
  * @param string $viewName
  * @return View\ODMLuceneQuery
  */
 public function createLuceneQuery($designDocName, $viewName)
 {
     $luceneHandlerName = $this->config->getLuceneHandlerName();
     $designDoc = $this->config->getDesignDocument($designDocName);
     if ($designDoc) {
         $designDoc = new $designDoc['className']($designDoc['options']);
     }
     $query = new ODMLuceneQuery($this->couchDBClient->getHttpClient(), $this->couchDBClient->getDatabase(), $luceneHandlerName, $designDocName, $viewName, $designDoc);
     $query->setDocumentManager($this);
     return $query;
 }
Beispiel #5
0
 /**
  * couchDB - Couch DB Connection
  * 				 - Uses Doctrine  CouchDBClient
  * @return Object $connection
  */
 public function couchDB()
 {
     $host = $GLOBALS['couchdb_host'];
     $port = $GLOBALS['couchdb_port'];
     $usename = $GLOBALS['couchdb_user'];
     $password = $GLOBALS['couchdb_pass'];
     $database = $GLOBALS['couchdb_dbase'];
     $enable_log = $GLOBALS['couchdb_log'] == 1 ? true : false;
     $options = array('host' => $host, 'port' => $port, 'user' => $usename, 'password' => $password, 'logging' => $enable_log, 'dbname' => $database);
     $connection = \Doctrine\CouchDB\CouchDBClient::create($options);
     return $connection;
 }
 /**
  * @param CouchDBClient $studentClient
  * @param CouchDBClient $solutionClient
  * @throws \Doctrine\CouchDB\HTTP\HTTPException
  */
 private function replicateDbFromStudentToSolution(CouchDBClient $studentClient, CouchDBClient $solutionClient)
 {
     $response = $studentClient->allDocs();
     if ($response->status !== 200) {
         //should maybe throw an exception - but what should we print?
         return;
     }
     foreach ($response->body['rows'] as $row) {
         $doc = $row['doc'];
         $data = array_filter($doc, function ($key) {
             return !in_array($key, ['_id', '_rev']);
         }, ARRAY_FILTER_USE_KEY);
         try {
             $solutionClient->putDocument($data, $doc['_id'], $doc['_rev']);
         } catch (HTTPException $e) {
         }
     }
 }
 /**
  * @depends testCreateBulkUpdater
  */
 public function testTransferChangedDocuments()
 {
     $client = $this->couchClient;
     // Recreate DB
     $client->deleteDatabase($this->getTestDatabase());
     $client->createDatabase($this->getTestDatabase());
     // Doc id.
     $id = 'multiple_attachments';
     // Document with attachments.
     $docWithAttachment = array('_id' => $id, '_rev' => '1-abc', '_attachments' => array('foo.txt' => array('content_type' => 'text/plain', 'data' => 'VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ='), 'bar.txt' => array('content_type' => 'text/plain', 'data' => 'VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ=')));
     // Doc without any attachment. The id of both the docs is same.
     // So we will get two leaf revisions.
     $doc = array('_id' => $id, 'foo' => 'bar', '_rev' => '1-bcd');
     // Add the documents to the test db using Bulk API.
     $updater = $this->couchClient->createBulkUpdater();
     $updater->updateDocument($docWithAttachment);
     $updater->updateDocument($doc);
     // Set newedits to false to use the supplied _rev instead of assigning
     // new ones.
     $updater->setNewEdits(false);
     $response = $updater->execute();
     // Create the copy database and a copyClient to interact with it.
     $copyDb = $this->getTestDatabase() . '_copy';
     $client->createDatabase($copyDb);
     $copyClient = new CouchDBClient($client->getHttpClient(), $copyDb);
     // Missing revisions in the $copyDb.
     $missingRevs = array('1-abc', '1-bcd');
     // Transfer the missing revisions from the source to the target.
     list($docStack, $responses) = $client->transferChangedDocuments($id, $missingRevs, $copyClient);
     // $docStack should contain the doc that didn't have the attachment.
     $this->assertEquals(1, count($docStack));
     $this->assertEquals($doc, json_decode($docStack[0], true));
     // The doc with attachment should have been copied to the copyDb.
     $this->assertEquals(1, count($responses));
     $this->assertArrayHasKey('ok', $responses[0]);
     $this->assertEquals(true, $responses[0]['ok']);
     // Clean up.
     $client->deleteDatabase($this->getTestDatabase());
     $client->createDatabase($this->getTestDatabase());
     $client->deleteDatabase($copyDb);
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $database = $this->argument('database');
     $couch = CouchDBClient::create(array('dbname' => $database, 'user' => env('COUCH_APP_USER'), 'password' => env('COUCH_APP_PASS')));
     $type = $this->argument('type');
     $doc_req = $couch->allDocs();
     if ($doc_req->status == 200 && $doc_req->body) {
         foreach ($doc_req->body['rows'] as $row) {
             $doc = $row['doc'];
             if ($doc['_id'][0] == '_') {
                 // special docs
                 continue;
             }
             if ($this->option('all')) {
                 $this->info("deleting " . $doc['_id']);
                 $couch->deleteDocument($doc['_id'], $doc['_rev']);
             } elseif ($type && @$doc['type'] == $type) {
                 $this->info("deleting " . $doc['_id']);
                 $couch->deleteDocument($doc['_id'], $doc['_rev']);
             }
         }
     }
 }
 /**
  * Create a new database connection instance.
  *
  * @param array $config
  */
 public function __construct(array $config)
 {
     $this->config = $config;
     $this->db = CouchDBClient::create($config);
 }
 public function login(Request $request)
 {
     try {
         // Logging Response from Facebook into DB
         $couch = CouchDBClient::create(array('dbname' => 'careapp_log_db', 'user' => env('COUCH_APP_USER'), 'password' => env('COUCH_APP_PASS')));
         $fb_response = $request->input('fb_response');
         $fb_response['type'] = 'fb_response';
         $fb_response['timestamp'] = time();
         $couch->postDocument($fb_response);
         $response = [];
         // Validate response from FB
         if (empty($fb_response['status']) || $fb_response['status'] != 'connected' || empty($fb_response['authResponse']['accessToken']) || empty($fb_response['authResponse']['userID']) || empty($fb_response['authResponse']['expiresIn'])) {
             Log::error('FB Status: Not Connected / Invalid');
             $response['status'] = 'error';
             return $response;
         }
         // Get User Profile
         $fb = new Facebook\Facebook(['app_id' => env('FB_APP_ID'), 'app_secret' => env('FB_APP_SECRET'), 'default_graph_version' => 'v2.2']);
         $access_token = $fb_response['authResponse']['accessToken'];
         $fb_query = $fb->get('/me?fields=id,name,email,gender,picture', $access_token);
         $fb_user = $fb_query->getGraphUser();
         // Check if requested UserID and AuthToken are for same FB User
         if ($fb_response['authResponse']['userID'] != $fb_user['id']) {
             // Possible forgery
             Log::warning('Possible threat: UC59');
             $response['status'] = 'error';
             return $response;
         }
         // Check if user exists in DB
         $couch = CouchDBClient::create(array('dbname' => '_users', 'user' => env('COUCH_ADMIN_USER'), 'password' => env('COUCH_ADMIN_PASS')));
         $username = '******' . $fb_user['id'];
         $user_id = "org.couchdb.user:{$username}";
         $user_req = $couch->findDocument($user_id);
         $is_existing_user = false;
         if ($user_req->status == 200 && $user_req->body['_id']) {
             // User Exists
             $is_existing_user = true;
             $user = $user_req->body;
         } else {
             // New User
             $user = ['_id' => $user_id, 'type' => 'user', 'roles' => [], 'fb_id' => $fb_user['id'], 'display_name' => $fb_user['name'], 'email' => $fb_user['email'], 'name' => $username, 'gender' => $fb_user['gender']];
         }
         $user['password'] = $this->_generate_password();
         $user['fb_access_token'] = $fb_response['authResponse']['accessToken'];
         $user['fb_expires_in'] = $fb_response['authResponse']['expiresIn'];
         $user['fb_expire_time'] = time() + $fb_response['authResponse']['expiresIn'];
         // Create/Update User
         if ($fb_user['picture']['url'] && !$fb_user['picture']['is_silhouette']) {
             $user['fb_picture'] = $fb_user['picture']['url'];
             $response['fb_picture'] = $user['fb_picture'];
         }
         $couch->putDocument($user, $user['_id']);
         $response['gender'] = $user['gender'];
         $response['display_name'] = $user['display_name'];
         $response['status'] = 'success';
         $response['token'] = $user['password'];
         // If existing user, fetch profile too
         if ($is_existing_user) {
             $couch = CouchDBClient::create(array('dbname' => 'careapp_profiles_db', 'user' => env('COUCH_APP_USER'), 'password' => env('COUCH_APP_PASS')));
             $profile_req = $couch->findDocument($username);
             if ($profile_req->status == 200 && $profile_req->body['_id']) {
                 $response['profile'] = $profile_req->body;
             }
         }
         return $response;
     } catch (Exception $e) {
         Log::error($e->getMessage());
         $response['status'] = 'error';
         return $response;
     }
 }
 public function tearDown()
 {
     $this->couchClient->deleteDatabase($this->getBulkTestDatabase());
 }
<?php

namespace Relaxed\ReplicationDemo;

require "../vendor/autoload.php";
use Doctrine\CouchDB\CouchDBClient;
use Relaxed\Replicator\ReplicationTask;
use Relaxed\Replicator\Replicator;
$sourceClient = CouchDBClient::create(array('dbname' => 'sourcedb'));
$targetClient = CouchDBClient::create(array('dbname' => 'targetdb1'));
// Add docs to the source db.
$id = 'id';
$docs = array(array('_id' => $id . '1', 'foo' => 'bar1', '_rev' => '1-abc'), array('_id' => $id . '2', 'foo' => 'bar2', '_rev' => '1-bcd'), array('_id' => $id . '3', 'foo' => 'bar3', '_rev' => '1-cde'));
$updater = $sourceClient->createBulkUpdater();
$updater->updateDocuments($docs);
// Set newedits to false to use the supplied _rev instead of assigning
// new ones.
$updater->setNewEdits(false);
$response = $updater->execute();
// Create the replication task.
$task = new ReplicationTask();
// Enable target creation.
$task->setCreateTarget(true);
// Create the replicator.
$replicator = new Replicator($sourceClient, $targetClient, $task);
// Get the replication report as an array.
var_dump($replicator->startReplication(false, true));
/*
* array(3) {
 ["multipartResponse"]=>
 array(0) {
Beispiel #13
0
 public function ensureFullCommit()
 {
     $this->target->ensureFullCommit();
 }
Beispiel #14
0
<?php

require '../vendor/autoload.php';
set_time_limit(0);
$client = \Doctrine\CouchDB\CouchDBClient::create(array('dbname' => 'pokedex'));
//pokemon
$pokedex = file_get_contents('http://pokeapi.co/api/v1/pokedex/1/');
$pokedex_data = json_decode($pokedex, true);
foreach ($pokedex_data['pokemon'] as $row) {
    $name = $row['name'];
    $pokemon = file_get_contents('http://pokeapi.co/' . $row['resource_uri']);
    $pokemon = json_decode($pokemon, true);
    $pokemon_description = file_get_contents('http://pokeapi.co/' . $pokemon['descriptions'][0]['resource_uri']);
    $pokemon['description'] = json_decode($pokemon_description, true)['description'];
    $pokemon_sprites = file_get_contents('http://pokeapi.co' . $pokemon['sprites'][0]['resource_uri']);
    $pokemon_sprites = json_decode($pokemon_sprites, true);
    $pokemon['small_photo'] = 'http://pokeapi.co' . $pokemon_sprites['image'];
    $pokemon['photo'] = 'http://img.pokemondb.net/artwork/' . strtolower($pokemon['name']) . '.jpg';
    $client->postDocument($pokemon);
}
 public function testRequestSuccessWithAttachments()
 {
     $client = new CouchDBClient($this->getHttpClient(), $this->getTestDatabase());
     // Recreate DB
     $client->deleteDatabase($this->getTestDatabase());
     $client->createDatabase($this->getTestDatabase());
     // Doc id.
     $id = $this->docId;
     // Document with attachments.
     $docWithAttachment = array('_id' => $id, '_rev' => '1-abc', '_attachments' => array('foo.txt' => array('content_type' => 'text/plain', 'data' => 'VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ='), 'bar.txt' => array('content_type' => 'text/plain', 'data' => 'VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ=')));
     // Doc without any attachment. The id of both the docs is same.
     // So we will get two leaf revisions.
     $doc = array('_id' => $id, 'foo' => 'bar', '_rev' => '1-bcd');
     // Add the documents to the test db using Bulk API.
     $updater = $client->createBulkUpdater();
     $updater->updateDocument($docWithAttachment);
     $updater->updateDocument($doc);
     // Set newedits to false to use the supplied _rev instead of assigning
     // new ones.
     $updater->setNewEdits(false);
     $response = $updater->execute();
     // Create the copy database and a copyClient to interact with it.
     $copyDb = $this->getTestDatabase() . '_multipart_copy';
     $client->createDatabase($copyDb);
     $copyClient = new CouchDBClient($client->getHttpClient(), $copyDb);
     // Missing revisions in the $copyDb.
     $missingRevs = array('1-abc', '1-bcd');
     $this->sourceParams['open_revs'] = json_encode($missingRevs);
     $query = http_build_query($this->sourceParams);
     $this->sourcePath .= '?' . $query;
     // Get the multipart data stream from real CouchDB instance.
     $stream = (new StreamClient())->getConnection($this->sourceMethod, $this->sourcePath, null, $this->sourceHeaders);
     // Set the return values for the mocked StreamClient.
     $this->streamClientMock->expects($this->once())->method('getConnection')->willReturn($stream);
     // Return header with status code as 200.
     $this->streamClientMock->expects($this->once())->method('getStreamHeaders')->willReturn(array('status' => 200));
     // Transfer the missing revisions from the source to the target.
     list($docStack, $responses) = $this->parserAndSender->request($this->sourceMethod, $this->sourcePath, $this->targetPath, null, $this->sourceHeaders);
     // $docStack should contain the doc that didn't have the attachment.
     $this->assertEquals(1, count($docStack));
     $this->assertEquals($doc, json_decode($docStack[0], true));
     // The doc with attachment should have been copied to the copyDb.
     $this->assertEquals(1, count($responses));
     $this->assertArrayHasKey('ok', $responses[0]);
     $this->assertEquals(true, $responses[0]['ok']);
     // Clean up.
     $client->deleteDatabase($this->getTestDatabase());
     $client->createDatabase($this->getTestDatabase());
     $client->deleteDatabase($copyDb);
 }
Beispiel #16
0
 /**
  * Transfer missing revisions to the target. The Content-Type of response
  * from the source should be multipart/mixed.
  *
  * @param string $docId
  * @param array $missingRevs
  * @param CouchDBClient $target
  * @return array|HTTP\ErrorResponse|string
  * @throws HTTPException
  */
 public function transferChangedDocuments($docId, $missingRevs, CouchDBClient $target)
 {
     $path = '/' . $this->getDatabase() . '/' . $docId;
     $params = array('revs' => true, 'latest' => true, 'open_revs' => json_encode($missingRevs));
     $query = http_build_query($params);
     $path .= '?' . $query;
     $targetPath = '/' . $target->getDatabase() . '/' . $docId . '?new_edits=false';
     $mutltipartHandler = new MultipartParserAndSender($this->getHttpClient(), $target->getHttpClient());
     return $mutltipartHandler->request('GET', $path, $targetPath, null, array('Accept' => 'multipart/mixed'));
 }
Beispiel #17
0
 /**
  * @param \Doctrine\CouchDB\CouchDBClient $client
  * @param string                          $database
  * @param bool                            $createIfNotFound
  *
  * @return bool Returns TRUE ONLY when the database existed before the call.
  * @throws \Doctrine\CouchDB\HTTP\HTTPException
  */
 public static function databaseExists($client, $database = null, $createIfNotFound = true)
 {
     try {
         return $client->getDatabaseInfo($database ?: $client->getDatabase());
     } catch (\Doctrine\CouchDB\HTTP\HTTPException $_ex) {
         if (static::NotFound != $_ex->getCode()) {
             throw $_ex;
         }
         if (true === $createIfNotFound) {
             $client->createDatabase($database ?: $client->getDatabase());
         }
     }
     return false;
 }
Beispiel #18
0
 public function _add_countries()
 {
     $couch = CouchDBClient::create(array('dbname' => 'careapp_passions_db', 'user' => env('COUCH_APP_USER'), 'password' => env('COUCH_APP_PASS')));
     $countries_json = "http://vocab.nic.in/rest.php/country/json";
     $countries_text = file_get_contents($countries_json);
     $countries = json_decode($countries_text, true);
     if (empty($countries)) {
         $this->info("Warning: No countries.");
         return;
     }
     $count = 0;
     $errors = 0;
     foreach ($countries['countries'] as $item) {
         if ($errors > 10) {
             break;
         }
         $country = ['name' => ucwords(strtolower($item['country']['country_name'])), 'code' => strtolower($item['country']['country_id']), 'type' => 'country'];
         $country['_id'] = 'cty-' . $country['code'];
         try {
             $couch->putDocument($country, $country['_id']);
             $count++;
         } catch (Exception $e) {
             $errors++;
         }
     }
     $this->info("{$count} countries added. {$errors} errors.");
 }
Beispiel #19
0
 public static function init()
 {
     $couch = parent::create(array('dbname' => Config::get('database.couch.default.database'), 'host' => Config::get('database.couch.default.host'), 'port' => (int) Config::get('database.couch.default.port')));
     return $couch;
 }
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage There is no client implementation registered for foo, valid options are: socket, stream
  */
 public function testCreateClientMissingClientException()
 {
     CouchDBClient::create(array('dbname' => 'test', 'type' => 'foo'));
 }
Beispiel #21
0
 /**
  * {@inheritDoc}
  */
 public function find($storageName, $key)
 {
     $key = $this->flattenKey($storageName, $key);
     return $this->client->findDocument($key);
 }