mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
8 files changed
+1150
No files matched your search
Executable
+15
@@ -0,0 +1,15 @@
|
||||
/vendor/
|
||||
/.idea/
|
||||
.DS_Store
|
||||
mock.json
|
||||
data-tests.php
|
||||
loader.php
|
||||
.phpunit.result.cache
|
||||
/bin/view/results/
|
||||
.vscode
|
||||
.vscode/*
|
||||
|
||||
## - Oh Wess!
|
||||
Makefile
|
||||
.envrc
|
||||
.vscode
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
FROM composer:2.0 as composer
|
||||
|
||||
ARG TESTING=false
|
||||
ENV TESTING=$TESTING
|
||||
|
||||
WORKDIR /usr/local/src/
|
||||
|
||||
COPY composer.lock /usr/local/src/
|
||||
COPY composer.json /usr/local/src/
|
||||
|
||||
RUN composer update --ignore-platform-reqs --optimize-autoloader \
|
||||
--no-plugins --no-scripts --prefer-dist
|
||||
|
||||
FROM php:8.0-cli-alpine as compile
|
||||
|
||||
ENV PHP_REDIS_VERSION=5.3.4 \
|
||||
PHP_SWOOLE_VERSION=v4.8.0 \
|
||||
PHP_MONGO_VERSION=1.11.1
|
||||
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
RUN \
|
||||
apk update \
|
||||
&& apk add --no-cache postgresql-libs postgresql-dev make automake autoconf gcc g++ git brotli-dev \
|
||||
&& docker-php-ext-install opcache pgsql pdo_mysql pdo_pgsql \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
# Redis Extension
|
||||
FROM compile AS redis
|
||||
RUN \
|
||||
git clone --depth 1 --branch $PHP_REDIS_VERSION https://github.com/phpredis/phpredis.git \
|
||||
&& cd phpredis \
|
||||
&& phpize \
|
||||
&& ./configure \
|
||||
&& make && make install
|
||||
|
||||
## Swoole Extension
|
||||
FROM compile AS swoole
|
||||
RUN \
|
||||
git clone --depth 1 --branch $PHP_SWOOLE_VERSION https://github.com/swoole/swoole-src.git \
|
||||
&& cd swoole-src \
|
||||
&& phpize \
|
||||
&& ./configure --enable-http2 \
|
||||
&& make && make install
|
||||
|
||||
## MongoDB Extension
|
||||
FROM compile AS mongodb
|
||||
RUN \
|
||||
git clone --depth 1 --branch $PHP_MONGO_VERSION https://github.com/mongodb/mongo-php-driver.git \
|
||||
&& cd mongo-php-driver \
|
||||
&& git submodule update --init \
|
||||
&& phpize \
|
||||
&& ./configure \
|
||||
&& make && make install
|
||||
|
||||
FROM compile as final
|
||||
|
||||
LABEL maintainer="team@appwrite.io"
|
||||
|
||||
WORKDIR /usr/src/code
|
||||
|
||||
RUN echo extension=redis.so >> /usr/local/etc/php/conf.d/redis.ini
|
||||
RUN echo extension=swoole.so >> /usr/local/etc/php/conf.d/swoole.ini
|
||||
RUN echo extension=mongodb.so >> /usr/local/etc/php/conf.d/mongodb.ini
|
||||
|
||||
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
|
||||
|
||||
RUN echo "opcache.enable_cli=1" >> $PHP_INI_DIR/php.ini
|
||||
|
||||
RUN echo "memory_limit=1024M" >> $PHP_INI_DIR/php.ini
|
||||
|
||||
COPY --from=composer /usr/local/src/vendor /usr/src/code/vendor
|
||||
COPY --from=swoole /usr/local/lib/php/extensions/no-debug-non-zts-20200930/swoole.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
|
||||
COPY --from=redis /usr/local/lib/php/extensions/no-debug-non-zts-20200930/redis.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
|
||||
COPY --from=mongodb /usr/local/lib/php/extensions/no-debug-non-zts-20200930/mongodb.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
|
||||
|
||||
# Add Source Code
|
||||
COPY . /usr/src/code
|
||||
|
||||
CMD [ "tail", "-f", "/dev/null" ]
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "utopia-php/mongo",
|
||||
"description": "A simple library to manage Mongo database",
|
||||
"type": "library",
|
||||
"keywords": ["php","mongo", "upf", "utopia", "database"],
|
||||
"license": "MIT",
|
||||
"minimum-stability": "stable",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Eldad Fux",
|
||||
"email": "eldad@appwrite.io"
|
||||
},
|
||||
{
|
||||
"name": "Wess",
|
||||
"email": "wess@appwrite.io"
|
||||
}
|
||||
],
|
||||
"autoload": {
|
||||
"psr-4": {"Utopia\\Mongo\\": "src/Mongo"}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {"Utopia\\Tests\\": "tests/Mongo"}
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.0",
|
||||
"ext-mongodb": "*",
|
||||
"mongodb/mongodb": "1.8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.14",
|
||||
"phpunit/phpunit": "^9.4",
|
||||
"swoole/ide-helper": "4.8.0",
|
||||
"utopia-php/cli": "^0.11.0",
|
||||
"vimeo/psalm": "4.0.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
version: '3.1'
|
||||
|
||||
services:
|
||||
|
||||
tests:
|
||||
container_name: tests
|
||||
build:
|
||||
context: .
|
||||
networks:
|
||||
- database
|
||||
volumes:
|
||||
- ./:/usr/src/code
|
||||
ports:
|
||||
- "8708:8708"
|
||||
|
||||
adminer:
|
||||
image: adminer
|
||||
container_name: utopia-adminer
|
||||
restart: always
|
||||
ports:
|
||||
- "8760:8080"
|
||||
networks:
|
||||
- database
|
||||
|
||||
postgres:
|
||||
image: postgres:13
|
||||
container_name: utopia-postgres
|
||||
networks:
|
||||
- database
|
||||
ports:
|
||||
- "8700:5432"
|
||||
environment:
|
||||
POSTGRES_USER: root
|
||||
POSTGRES_PASSWORD: password
|
||||
|
||||
cockroach:
|
||||
image: cockroachdb/cockroach:v20.2.0
|
||||
container_name: utopia-cockroach
|
||||
command: start-single-node --insecure --logtostderr
|
||||
networks:
|
||||
- database
|
||||
ports:
|
||||
- "8704:26257"
|
||||
- "8705:8080"
|
||||
|
||||
mariadb:
|
||||
image: mariadb:10.5
|
||||
container_name: utopia-mariadb
|
||||
networks:
|
||||
- database
|
||||
ports:
|
||||
- "8701:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=password
|
||||
|
||||
mongo:
|
||||
image: mongo:4.4
|
||||
container_name: utopia-mongo
|
||||
networks:
|
||||
- database
|
||||
ports:
|
||||
- "8702:27017"
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: example
|
||||
|
||||
mysql:
|
||||
image: mysql:8.0.28-oracle
|
||||
container_name: utopia-mysql
|
||||
networks:
|
||||
- database
|
||||
ports:
|
||||
- "8703:3307"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: password
|
||||
MYSQL_DATABASE: default
|
||||
MYSQL_USER: user
|
||||
MYSQL_PASSWORD: password
|
||||
MYSQL_TCP_PORT: 3307
|
||||
cap_add:
|
||||
- SYS_NICE
|
||||
|
||||
redis:
|
||||
image: redis:6.0-alpine
|
||||
container_name: utopia-redis
|
||||
networks:
|
||||
- database
|
||||
|
||||
networks:
|
||||
database:
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
<?php
|
||||
|
||||
namespace Utopia\Database\Adapter\Mongo;
|
||||
|
||||
use MongoDB\BSON;
|
||||
|
||||
class Auth
|
||||
{
|
||||
private string $authcid;
|
||||
private string $secret;
|
||||
private string $authzid;
|
||||
private string $gs2Header;
|
||||
private string $cnonce;
|
||||
private string $firstMessageBare;
|
||||
private string $saltedPassword;
|
||||
private string $authMessage;
|
||||
|
||||
public function __construct(array $options)
|
||||
{
|
||||
$this->authcid = isset($options['authcid']) ? $options['authcid'] : '';
|
||||
$this->secret = isset($options['secret']) ? $options['secret'] : '';
|
||||
$this->authzid = isset($options['authzid']) ? $options['authzid'] : '';
|
||||
$this->service = isset($options['service']) ? $options['service'] : '';
|
||||
|
||||
$this->nonce = base64_encode(random_bytes(32));
|
||||
}
|
||||
|
||||
public function start(): array
|
||||
{
|
||||
$response = $this->createResponse();
|
||||
$payload = new BSON\Binary($response, 0);
|
||||
|
||||
return [
|
||||
[
|
||||
"saslStart" => 1,
|
||||
"mechanism" => "SCRAM-SHA-1",
|
||||
"payload" => $payload,
|
||||
"autoAuthorize" => 1,
|
||||
"options" => ["skipEmptyExchange" => true],
|
||||
],
|
||||
'admin'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $data
|
||||
* @return array
|
||||
*/
|
||||
public function continue($data): array
|
||||
{
|
||||
$cid = $data->conversationId;
|
||||
$token = $data->payload->getData();
|
||||
|
||||
$answer = $this->createResponse($token);
|
||||
$payload = new \MongoDB\BSON\Binary($answer, 0);
|
||||
|
||||
return [
|
||||
[
|
||||
"saslContinue" => 1,
|
||||
"conversationId" => $cid,
|
||||
"payload" => $payload,
|
||||
],
|
||||
'admin'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $challenge
|
||||
* @return string
|
||||
*/
|
||||
public function createResponse($challenge = null): string
|
||||
{
|
||||
$authcid = $this->formatName($this->authcid);
|
||||
if (empty($authcid)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$authzid = $this->authzid;
|
||||
|
||||
if (!empty($authzid)) {
|
||||
$authzid = $this->formatName($authzid);
|
||||
}
|
||||
|
||||
if (empty($challenge)) {
|
||||
return $this->generateInitialResponse($authcid, $authzid);
|
||||
} else {
|
||||
return $this->generateResponse($challenge, $this->secret);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a name for inclusion in a SCRAM response.
|
||||
*
|
||||
* @param string $username a name to be prepared.
|
||||
* @return string the reformated name.
|
||||
*/
|
||||
private function formatName(string $username): string
|
||||
{
|
||||
return str_replace(['=', ','], ['=3D', '=2C'], $username);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the initial response which can be either sent directly in the first message or as a response to an empty
|
||||
* server challenge.
|
||||
*
|
||||
* @param string $authcid Prepared authentication identity.
|
||||
* @param string $authzid Prepared authorization identity.
|
||||
* @return string The SCRAM response to send.
|
||||
*/
|
||||
private function generateInitialResponse(string $authcid, string $authzid): string
|
||||
{
|
||||
$gs2CbindFlag = 'n,';
|
||||
$this->gs2Header = $gs2CbindFlag . (!empty($authzid) ? 'a=' . $authzid : '') . ',';
|
||||
|
||||
// I must generate a client nonce and "save" it for later comparison on second response.
|
||||
$this->cnonce = $this->generateCnonce();
|
||||
|
||||
$this->firstMessageBare = 'n=' . $authcid . ',r=' . $this->cnonce;
|
||||
|
||||
return $this->gs2Header . $this->firstMessageBare;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses and verifies a non-empty SCRAM challenge.
|
||||
*
|
||||
* @param string $challenge The SCRAM challenge
|
||||
* @param string $password The password challenge
|
||||
* @return string|false The response to send; false in case of wrong challenge or if an initial response has not
|
||||
* been generated first.
|
||||
*/
|
||||
private function generateResponse(string $challenge, string $password): string|bool
|
||||
{
|
||||
$matches = [];
|
||||
|
||||
$serverMessageRegexp = "#^r=([\x21-\x2B\x2D-\x7E/]+)"
|
||||
. ",s=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)"
|
||||
. ",i=([0-9]*)(,[A-Za-z]=[^,])*$#";
|
||||
|
||||
if (!isset($this->cnonce, $this->gs2Header) || !preg_match($serverMessageRegexp, $challenge, $matches)) {
|
||||
return false;
|
||||
}
|
||||
$nonce = $matches[1];
|
||||
$salt = base64_decode($matches[2]);
|
||||
|
||||
if (!$salt) {
|
||||
return false;
|
||||
}
|
||||
$i = intval($matches[3]);
|
||||
|
||||
$cnonce = substr($nonce, 0, strlen($this->cnonce));
|
||||
if ($cnonce !== $this->cnonce) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$channelBinding = 'c=' . base64_encode($this->gs2Header);
|
||||
$finalMessage = $channelBinding . ',r=' . $nonce;
|
||||
$saltedPassword = $this->hi($password, $salt, $i);
|
||||
$this->saltedPassword = $saltedPassword;
|
||||
$clientKey = $this->hmac($saltedPassword, "Client Key", true);
|
||||
$storedKey = $this->hash($clientKey, true);
|
||||
$authMessage = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
|
||||
$this->authMessage = $authMessage;
|
||||
$clientSignature = $this->hmac($storedKey, $authMessage, true);
|
||||
$clientProof = $clientKey ^ $clientSignature;
|
||||
$proof = ',p=' . base64_encode($clientProof);
|
||||
|
||||
return $finalMessage . $proof;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
|
||||
*
|
||||
* @param string $str The string to hash.
|
||||
* @param string $salt The salt value.
|
||||
* @param int $i The iteration count.
|
||||
* @return string The hashed string.
|
||||
*/
|
||||
private function hi(string $str, string $salt, int $i): string
|
||||
{
|
||||
$int1 = "\0\0\0\1";
|
||||
$ui = $this->hmac($str, $salt . $int1, true);
|
||||
$result = $ui;
|
||||
for ($k = 1; $k < $i; $k++) {
|
||||
$ui = $this->hmac($str, $ui, true);
|
||||
$result = $result ^ $ui;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* SCRAM has also a server verification step. On a successful outcome, it will send additional data which must
|
||||
* absolutely be checked against this function. If this fails, the entity which we are communicating with is probably
|
||||
* not the server as it has not access to your ServerKey.
|
||||
*
|
||||
* @param string $data The additional data sent along a successful outcome.
|
||||
* @return bool Whether the server has been authenticated.
|
||||
* If false, the client must close the connection and consider to be under a MITM attack.
|
||||
*/
|
||||
public function verify(string $data): bool
|
||||
{
|
||||
$verifierRegexp = '#^v=((?:[A-Za-z0-9/+]{4})*(?:[A-Za-z0-9/+]{3}=|[A-Za-z0-9/+]{2}==)?)$#';
|
||||
|
||||
$matches = [];
|
||||
if (!isset($this->saltedPassword, $this->authMessage) || !preg_match($verifierRegexp, $data, $matches)) {
|
||||
// This cannot be an outcome, you never sent the challenge's response.
|
||||
return false;
|
||||
}
|
||||
|
||||
$verifier = $matches[1];
|
||||
$proposedServerSignature = base64_decode($verifier);
|
||||
$serverKey = $this->hmac($this->saltedPassword, "Server Key", true);
|
||||
$serverSignature = $this->hmac($serverKey, $this->authMessage, true);
|
||||
|
||||
return $proposedServerSignature === $serverSignature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCnonce(): string
|
||||
{
|
||||
return $this->cnonce;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getSaltedPassword(): string
|
||||
{
|
||||
return $this->saltedPassword;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getAuthMessage(): string
|
||||
{
|
||||
return $this->authMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHashAlgo(): string
|
||||
{
|
||||
return $this->hashAlgo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function hash($data): string
|
||||
{
|
||||
return hash('sha1', $data, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function hmac($key, $str, $raw): string
|
||||
{
|
||||
return hash_hmac('sha1', $str, $key, $raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function generateCnonce(): string
|
||||
{
|
||||
foreach (['/dev/urandom', '/dev/random'] as $file) {
|
||||
if (is_readable($file)) {
|
||||
return base64_encode(file_get_contents($file, false, null, 0, 32));
|
||||
}
|
||||
}
|
||||
|
||||
$cnonce = '';
|
||||
|
||||
for ($i = 0; $i < 32; $i++) {
|
||||
$cnonce .= chr(mt_rand(0, 255));
|
||||
}
|
||||
|
||||
return base64_encode($cnonce);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
static function encodeCredentials($username, $password): string
|
||||
{
|
||||
return \md5(\utf8_encode($username . ':mongo:' . $password));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
<?php
|
||||
|
||||
namespace Utopia\Database\Adapter\Mongo;
|
||||
|
||||
use MongoDB\BSON;
|
||||
use Swoole\Client;
|
||||
use Swoole\Coroutine\Client as CoroutineClient;
|
||||
use Utopia\Database\Adapter\Mongo\Auth;
|
||||
use Utopia\Database\Adapter\Mongo\MongoClientOptions;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Exception\Duplicate as DuplicateException;
|
||||
|
||||
class MongoClient
|
||||
{
|
||||
/**
|
||||
* Unique identifier for socket connection.
|
||||
*/
|
||||
private string $id;
|
||||
|
||||
/**
|
||||
* Options for connection.
|
||||
*/
|
||||
private MongoClientOptions $options;
|
||||
|
||||
/**
|
||||
* Socket (sync or async) client.
|
||||
*/
|
||||
private Client|CoroutineClient $client;
|
||||
|
||||
/**
|
||||
* Authentication for connection
|
||||
*/
|
||||
private Auth $auth;
|
||||
|
||||
/**
|
||||
* Create a Mongo connection.
|
||||
* @param MongoClientOptions $options
|
||||
* @param Boolean $useCoroutine
|
||||
*/
|
||||
public function __construct(MongoClientOptions $options, bool $useCoroutine = true)
|
||||
{
|
||||
$this->id = uniqid('utopia.mongo.client');
|
||||
$this->options = $options;
|
||||
|
||||
$this->client = $useCoroutine
|
||||
? new CoroutineClient(SWOOLE_SOCK_TCP | SWOOLE_KEEP)
|
||||
: new Client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
|
||||
|
||||
$this->auth = new Auth([
|
||||
'authcid' => $options->username,
|
||||
'secret' => Auth::encodeCredentials($options->username, $options->password)
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to Mongo using TCP/IP
|
||||
* and Wire Protocol.
|
||||
*/
|
||||
public function connect(): MongoClient
|
||||
{
|
||||
$this->client->connect($this->options->host, $this->options->port);
|
||||
[$payload, $db] = $this->auth->start();
|
||||
|
||||
$res = $this->query($payload, $db);
|
||||
|
||||
[$payload, $db] = $this->auth->continue($res);
|
||||
|
||||
$res = $this->query($payload, $db);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a raw string query to connection.
|
||||
* @param string $qry
|
||||
*/
|
||||
public function raw_query(string $qry): mixed
|
||||
{
|
||||
return $this->send($qry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a BSON packed query to connection.
|
||||
*
|
||||
* @param array $command
|
||||
* @param string $db
|
||||
*/
|
||||
public function query(array $command, ?string $db = null): \stdClass|array|int
|
||||
{
|
||||
$params = array_merge($command, [
|
||||
'$db' => $db ?? $this->options->name,
|
||||
]);
|
||||
|
||||
$sections = BSON\fromPHP($params);
|
||||
$message = pack('V*', 21 + strlen($sections), $this->id, 0, 2013, 0) . "\0" . $sections;
|
||||
|
||||
return $this->send($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a syncronous command to connection.
|
||||
*/
|
||||
public function blocking(string $cmd): \stdClass|array|int
|
||||
{
|
||||
$this->client->send($cmd . PHP_EOL);
|
||||
|
||||
$result = '';
|
||||
|
||||
while ($result = $this->client->recv()) {
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to connection.
|
||||
*
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function send(mixed $data): \stdClass|array|int
|
||||
{
|
||||
$this->client->send($data);
|
||||
|
||||
return $this->receive();
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive a message from connection.
|
||||
*/
|
||||
private function receive(): \stdClass|array|int
|
||||
{
|
||||
$receivedLength = 0;
|
||||
$responseLength = null;
|
||||
$res = '';
|
||||
|
||||
do {
|
||||
if (($chunk = $this->client->recv()) === false) {
|
||||
sleep(1); // Prevent excessive CPU Load, test lower.
|
||||
continue;
|
||||
}
|
||||
|
||||
$receivedLength += strlen($chunk);
|
||||
$res .= $chunk;
|
||||
|
||||
if ((!isset($responseLength)) && (strlen($res) >= 4)) {
|
||||
$responseLength = unpack('Vl', substr($res, 0, 4))['l'];
|
||||
}
|
||||
} while (
|
||||
(!isset($responseLength)) || ($receivedLength < $responseLength)
|
||||
);
|
||||
|
||||
$result = BSON\toPHP(substr($res, 21, $responseLength - 21));
|
||||
|
||||
if (property_exists($result, "writeErrors")) {
|
||||
throw new DuplicateException($result->writeErrors[0]->errmsg);
|
||||
}
|
||||
|
||||
if (property_exists($result, "n") && $result->ok == 1) {
|
||||
return $result->n;
|
||||
}
|
||||
|
||||
if (property_exists($result, "nonce") && $result->ok == 1) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
if (property_exists($result, 'errmsg')) {
|
||||
throw new \Exception($result->errmsg);
|
||||
}
|
||||
|
||||
if ($result->ok == 1) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $result->cursor->firstBatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a collection.
|
||||
*
|
||||
* Note: Since Mongo creates on the fly, this just returns
|
||||
* a instances of self.
|
||||
*/
|
||||
public function selectDatabase(string $name): MongoClient
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a collection.
|
||||
*
|
||||
* Note: Since Mongo creates on the fly, this just returns
|
||||
* a instances of self.
|
||||
*/
|
||||
public function createDatabase(string $name): MongoClient
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of databases.
|
||||
*/
|
||||
public function listDatabaseNames(): \stdClass
|
||||
{
|
||||
return $this->query([
|
||||
'listDatabases' => 1,
|
||||
'nameOnly' => true,
|
||||
], 'admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop (remove) a database.
|
||||
* https://docs.mongodb.com/manual/reference/command/dropDatabase/#mongodb-dbcommand-dbcmd.dropDatabase
|
||||
*
|
||||
* @param array $options
|
||||
* @param string $db
|
||||
*/
|
||||
public function dropDatabase(array $options = [], ?string $db = null): MongoClient
|
||||
{
|
||||
$db ??= $this->options->name;
|
||||
|
||||
$this->query(array_merge(["dropDatabase" => 1], $options), $db);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function selectCollection($name): MongoClient
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a collection.
|
||||
* https://docs.mongodb.com/manual/reference/command/create/#mongodb-dbcommand-dbcmd.create
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $options
|
||||
*/
|
||||
public function createCollection(string $name, array $options = []): MongoClient
|
||||
{
|
||||
$list = $this->listCollectionNames(["name" => $name]);
|
||||
|
||||
if (\count($list->cursor->firstBatch) > 0) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->query(array_merge([
|
||||
'create' => $name,
|
||||
], $options));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a collection.
|
||||
* https://docs.mongodb.com/manual/reference/command/drop/#mongodb-dbcommand-dbcmd.drop
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $options
|
||||
*/
|
||||
public function dropCollection(string $name, array $options = []): MongoClient
|
||||
{
|
||||
$this->query(array_merge([
|
||||
'drop' => $name,
|
||||
], $options));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* List collections (name only).
|
||||
* https://docs.mongodb.com/manual/reference/command/listCollections/#listcollections
|
||||
*
|
||||
* @param array $filter
|
||||
* @param array $options
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function listCollectionNames(array $filter = [], array $options = []): \stdClass
|
||||
{
|
||||
$qry = array_merge(
|
||||
[
|
||||
"listCollections" => 1.0,
|
||||
"nameOnly" => true,
|
||||
"authorizedCollections" => true,
|
||||
"filter" => $this->toObject($filter)
|
||||
],
|
||||
$options
|
||||
);
|
||||
|
||||
return $this->query($qry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create indexes.
|
||||
* https://docs.mongodb.com/manual/reference/command/createIndexes/#createindexes
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $indexes
|
||||
* @param array $options
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function createIndexes(string $collection, array $indexes, array $options = []): bool
|
||||
{
|
||||
|
||||
$qry = array_merge(
|
||||
[
|
||||
'createIndexes' => $collection,
|
||||
'indexes' => $indexes
|
||||
],
|
||||
$options
|
||||
);
|
||||
|
||||
$this->query($qry);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop indexes from a collection.
|
||||
* https://docs.mongodb.com/manual/reference/command/dropIndexes/#dropindexes
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $indexes
|
||||
* @param array $options
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function dropIndexes(string $collection, array $indexes, array $options = []): MongoClient
|
||||
{
|
||||
$this->query(
|
||||
array_merge([
|
||||
'dropIndexes' => $collection,
|
||||
'index' => $indexes,
|
||||
], $options)
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/insert/#mongodb-dbcommand-dbcmd.insert
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $documents
|
||||
* @param array $options
|
||||
*
|
||||
* @return Document
|
||||
*/
|
||||
public function insert(string $collection, array $documents, array $options = []): Document
|
||||
{
|
||||
$docObj = new \stdClass();
|
||||
|
||||
foreach ($documents as $key => $value) {
|
||||
$docObj->{$key} = $value;
|
||||
}
|
||||
|
||||
$this->query(array_merge([
|
||||
MongoCommand::INSERT => $collection,
|
||||
'documents' => [$docObj],
|
||||
], $options));
|
||||
|
||||
return new Document($this->toArray($docObj));
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/update/#syntax
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $where
|
||||
* @param array $updates
|
||||
* @param array $options
|
||||
*
|
||||
* @return MongoClient
|
||||
*/
|
||||
public function update(string $collection, array $where = [], array $updates = [], array $options = []): MongoClient
|
||||
{
|
||||
|
||||
$this->query(
|
||||
array_merge([
|
||||
MongoCommand::UPDATE => $collection,
|
||||
'updates' => [
|
||||
[
|
||||
'q' => $this->toObject($where),
|
||||
'u' => $this->toObject($updates),
|
||||
'multi' => false,
|
||||
'upsert' => false
|
||||
]
|
||||
]
|
||||
], $options)
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert, or update, a document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/update/#syntax
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $where
|
||||
* @param array $updates
|
||||
* @param array $options
|
||||
*
|
||||
* @return MongoClient
|
||||
*/
|
||||
|
||||
public function upsert(string $collection, array $where = [], array $updates = [], array $options = []): MongoClient
|
||||
{
|
||||
$this->query(
|
||||
array_merge(
|
||||
[
|
||||
'update' => $collection,
|
||||
'updates' => [
|
||||
[
|
||||
'q' => ['_uid' => $where['_uid']],
|
||||
'u' => ['$set' => $updates],
|
||||
]
|
||||
],
|
||||
],
|
||||
$options
|
||||
)
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/find/#mongodb-dbcommand-dbcmd.find
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $filters
|
||||
* @param array $options
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function find(string $collection, array $filters = [], array $options = []): \stdClass
|
||||
{
|
||||
|
||||
$result = $this->query(
|
||||
array_merge([
|
||||
MongoCommand::FIND => $collection,
|
||||
'filter' => $this->toObject($filters),
|
||||
], $options)
|
||||
);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and modify document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/findAndModify/#mongodb-dbcommand-dbcmd.findAndModify
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $update
|
||||
* @param boolean $remove
|
||||
* @param array $filters
|
||||
* @param array $options
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function findAndModify(string $collection, array $update, bool $remove = false, array $filters = [], array $options = []): \stdClass
|
||||
{
|
||||
return $this->query(
|
||||
array_merge([
|
||||
MongoCommand::FIND_AND_MODIFY => $collection,
|
||||
'filter' => $this->toObject($filters),
|
||||
'remove' => $remove,
|
||||
'update' => $update,
|
||||
], $options)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a document/s.
|
||||
* https://docs.mongodb.com/manual/reference/command/delete/#mongodb-dbcommand-dbcmd.delete
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $filters
|
||||
* @param int $limit
|
||||
* @param array $deleteOptions
|
||||
* @param array $options
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function delete(string $collection, array $filters = [], int $limit = 1, array $deleteOptions = [], array $options = []): int
|
||||
{
|
||||
return $this->query(
|
||||
array_merge(
|
||||
[
|
||||
MongoCommand::DELETE => $collection,
|
||||
'deletes' => [
|
||||
$this->toObject(
|
||||
array_merge(
|
||||
[
|
||||
'q' => $this->toObject($filters),
|
||||
'limit' => $limit,
|
||||
],
|
||||
$deleteOptions
|
||||
)
|
||||
),
|
||||
]
|
||||
],
|
||||
$options
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count documents.
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $filters
|
||||
* @param array $options
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count(string $collection, array $filters, array $options): int
|
||||
{
|
||||
$result = $this->find($collection, $filters, $options);
|
||||
$list = $result->cursor->firstBatch;
|
||||
|
||||
return \count($list);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate a collection pipeline.
|
||||
*
|
||||
* @param string $collection
|
||||
* @param array $pipeline
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function aggregate(string $collection, array $pipeline): \stdClass
|
||||
{
|
||||
$result = $this->query([
|
||||
MongoCommand::AGGREGATE => $collection,
|
||||
'pipeline' => $pipeline,
|
||||
'cursor' => $this->toObject([]),
|
||||
]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an assoc array to an object (stdClass).
|
||||
*
|
||||
* @param array $dict
|
||||
*
|
||||
* @return stdClass
|
||||
*/
|
||||
public function toObject(array $dict): \stdClass
|
||||
{
|
||||
$obj = new \stdClass();
|
||||
|
||||
foreach ($dict as $k => $v) {
|
||||
$key = $k == 'id' ? '_id' : $k;
|
||||
$val = $v;
|
||||
|
||||
if ($k == '_id') {
|
||||
$val = new \MongoDB\BSON\ObjectId($val);
|
||||
}
|
||||
|
||||
$obj->{$key} = $val;
|
||||
}
|
||||
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an object (stdClass) to an assoc array.
|
||||
*
|
||||
* @param string $obj
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray(\stdClass|array|string $obj): array
|
||||
{
|
||||
if (is_object($obj) || is_array($obj)) {
|
||||
$ret = (array) $obj;
|
||||
foreach ($ret as $item) {
|
||||
$item = $this->toArray($item);
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
return [$obj];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Utopia\Database\Adapter\Mongo;
|
||||
|
||||
class MongoClientOptions
|
||||
{
|
||||
/**
|
||||
* Creates an object that contains the connection
|
||||
* details for Mongo.
|
||||
*/
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public string $host,
|
||||
public int $port,
|
||||
public string $username,
|
||||
public string $password
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Utopia\Database\Adapter\Mongo;
|
||||
|
||||
class MongoCommand
|
||||
{
|
||||
/**
|
||||
* Defines commands Mongo uses over wire protocol.
|
||||
*/
|
||||
public const CREATE = "create";
|
||||
public const DELETE = "delete";
|
||||
public const FIND = "find";
|
||||
public const FIND_AND_MODIFY = "findAndModify";
|
||||
public const GET_LAST_ERROR = "getLastError";
|
||||
public const GET_MORE = "getMore";
|
||||
public const INSERT = "insert";
|
||||
public const RESET_ERROR = "resetError";
|
||||
public const UPDATE = "update";
|
||||
public const COUNT = "count";
|
||||
public const AGGREGATE = "aggregate";
|
||||
public const DISTINCT = "distinct";
|
||||
public const MAP_REDUCE = "mapReduce";
|
||||
}
|
||||
Reference in new issue
Block a user