1
0
Fork 0
mirror of synced 2024-09-28 07:21:35 +12:00
appwrite/app/workers/deletes.php

733 lines
24 KiB
PHP
Raw Normal View History

<?php
2021-07-14 07:24:52 +12:00
use Utopia\Database\Database;
use Utopia\Database\Document;
2021-07-13 09:57:37 +12:00
use Utopia\Database\Query;
2021-07-14 07:24:52 +12:00
use Utopia\Database\Validator\Authorization;
use Appwrite\Resque\Worker;
2021-01-22 21:28:33 +13:00
use Utopia\Storage\Device\Local;
2020-12-19 03:08:28 +13:00
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Audit\Audit;
require_once __DIR__ . '/../init.php';
2020-12-19 21:08:03 +13:00
2021-01-15 19:02:48 +13:00
Console::title('Deletes V1 Worker');
2021-09-01 21:13:23 +12:00
Console::success(APP_NAME . ' deletes worker v1 has started' . "\n");
2020-12-19 21:08:03 +13:00
class DeletesV1 extends Worker
{
2021-08-27 16:37:15 +12:00
/**
* @var Database
*/
protected $consoleDB = null;
2021-11-24 22:38:32 +13:00
public function getName(): string {
return "deletes";
}
public function init(): void
{
}
public function run(): void
{
2021-06-12 22:07:26 +12:00
$projectId = $this->args['projectId'] ?? '';
$type = $this->args['type'] ?? '';
switch (strval($type)) {
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_DOCUMENT:
$document = new Document($this->args['document'] ?? []);
2021-06-12 22:07:26 +12:00
switch ($document->getCollection()) {
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_COLLECTIONS:
$this->deleteCollection($document, $projectId);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_PROJECTS:
$this->deleteProject($document);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_FUNCTIONS:
$this->deleteFunction($document, $projectId);
break;
case DELETE_TYPE_DEPLOYMENTS:
$this->deleteDeployment($document, $projectId);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_USERS:
$this->deleteUser($document, $projectId);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_TEAMS:
$this->deleteMemberships($document, $projectId);
break;
default:
2021-09-01 21:13:23 +12:00
Console::error('No lazy delete operation available for document of type: ' . $document->getCollection());
break;
}
2020-12-15 10:26:37 +13:00
break;
2020-12-22 07:15:52 +13:00
2020-12-28 06:57:35 +13:00
case DELETE_TYPE_EXECUTIONS:
$this->deleteExecutionLogs($this->args['timestamp']);
2020-12-22 07:15:52 +13:00
break;
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_AUDIT:
$timestamp = $this->args['timestamp'] ?? 0;
$document = new Document($this->args['document'] ?? []);
if (!empty($timestamp)) {
$this->deleteAuditLogs($this->args['timestamp']);
}
if (!$document->isEmpty()) {
$this->deleteAuditLogsByResource('document/' . $document->getId(), $projectId);
}
break;
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_ABUSE:
$this->deleteAbuseLogs($this->args['timestamp']);
break;
2021-02-05 23:57:43 +13:00
case DELETE_TYPE_REALTIME:
$this->deleteRealtimeUsage($this->args['timestamp']);
break;
2021-02-05 23:57:43 +13:00
case DELETE_TYPE_CERTIFICATES:
$document = new Document($this->args['document']);
$this->deleteCertificates($document);
break;
2021-09-01 21:13:23 +12:00
case DELETE_TYPE_USAGE:
2021-08-27 23:37:52 +12:00
$this->deleteUsageStats($this->args['timestamp1d'], $this->args['timestamp30m']);
2021-09-06 21:39:36 +12:00
break;
2020-12-19 21:08:03 +13:00
default:
2021-09-01 21:13:23 +12:00
Console::error('No delete operation for type: ' . $type);
2020-12-19 21:08:03 +13:00
break;
2021-09-01 21:13:23 +12:00
}
}
public function shutdown(): void
{
}
2021-09-01 21:13:23 +12:00
/**
* @param Document $document teams document
* @param string $projectId
*/
protected function deleteCollection(Document $document, string $projectId): void
{
$collectionId = $document->getId();
2021-09-01 21:13:23 +12:00
$dbForProject = $this->getProjectDB($projectId);
2021-12-31 00:21:06 +13:00
$dbForProject->deleteCollection('collection_' . $collectionId);
$this->deleteByGroup('attributes', [
new Query('collectionId', Query::TYPE_EQUAL, [$collectionId])
], $dbForProject);
$this->deleteByGroup('indexes', [
new Query('collectionId', Query::TYPE_EQUAL, [$collectionId])
], $dbForProject);
$this->deleteAuditLogsByResource('collection/' . $collectionId, $projectId);
}
2021-08-27 23:37:52 +12:00
/**
* @param int $timestamp1d
* @param int $timestamp30m
*/
protected function deleteUsageStats(int $timestamp1d, int $timestamp30m)
2021-09-01 21:13:23 +12:00
{
$this->deleteForProjectIds(function (string $projectId) use ($timestamp1d, $timestamp30m) {
$dbForProject = $this->getProjectDB($projectId);
2021-08-27 23:37:52 +12:00
// Delete Usage stats
$this->deleteByGroup('stats', [
new Query('time', Query::TYPE_LESSER, [$timestamp1d]),
new Query('period', Query::TYPE_EQUAL, ['1d']),
], $dbForProject);
2021-08-27 23:37:52 +12:00
$this->deleteByGroup('stats', [
new Query('time', Query::TYPE_LESSER, [$timestamp30m]),
new Query('period', Query::TYPE_EQUAL, ['30m']),
], $dbForProject);
2021-08-27 23:37:52 +12:00
});
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document teams document
* @param string $projectId
*/
2021-08-27 16:37:15 +12:00
protected function deleteMemberships(Document $document, string $projectId): void
{
$teamId = $document->getAttribute('teamId', '');
// Delete Memberships
2021-07-14 07:24:52 +12:00
$this->deleteByGroup('memberships', [
new Query('teamId', Query::TYPE_EQUAL, [$teamId])
], $this->getProjectDB($projectId));
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document project document
*/
2021-08-27 16:37:15 +12:00
protected function deleteProject(Document $document): void
{
2021-07-14 06:44:45 +12:00
$projectId = $document->getId();
// Delete all DBs
$this->getProjectDB($projectId)->delete($projectId);
2021-07-14 06:44:45 +12:00
// Delete all storage directories
2021-09-01 21:13:23 +12:00
$uploads = new Local(APP_STORAGE_UPLOADS . '/app-' . $document->getId());
$cache = new Local(APP_STORAGE_CACHE . '/app-' . $document->getId());
2020-05-27 07:12:40 +12:00
$uploads->delete($uploads->getRoot(), true);
$cache->delete($cache->getRoot(), true);
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document user document
* @param string $projectId
*/
2021-08-27 16:37:15 +12:00
protected function deleteUser(Document $document, string $projectId): void
{
/**
* DO NOT DELETE THE USER RECORD ITSELF.
* WE RETAIN THE USER RECORD TO RESERVE THE USER ID AND ENSURE THAT THE USER ID IS NOT REUSED.
*/
2021-07-13 09:57:37 +12:00
$userId = $document->getId();
$user = $this->getProjectDB($projectId)->getDocument('users', $userId);
2021-02-20 02:59:36 +13:00
// Delete all sessions of this user from the sessions table and update the sessions field of the user record
$this->deleteByGroup('sessions', [
new Query('userId', Query::TYPE_EQUAL, [$userId])
], $this->getProjectDB($projectId));
$user->setAttribute('sessions', []);
$updated = Authorization::skip(fn() => $this->getProjectDB($projectId)->updateDocument('users', $userId, $user));
// Delete Memberships and decrement team membership counts
2021-07-14 07:24:52 +12:00
$this->deleteByGroup('memberships', [
2021-07-13 09:57:37 +12:00
new Query('userId', Query::TYPE_EQUAL, [$userId])
2021-09-01 21:13:23 +12:00
], $this->getProjectDB($projectId), function (Document $document) use ($projectId) {
if ($document->getAttribute('confirm')) { // Count only confirmed members
$teamId = $document->getAttribute('teamId');
$team = $this->getProjectDB($projectId)->getDocument('teams', $teamId);
2021-09-01 21:13:23 +12:00
if (!$team->isEmpty()) {
$team = $this->getProjectDB($projectId)->updateDocument('teams', $teamId, new Document(\array_merge($team->getArrayCopy(), [
2021-05-31 16:56:06 +12:00
'sum' => \max($team->getAttribute('sum', 0) - 1, 0), // Ensure that sum >= 0
2021-07-13 09:57:37 +12:00
])));
}
}
});
}
2021-07-14 07:24:52 +12:00
/**
* @param int $timestamp
*/
2021-08-27 16:37:15 +12:00
protected function deleteExecutionLogs(int $timestamp): void
2020-12-15 10:26:37 +13:00
{
$this->deleteForProjectIds(function (string $projectId) use ($timestamp) {
$dbForProject = $this->getProjectDB($projectId);
2020-12-15 10:26:37 +13:00
// Delete Executions
2021-07-14 07:24:52 +12:00
$this->deleteByGroup('executions', [
new Query('dateCreated', Query::TYPE_LESSER, [$timestamp])
], $dbForProject);
});
2020-12-15 10:26:37 +13:00
}
/**
* @param int $timestamp
*/
protected function deleteRealtimeUsage(int $timestamp): void
{
$this->deleteForProjectIds(function (string $projectId) use ($timestamp) {
$dbForProject = $this->getProjectDB($projectId);
// Delete Dead Realtime Logs
$this->deleteByGroup('realtime', [
new Query('timestamp', Query::TYPE_LESSER, [$timestamp])
], $dbForProject);
});
}
2021-07-14 07:24:52 +12:00
/**
* @param int $timestamp
*/
2021-08-27 16:37:15 +12:00
protected function deleteAbuseLogs(int $timestamp): void
{
2021-09-01 21:13:23 +12:00
if ($timestamp == 0) {
throw new Exception('Failed to delete audit logs. No timestamp provided');
2020-12-19 03:05:15 +13:00
}
$this->deleteForProjectIds(function (string $projectId) use ($timestamp) {
$dbForProject = $this->getProjectDB($projectId);
$timeLimit = new TimeLimit("", 0, 1, $dbForProject);
2021-09-01 21:13:23 +12:00
$abuse = new Abuse($timeLimit);
2020-12-19 03:08:28 +13:00
$status = $abuse->cleanup($timestamp);
if (!$status) {
2021-09-01 21:13:23 +12:00
throw new Exception('Failed to delete Abuse logs for project ' . $projectId);
}
});
}
2021-07-14 07:24:52 +12:00
/**
* @param int $timestamp
*/
2021-08-27 16:37:15 +12:00
protected function deleteAuditLogs(int $timestamp): void
{
2021-09-01 21:13:23 +12:00
if ($timestamp == 0) {
2020-12-19 03:05:15 +13:00
throw new Exception('Failed to delete audit logs. No timestamp provided');
}
$this->deleteForProjectIds(function (string $projectId) use ($timestamp) {
$dbForProject = $this->getProjectDB($projectId);
$audit = new Audit($dbForProject);
2020-12-19 03:05:15 +13:00
$status = $audit->cleanup($timestamp);
if (!$status) {
2021-09-01 21:13:23 +12:00
throw new Exception('Failed to delete Audit logs for project' . $projectId);
}
});
}
/**
* @param int $timestamp
*/
protected function deleteAuditLogsByResource(string $resource, string $projectId): void
{
$dbForProject = $this->getProjectDB($projectId);
$this->deleteByGroup(Audit::COLLECTION, [
new Query('resource', Query::TYPE_EQUAL, [$resource])
], $dbForProject);
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document function document
* @param string $projectId
*/
2021-08-27 16:37:15 +12:00
protected function deleteFunction(Document $document, string $projectId): void
{
$dbForProject = $this->getProjectDB($projectId);
2022-01-28 13:25:28 +13:00
/**
* Request executor to delete all deployment containers
*/
try {
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
\curl_setopt($ch, CURLOPT_URL, "http://appwrite-executor/v1/functions/{$document->getId()}");
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
\curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'x-appwrite-project: '. $projectId,
'x-appwrite-executor-key: '. App::getEnv('_APP_EXECUTOR_SECRET', '')
]);
$executorResponse = \curl_exec($ch);
$error = \curl_error($ch);
if (!empty($error)) {
throw new Exception($error, 500);
}
$statusCode = \curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($statusCode >= 400) {
throw new Exception('Executor error: ' . $executorResponse, $statusCode);
}
\curl_close($ch);
} catch (Throwable $th) {
Console::error($th->getMessage());
}
/**
* Delete Deployments
*/
$storageFunctions = new Local(APP_STORAGE_FUNCTIONS . '/app-' . $projectId);
$deploymentIds = [];
$this->deleteByGroup('deployments', [
2022-02-01 03:43:11 +13:00
new Query('resourceId', Query::TYPE_EQUAL, [$document->getId()])
], $dbForProject, function (Document $document) use ($storageFunctions, &$deploymentIds) {
$deploymentIds[] = $document->getId();
if ($storageFunctions->delete($document->getAttribute('path', ''), true)) {
2022-02-01 12:44:55 +13:00
Console::success('Deleted deployment files: ' . $document->getAttribute('path', ''));
} else {
Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', ''));
}
});
/**
* Delete builds
*/
2022-01-29 13:52:06 +13:00
if (!empty($deploymentIds)) {
$storageBuilds = new Local(APP_STORAGE_BUILDS . '/app-' . $projectId);
$this->deleteByGroup('builds', [
new Query('deploymentId', Query::TYPE_EQUAL, $deploymentIds)
], $dbForProject, function (Document $document) use ($storageBuilds) {
if ($storageBuilds->delete($document->getAttribute('outputPath', ''), true)) {
Console::success('Deleted build files: ' . $document->getAttribute('outputPath', ''));
} else {
Console::error('Failed to delete build files: ' . $document->getAttribute('outputPath', ''));
}
});
}
// Delete Executions
$this->deleteByGroup('executions', [
new Query('functionId', Query::TYPE_EQUAL, [$document->getId()])
], $dbForProject);
}
/**
* @param Document $document deployment document
* @param string $projectId
*/
protected function deleteDeployment(Document $document, string $projectId): void
{
$dbForProject = $this->getProjectDB($projectId);
$builds = $dbForProject->find('builds', [
new Query('deploymentId', Query::TYPE_EQUAL, [$document->getId()])
], 999);
$buildIds = [];
foreach ($builds as $build) {
$buildIds[] = $build['$id'];
}
/**
* Request executor to delete the deployment containers
*/
try {
$route = "/deployments/{$document->getId()}";
$headers = [
'content-Type' => 'application/json',
'x-appwrite-project' => $projectId,
'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', '')
];
$params = [
'buildIds' => $buildIds ?? []
];
$response = $this->call(self::METHOD_DELETE, $route, $headers, $params, true, 30);
$status = $response['headers']['status-code'];
if ($status >= 400) {
throw new \Exception('Error deleting deplyoment: ' . $document->getId() , $status);
}
} catch (Throwable $th) {
Console::error($th->getMessage());
}
/**
2022-01-29 13:00:25 +13:00
* Delete deployment files
*/
$storageFunctions = new Local(APP_STORAGE_FUNCTIONS . '/app-' . $projectId);
if ($storageFunctions->delete($document->getAttribute('path', ''), true)) {
2022-02-01 12:44:55 +13:00
Console::success('Deleted deployment files: ' . $document->getAttribute('path', ''));
} else {
Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', ''));
}
/**
* Delete builds
*/
$storageBuilds = new Local(APP_STORAGE_BUILDS . '/app-' . $projectId);
$this->deleteByGroup('builds', [
new Query('deploymentId', Query::TYPE_EQUAL, [$document->getId()])
], $dbForProject, function (Document $document) use ($storageBuilds) {
if ($storageBuilds->delete($document->getAttribute('outputPath', ''), true)) {
Console::success('Deleted build files: ' . $document->getAttribute('outputPath', ''));
2021-09-01 21:13:23 +12:00
} else {
Console::error('Failed to delete build files: ' . $document->getAttribute('outputPath', ''));
}
});
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document to be deleted
* @param Database $database to delete it from
* @param callable $callback to perform after document is deleted
*
* @return bool
*/
protected function deleteById(Document $document, Database $database, callable $callback = null): bool
{
Authorization::disable();
if ($database->deleteDocument($document->getCollection(), $document->getId())) {
2021-09-01 21:13:23 +12:00
Console::success('Deleted document "' . $document->getId() . '" successfully');
2021-09-01 21:13:23 +12:00
if (is_callable($callback)) {
$callback($document);
}
return true;
2021-09-01 21:13:23 +12:00
} else {
Console::error('Failed to delete document: ' . $document->getId());
return false;
}
Authorization::reset();
}
2021-07-14 07:24:52 +12:00
/**
* @param callable $callback
*/
2021-08-27 16:37:15 +12:00
protected function deleteForProjectIds(callable $callback): void
2020-12-22 07:15:52 +13:00
{
$count = 0;
$chunk = 0;
$limit = 50;
$projects = [];
$sum = $limit;
2020-12-22 07:15:52 +13:00
$executionStart = \microtime(true);
2021-09-01 21:13:23 +12:00
while ($sum === $limit) {
$projects = Authorization::skip(fn() => $this->getConsoleDB()->find('projects', [], $limit, ($chunk * $limit)));
2021-08-27 16:37:15 +12:00
$chunk++;
/** @var string[] $projectIds */
$projectIds = array_map(fn(Document $project) => $project->getId(), $projects);
$sum = count($projects);
2021-09-01 21:13:23 +12:00
Console::info('Executing delete function for chunk #' . $chunk . '. Found ' . $sum . ' projects');
foreach ($projectIds as $projectId) {
$callback($projectId);
$count++;
}
}
2020-12-22 07:15:52 +13:00
$executionEnd = \microtime(true);
Console::info("Found {$count} projects " . ($executionEnd - $executionStart) . " seconds");
2020-12-22 07:15:52 +13:00
}
2021-07-13 09:57:37 +12:00
/**
* @param string $collection collectionID
* @param Query[] $queries
2021-07-14 07:24:52 +12:00
* @param Database $database
2021-07-13 09:57:37 +12:00
* @param callable $callback
*/
2021-08-27 16:37:15 +12:00
protected function deleteByGroup(string $collection, array $queries, Database $database, callable $callback = null): void
{
$count = 0;
$chunk = 0;
$limit = 50;
$results = [];
$sum = $limit;
$executionStart = \microtime(true);
2021-09-01 21:13:23 +12:00
while ($sum === $limit) {
$chunk++;
2022-01-29 13:52:06 +13:00
Authorization::disable();
$results = $database->find($collection, $queries, $limit, 0);
Authorization::reset();
$sum = count($results);
2021-09-01 21:13:23 +12:00
Console::info('Deleting chunk #' . $chunk . '. Found ' . $sum . ' documents');
foreach ($results as $document) {
$this->deleteById($document, $database, $callback);
$count++;
}
}
$executionEnd = \microtime(true);
Console::info("Deleted {$count} document by group in " . ($executionEnd - $executionStart) . " seconds");
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document certificates document
*/
2021-08-27 16:37:15 +12:00
protected function deleteCertificates(Document $document): void
2021-02-05 22:05:26 +13:00
{
2021-02-05 23:57:43 +13:00
$domain = $document->getAttribute('domain');
2021-02-05 22:05:26 +13:00
$directory = APP_STORAGE_CERTIFICATES . '/' . $domain;
2021-02-06 00:18:12 +13:00
$checkTraversal = realpath($directory) === $directory;
2021-02-05 22:05:26 +13:00
2021-09-01 21:13:23 +12:00
if ($domain && $checkTraversal && is_dir($directory)) {
array_map('unlink', glob($directory . '/*.*'));
2021-02-05 22:05:26 +13:00
rmdir($directory);
2021-02-05 23:57:43 +13:00
Console::info("Deleted certificate files for {$domain}");
} else {
Console::info("No certificate files found for {$domain}");
2021-02-05 22:05:26 +13:00
}
}
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_HEAD = 'HEAD';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_CONNECT = 'CONNECT';
const METHOD_TRACE = 'TRACE';
protected $selfSigned = false;
private $endpoint = 'http://appwrite-executor/v1';
protected $headers = [
'content-type' => '',
];
/**
* Call
*
* Make an API call
*
* @param string $method
* @param string $path
* @param array $params
* @param array $headers
* @param bool $decode
* @return array|string
* @throws Exception
*/
public function call(string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true, int $timeout = 15)
{
$headers = array_merge($this->headers, $headers);
$ch = curl_init($this->endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : ''));
$responseHeaders = [];
$responseStatus = -1;
$responseType = '';
$responseBody = '';
switch ($headers['content-type']) {
case 'application/json':
$query = json_encode($params);
break;
case 'multipart/form-data':
$query = $this->flatten($params);
break;
default:
$query = http_build_query($params);
break;
}
foreach ($headers as $i => $header) {
$headers[] = $i . ':' . $header;
unset($headers[$i]);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
if ($method != self::METHOD_GET) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}
// Allow self signed certificates
if ($this->selfSigned) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$responseBody = curl_exec($ch);
$responseType = $responseHeaders['content-type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($decode) {
switch (substr($responseType, 0, strpos($responseType, ';'))) {
case 'application/json':
$json = json_decode($responseBody, true);
if ($json === null) {
throw new Exception('Failed to parse response: '.$responseBody);
}
$responseBody = $json;
$json = null;
break;
}
}
if ((curl_errno($ch)/* || 200 != $responseStatus*/)) {
throw new Exception(curl_error($ch) . ' with status code ' . $responseStatus, $responseStatus);
}
curl_close($ch);
$responseHeaders['status-code'] = $responseStatus;
if ($responseStatus === 500) {
echo 'Server error('.$method.': '.$path.'. Params: '.json_encode($params).'): '.json_encode($responseBody)."\n";
}
return [
'headers' => $responseHeaders,
'body' => $responseBody
];
}
/**
* Parse Cookie String
*
* @param string $cookie
* @return array
*/
public function parseCookie(string $cookie): array
{
$cookies = [];
parse_str(strtr($cookie, array('&' => '%26', '+' => '%2B', ';' => '&')), $cookies);
return $cookies;
}
/**
* Flatten params array to PHP multiple format
*
* @param array $data
* @param string $prefix
* @return array
*/
protected function flatten(array $data, string $prefix = ''): array
{
$output = [];
foreach ($data as $key => $value) {
$finalKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
$output += $this->flatten($value, $finalKey); // @todo: handle name collision here if needed
} else {
$output[$finalKey] = $value;
}
}
return $output;
}
2021-09-01 21:13:23 +12:00
}