This commit is contained in:
2022-11-25 20:52:52 -03:00
parent dd0410a0fb
commit efed50cd7f
39 changed files with 2777 additions and 5 deletions

View File

@ -0,0 +1,60 @@
<?php
namespace ProVM\Common\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use function Safe\json_decode;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Attachments as Service;
class Attachments
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$attachments = array_map(function($attachment) {
$attachment['original_attachment'] = $attachment['original_attachment']->getRealPath();
if (isset($attachment['decrypted_attachment']) and $attachment['decrypted_attachment'] !== false) {
$attachment['decrypted_attachment'] = $attachment['decrypted_attachment']->getRealPath();
}
return $attachment;
}, $service->fetchFullAttachments());
return $this->withJson($response, compact('attachments'));
}
protected function fileToArray(\SplFileInfo $info): array
{
return [
'filename' => $info->getFilename(),
'path' => $info->getPath(),
'full_name' => $info->getRealPath(),
'extension' => $info->getExtension()
];
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = json_decode($body);
if (!is_array($json)) {
$json = [$json];
}
$output = ['input' => $json, 'attachments' => []];
foreach ($json as $attachment) {
$output['attachments'] []= $this->fileToArray($service->getAttachment($json->attachment));
}
return $this->withJson($response, $output);
}
public function decrypt(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = json_decode($body);
if (!is_array($json)) {
$json = [$json];
}
$output = ['input' => $json, 'attachments' => []];
foreach ($json as $attachment) {
$output['attachments'] []= $this->fileToArray($service->removeEncryption($attachment));
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,141 @@
<?php
namespace ProVM\Common\Controller;
use Ddeboer\Imap\MailboxInterface;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Emails\Repository\Mailbox;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Service\Emails as Service;
use Psr\Log\LoggerInterface;
use Safe\Exceptions\FilesystemException;
class Emails
{
use Json;
public function __construct(LoggerInterface $logger)
{
$this->setLogger($logger);
}
protected LoggerInterface $logger;
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setLogger(LoggerInterface $logger): Emails
{
$this->logger = $logger;
return $this;
}
public function mailboxes(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$mailboxes = array_map(function(MailboxInterface $mailbox) {
return ['name' => $mailbox->getName(), 'message_count' => $mailbox->count()];
}, array_values($service->getMailboxes()->getAll()));
return $this->withJson($response, compact('mailboxes'));
}
public function messages(ServerRequestInterface $request, ResponseInterface $response, Service $service, Mailbox $repository): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = \Safe\json_decode($body);
$mailbox = $repository->fetchById($json->mailbox);
$remote_mailbox = $service->getMailboxes()->get($mailbox->getName());
$messages = $service->getMessages($remote_mailbox, $json->start ?? 0, $json->amount ?? null);
$mails = [];
foreach ($messages as $message) {
$mails []= [
'position' => $message->getPosition(),
'uid' => $message->getUID(),
'subject' => $message->getSubject(),
'date' => $message->getDateTime()->format('Y-m-d H:i:s'),
'from' => $message->getFrom(),
'has_attachments' => $message->hasAttachments(),
'valid_attachments' => $message->hasValidAttachments(),
'downloaded_attachments' => $message->hasDownloadedAttachments()
];
}
return $this->withJson($response, [
'input' => $json,
'total' => $mailbox->count(),
'messages' => $mails
]);
}
public function withAttachments(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = \Safe\json_decode($body);
$mailbox = $service->getMailboxes()->get($json->mailbox);
$messages = $service->getValidMessages($mailbox, $json->start ?? 0, $json->amount ?? null);
$mails = [];
foreach ($messages as $message) {
$mails []= [
'position' => $message->getPosition(),
'uid' => $message->getUID(),
'subject' => $message->getSubject(),
'date' => $message->getDateTime()->format('Y-m-d H:i:s'),
'from' => $message->getFrom(),
'has_attachments' => $message->hasAttachments(),
'valid_attachments' => $message->hasValidAttachments(),
'downloaded_attachments' => $message->hasDownloadedAttachments()
];
}
return $this->withJson($response, [
'input' => $json,
'total' => $service->getMailboxes()->countValid($mailbox),
'messages' => $mails
]);
}
public function attachments(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = \Safe\json_decode($body);
$mailbox = $service->getMailboxes()->get($json->mailbox);
$messages = $service->getMessages($mailbox, $json->start ?? 0, $json->amount ?? null);
$cnt = 0;
$attachments = [];
foreach ($messages as $message) {
$attachments = array_merge($attachments, $service->saveAttachments($message, $json->extension ?? null));
$cnt ++;
}
return $this->withJson($response, [
'input' => $json,
'messages_count' => $cnt,
'attachments_count' => count($attachments),
'attachments' => $attachments
]);
}
public function attachment(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody()->getContents();
$json = \Safe\json_decode($body);
$mailbox = $service->getMailbox($json->mailbox);
$cnt = 0;
$attachments = [];
$errors = [];
foreach ($json->messages as $uid) {
$message = $service->getMessage($mailbox, $uid);
try {
$attachments = array_merge($attachments, $service->saveAttachments($message, $json->extension ?? null));
} catch (FilesystemException $e) {
$errors []= [
'message' => $uid,
'error' => $e->getMessage()
];
}
$cnt ++;
}
$output = [
'input' => $json,
'messages_count' => $cnt,
'attachments_count' => count($attachments),
'attachments' => $attachments
];
if (count($errors) > 0) {
$output['errors'] = $errors;
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace ProVM\Common\Controller;
use ProVM\Common\Implement\Controller\Json;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Exception;
use ProVM\Common\Service\Install as Service;
class Install
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
try {
$service->run();
return $this->withJson($response, [
'message' => 'Install finished'
]);
} catch (Exception $e) {
return $this->withJson($response, [
'message' => 'Install with error',
'error' => $e->getMessage()
]);
}
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace ProVM\Common\Controller;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Emails\Repository\Mailbox;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class Mailboxes
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \ProVM\Common\Service\Mailboxes $service, Mailbox $repository): ResponseInterface
{
$source_mailboxes = $service->getAll();
$mailboxes = [];
foreach ($source_mailboxes as $mailbox) {
$m = [
'name' => $mailbox->getName(),
'registered' => false
];
try {
$s = $repository->fetchByName($mailbox->getName());
$m['registered'] = true;
$m['id'] = $s->getId();
} catch (BlankResult $e) {
}
$mailboxes []= $m;
}
return $this->withJson($response, compact('mailboxes'));
}
public function register(ServerRequestInterface $request, ResponseInterface $response, \ProVM\Common\Service\Mailboxes $service, Mailbox $repository): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
$output = ['input' => $json, 'mailboxes' => []];
foreach ($json->mailboxes as $mailbox) {
try {
$model = $repository->create([
'name' => $mailbox
]);
$output['mailboxes'] []= ['name' => $mailbox, 'created' => true, 'id' => $model->getId()];
} catch (\PDOException $e) {
$output['mailboxes'] []= ['name' => $mailbox, 'created' => false];
}
}
return $this->withJson($response, $output);
}
public function unregister(ServerRequestInterface $request, ResponseInterface $response, Mailbox $repository): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
$output = ['input' => $json, 'mailboxes' => []];
foreach ($json->mailboxes as $id) {
try {
$mailbox = $repository->fetchById($id);
try {
$repository->delete($mailbox);
$output['mailboxes'] []= ['name' => $mailbox->getName(), 'id' => $id, 'removed' => true];
} catch (\PDOException $e) {
$output['mailboxes'] []= ['name' => $mailbox->getName(), 'id' => $id, 'removed' => false];
}
} catch (\PDOException | BlankResult $e) {
$output['mailboxes'] []= ['id' => $id, 'removed' => false];
}
}
return $this->withJson($response, $output);
}
public function registered(ServerRequestInterface $request, ResponseInterface $response, Mailbox $repository): ResponseInterface
{
$data = $repository->fetchAll();
$mailboxes = array_map(function(\ProVM\Emails\Model\Mailbox $mailbox) {
return $mailbox->toArray();
}, $data);
return $this->withJson($response, compact('mailboxes'));
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Mailbox $repository, int $mailbox_id): ResponseInterface
{
$mailbox = $repository->fetchById($mailbox_id);
return $this->withJson($response, ['mailbox' => $mailbox->toArray()]);
}
}

View File

@ -0,0 +1,117 @@
<?php
namespace ProVM\Common\Controller;
use Ddeboer\Imap\MessageInterface;
use ProVM\Common\Factory\Model;
use ProVM\Emails\Model\State\Mailbox;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Mailboxes as Service;
use ProVM\Emails\Repository\Message;
use Safe\DateTimeImmutable;
class Messages
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Message $repository): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
$messages = [];
foreach ($json->mailboxes as $mailbox_id) {
$messages = array_merge($messages, $repository->fetchByMailbox($mailbox_id) ?? []);
}
$messages = array_map(function(\ProVM\Emails\Model\Message $message) {
return $message->toArray();
}, $messages);
return $this->withJson($response, ['messages' => $messages, 'total' => count($messages)]);
}
public function valid(ServerRequestInterface $request, ResponseInterface $response, Message $repository): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
$messages = [];
foreach ($json->mailboxes as $mailbox_id) {
try {
$messages = array_merge($messages, $repository->fetchByMailbox($mailbox_id) ?? []);
} catch (BlankResult $e) {
}
}
$messages = array_values(array_map(function(\ProVM\Emails\Model\Message $message) {
return $message->toArray();
}, array_filter($messages, function(\ProVM\Emails\Model\Message $message) {
return $message->hasValidAttachments();
})));
return $this->withJson($response, ['messages' => $messages, 'total' => count($messages)]);
}
public function grab(ServerRequestInterface $request, ResponseInterface $response, Model $factory, Service $service): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
$message_count = 0;
foreach ($json->mailboxes as $mailbox_name) {
$message_count += $this->grabFromMailbox($factory, $service, $mailbox_name);
}
return $this->withJson($response, compact('message_count'));
}
protected function grabFromMailbox(Model $factory, Service $service, string $mailbox_name): int
{
$mailbox = $factory->find(\ProVM\Emails\Model\Mailbox::class)->fetchByName($mailbox_name);
$stored = array_reduce($mailbox->getStates(), function($count, Mailbox $state) {
return $count + $state->getCount();
}) ?? 0;
$remote_mailbox = $service->get($mailbox->getName());
$total = $remote_mailbox->count();
if ($stored >= $total) {
return 0;
}
$added = 0;
$uids = [];
$amount = $total - $stored;
$messages = $service->getMessages($remote_mailbox, $stored, $amount);
foreach ($messages as $j => $m) {
if ($this->addMessage($factory->find(\ProVM\Emails\Model\Message::class), $service, $mailbox, $m, $j + 1)) {
$uids []= $m->getId();
$added ++;
}
}
if ($added > 0 ) {
$data = [
'mailbox_id' => $mailbox->getId(),
'date_time' => (new DateTimeImmutable('now'))->format('Y-m-d H:i:s'),
'count' => $added,
'uids' => serialize($uids)
];
$state = $factory->find(\ProVM\Emails\Model\State\Mailbox::class)->create($data);
$factory->find(\ProVM\Emails\Model\State\Mailbox::class)->save($state);
}
return $added;
}
protected function addMessage(Message $repository, Service $service, \ProVM\Emails\Model\Mailbox $mailbox, MessageInterface $remote_message, int $position): bool
{
$data = [
'mailbox_id' => $mailbox->getId(),
'position' => $position,
'uid' => $remote_message->getId(),
'subject' => $remote_message->getSubject() ?? '',
'from' => $remote_message->getFrom()->getFullAddress(),
'date_time' => $remote_message->getDate()->format('Y-m-d H:i:s')
];
$message = $repository->create($data);
if ($message->getId() === 0) {
if ($remote_message->hasAttachments()) {
$message->doesHaveAttachments();
}
if ($service->validAttachments($remote_message)) {
$message->doesHaveValidAttachments();
}
$repository->save($message);
return true;
}
return false;
}
}

View File

@ -0,0 +1,6 @@
<?php
namespace ProVM\Common\Define;
interface Model
{
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception\Database;
use Exception;
class BlankResult extends Exception
{
public function __construct(?Throwable $previous = null)
{
$message = "No results found";
$code = 300;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception;
use Exception;
class EmptyMailbox extends Exception
{
public function __construct(?Throwable $previous = null)
{
$message = "No mails found";
$code = 102;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception\Mailbox;
use Exception;
class Invalid extends Exception
{
public function __construct(?Throwable $previous = null)
{
$message = "Mailbox not found";
$code = 100;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace ProVM\Common\Factory;
use ProVM\Common\Implement\Repository;
use Psr\Container\ContainerInterface;
class Model
{
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
}
protected ContainerInterface $container;
protected array $repositories;
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function getRepositories(): array
{
return $this->repositories;
}
public function getRepository(string $name): string
{
return $this->getRepositories()[$name];
}
public function setContainer(ContainerInterface $container): Model
{
$this->container = $container;
return $this;
}
public function addRepository(string $name, string $repository_class_name): Model
{
$this->repositories[$name] = $repository_class_name;
return $this;
}
public function setRepositories(array $repositories): Model
{
foreach ($repositories as $name => $class) {
$this->addRepository($name, $class);
}
return $this;
}
public function find(string $model_class_name): Repository
{
$name = str_replace("ProVM\\Emails\\Model\\", '', $model_class_name);
try {
$repository_class = $this->getRepository($name);
} catch (\Exception $e) {
$repository_class = str_replace('Model', 'Repository', $model_class_name);
}
return $this->getContainer()->get($repository_class);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace ProVM\Common\Implement\Controller;
use Psr\Http\Message\ResponseInterface;
trait Json
{
public function withJson(ResponseInterface $response, mixed $data, int $status = 200): ResponseInterface
{
$response->getBody()->write(\Safe\json_encode($data));
return $response
->withStatus($status)
->withHeader('Content-Type', 'application/json');
}
}

View File

@ -0,0 +1,185 @@
<?php
namespace ProVM\Common\Implement;
use PDO;
use ProVM\Common\Exception\Database\BlankResult;
use Psr\Log\LoggerInterface;
use ProVM\Common\Define\Model as ModelInterface;
abstract class Repository
{
public function __construct(PDO $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
protected PDO $connection;
protected string $table;
protected LoggerInterface $logger;
public function getConnection(): PDO
{
return $this->connection;
}
public function getTable(): string
{
return $this->table;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setConnection(PDO $pdo): Repository
{
$this->connection = $pdo;
return $this;
}
public function setTable(string $table): Repository
{
$this->table = $table;
return $this;
}
public function setLogger(LoggerInterface $logger): Repository
{
$this->logger = $logger;
return $this;
}
abstract protected function fieldsForUpdate(): array;
abstract protected function valuesForUpdate(ModelInterface $model): array;
protected function idProperty(): string
{
return 'getId';
}
protected function idField(): string
{
return 'id';
}
public function update(ModelInterface $model, ModelInterface $old): void
{
$query = "UPDATE `{$this->getTable()}` SET ";
$model_values = $this->valuesForUpdate($model);
$old_values = $this->valuesForUpdate($old);
$columns = [];
$values = [];
foreach ($this->fieldsForUpdate() as $column => $method) {
if (isset($model_values[$column]) and $old_values[$column] !== $model_values[$column]) {
$columns []= "`{$column}`";
$values []= $model_values[$column];
}
}
if (count($columns) === 0) {
return;
}
$query .= implode(', ', $columns) . " WHERE {$this->idField()} = ?";
$values []= $old->{$this->idProperty()}();
$st = $this->getConnection()->prepare($query);
$st->execute($values);
}
abstract protected function fieldsForInsert(): array;
abstract protected function valuesForInsert(ModelInterface $model): array;
protected function insert(ModelInterface $model): void
{
$fields = $this->fieldsForInsert();
$fields_string = implode(', ', array_map(function($field) {
return "`{$field}`";
}, $fields));
$fields_questions = implode(', ', array_fill(0, count($fields), '?'));
$query = "INSERT INTO `{$this->getTable()}` ({$fields_string}) VALUES ({$fields_questions})";
$values = $this->valuesForInsert($model);
$st = $this->getConnection()->prepare($query);
$st->execute($values);
}
abstract protected function defaultFind(ModelInterface $model): ModelInterface;
public function save(ModelInterface &$model): void
{
try {
$old = $this->defaultFind($model);
$this->update($model, $old);
} catch (BlankResult $e) {
$this->insert($model);
$model->setId($this->getConnection()->lastInsertId());
} catch (\Error | \Exception $e) {
$this->getLogger()->error($e);
}
}
abstract public function load(array $row): ModelInterface;
abstract protected function fieldsForCreate(): array;
abstract protected function valuesForCreate(array $data): array;
abstract protected function defaultSearch(array $data): ModelInterface;
public function create(array $data): ModelInterface
{
try {
return $this->defaultSearch($data);
} catch (PDOException | BlankResult $e) {
$data[$this->idField()] = 0;
return $this->load($data);
}
}
protected function getId(ModelInterface $model): int
{
return $model->getId();
}
public function resetIndex(): void
{
$query = "ALTER TABLE `{$this->getTable()}` AUTO_INCREMENT = 1";
$this->getConnection()->query($query);
}
public function optimize(): void
{
$query = "OPTIMIZE TABLE `{$this->getTable()}`";
$this->getConnection()->query($query);
}
public function delete(ModelInterface $model): void
{
$query = "DELETE FROM `{$this->getTable()}` WHERE `{$this->idField()}` = ?";
$st = $this->getConnection()->prepare($query);
$st->execute([$this->getId($model)]);
$this->resetIndex();
$this->optimize();
}
protected function fetchOne(string $query, ?array $values = null): ModelInterface
{
if ($values !== null) {
$st = $this->getConnection()->prepare($query);
$st->execute($values);
} else {
$st = $this->getConnection()->query($query);
}
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) {
throw new BlankResult();
}
return $this->load($row);
}
protected function fetchMany(string $query, ?array $values = null): array
{
if ($values !== null) {
$st = $this->getConnection()->prepare($query);
$st->execute($values);
} else {
$st = $this->getConnection()->query($query);
}
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
if (!$rows) {
throw new BlankResult();
}
return array_map([$this, 'load'], $rows);
}
public function fetchAll(): array
{
$query = "SELECT * FROM `{$this->getTable()}`";
return $this->fetchMany($query);
}
public function fetchById(int $id): ModelInterface
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `{$this->idField()}` = ?";
return $this->fetchOne($query, [$id]);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace ProVM\Common\Middleware;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
class Auth
{
public function __construct(ResponseFactoryInterface $factory, LoggerInterface $logger, string $api_key)
{
$this->setResponseFactory($factory);
$this->setLogger($logger);
$this->setAPIKey($api_key);
}
protected ResponseFactoryInterface $factory;
protected LoggerInterface $logger;
protected string $api_key;
public function getResponseFactory(): ResponseFactoryInterface
{
return $this->factory;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function getAPIKey(): string
{
return $this->api_key;
}
public function setResponseFactory(ResponseFactoryInterface $factory): Auth
{
$this->factory = $factory;
return $this;
}
public function setLogger(LoggerInterface $logger): Auth
{
$this->logger = $logger;
return $this;
}
public function setAPIKey(string $key): Auth
{
$this->api_key = $key;
return $this;
}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'OPTIONS') {
return $handler->handle($request);
}
$auths = $request->getHeader('Authorization');
foreach ($auths as $auth) {
if (str_contains($auth, 'Bearer')) {
$key = str_replace('Bearer ', '', $auth);
if (sha1($this->getAPIKey()) === $key) {
return $handler->handle($request);
}
}
}
$response = $this->getResponseFactory()->createResponse(401);
$response->getBody()->write(\Safe\json_encode(['error' => 401, 'message' => 'Incorrect token']));
return $response
->withHeader('Content-Type', 'application/json');
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace ProVM\Common\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CORS
{
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
$request
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range')
->withHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE,PATCH');
return $response;
}
}

View File

@ -0,0 +1,159 @@
<?php
namespace ProVM\Common\Service;
use Ddeboer\Imap\Message\AttachmentInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Emails\Model\Attachment;
use ProVM\Emails\Model\Message;
class Attachments
{
public function __construct(Decrypt $decrypt, \ProVM\Emails\Repository\Attachment $repository, string $attachments_folder)
{
$this->setDecrypt($decrypt);
$this->setAttachmentsFolder($attachments_folder);
}
protected string $attachments_folder;
protected Decrypt $decrypt;
protected \ProVM\Emails\Repository\Attachment $repository;
public function getAttachmentsFolder(): string
{
return $this->attachments_folder;
}
public function getDecrypt(): Decrypt
{
return $this->decrypt;
}
public function getRepository(): \ProVM\Emails\Repository\Attachment
{
return $this->repository;
}
public function setAttachmentsFolder(string $folder): Attachments
{
$this->attachments_folder = $folder;
return $this;
}
public function setDecrypt(Decrypt $decrypt): Attachments
{
$this->decrypt = $decrypt;
return $this;
}
public function setRepository(\ProVM\Emails\Repository\Attachment $repository): Attachments
{
$this->repository = $repository;
return $this;
}
public function validateAttachment(AttachmentInterface $remote_attachment): bool
{
return str_contains($remote_attachment->getFilename(), '.pdf');
}
public function buildAttachment(Message $message, AttachmentInterface $remote_attachment): Attachment
{
$data = [
'message_id' => $message->getId(),
'filename' => $this->buildFilename($message, $remote_attachment)
];
return $this->getRepository()->create($data);
}
public function exists(Attachment $attachment): bool
{
$filename = $this->buildFilename($attachment);
return file_exists($filename);
}
public function buildFilename(Message $message, AttachmentInterface $attachment): string
{
$filename = implode(' - ', [
$message->getSubject(),
$message->getDateTime()->format('Y-m-d'),
$attachment->getFilename()
]);
return implode(DIRECTORY_SEPARATOR, [
$this->getAttachmentsFolder(),
$filename
]);
}
public function checkEncrypted(): array
{
$output = [];
foreach ($this->fetchAttachments() as $attachment) {
$output[$attachment->getFilename()] = $this->getDecrypt()->isEncrypted($attachment->getRealPath());
}
return $output;
}
public function fetchAttachments(): array
{
$files = new \FilesystemIterator($this->getAttachmentsFolder());
$attachments = [];
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
$attachments []= $file;
}
return $attachments;
}
public function fetchDecryptedAttachments(): array
{
$folder = implode(DIRECTORY_SEPARATOR, [$this->getAttachmentsFolder(), 'decrypted']);
$files = new \FilesystemIterator($folder);
$attachments = [];
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
$attachments []= $file;
}
return $attachments;
}
public function fetchFullAttachments(): array
{
$attachments = $this->fetchAttachments();
$output = [];
foreach ($attachments as $attachment) {
$att = [
'original_attachment' => $attachment,
'encrypted' => $this->getDecrypt()->isEncrypted($attachment->getRealPath())
];
if ($att['encrypted']) {
$att['decrypted_attachment'] = $this->getDecryptedAttachment($attachment);
}
$output []= $att;
}
return $output;
}
public function getAttachment(string $filename): \SplFileInfo
{
if (!str_contains($filename, $this->getAttachmentsFolder())) {
$filename = implode(DIRECTORY_SEPARATOR, [$this->getAttachmentsFolder(), $filename]);
}
return new \SplFileInfo($filename);
}
public function getDecryptedAttachment(\SplFileInfo $info): \SplFileInfo|bool
{
$new_file = implode(DIRECTORY_SEPARATOR, [$info->getPath(), 'decrypted', $info->getFilename()]);
if (!file_exists($new_file)) {
return false;
}
return new \SplFileInfo($new_file);
}
public function removeEncryption(string $filename): \SplFileInfo
{
$attachment = $this->getAttachment($filename);
$new_file = implode(DIRECTORY_SEPARATOR, [$attachment->getPath(), 'decrypted', $attachment->getFilename()]);
if ($this->getDecrypt()->runCommand($attachment->getRealPath(), $new_file)) {
return new \SplFileInfo($new_file);
}
return $attachment;
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
abstract class Base
{
protected LoggerInterface $logger;
/**
* @return LoggerInterface
*/
public function getLogger(): LoggerInterface
{
return $this->logger;
}
/**
* @param LoggerInterface $logger
* @return $this
*/
public function setLogger(LoggerInterface $logger): Base
{
$this->logger = $logger;
return $this;
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
use function Safe\exec;
class Decrypt
{
public function __construct(LoggerInterface $logger, string $base_command, array $passwords)
{
$this->setLogger($logger);
$this->setBaseCommand($base_command);
$this->setPasswords($passwords);
}
protected array $passwords;
protected string $base_command;
protected LoggerInterface $logger;
public function getPasswords(): array
{
return $this->passwords;
}
public function getBaseCommand(): string
{
return $this->base_command;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function addPassword(string $password): Decrypt
{
$this->passwords []= $password;
return $this;
}
public function setPasswords(array $passwords): Decrypt
{
foreach ($passwords as $password) {
$this->addPassword($password);
}
return $this;
}
public function setBaseCommand(string $command): Decrypt
{
$this->base_command = $command;
return $this;
}
public function setLogger(LoggerInterface $logger): Decrypt
{
$this->logger = $logger;
return $this;
}
public function isEncrypted(string $filename): bool
{
if (!file_exists($filename)) {
throw new \InvalidArgumentException("File not found {$filename}");
}
$escaped_filename = escapeshellarg($filename);
$cmd = "{$this->getBaseCommand()} --is-encrypted {$escaped_filename}";
exec($cmd, $output, $retcode);
return $retcode == 0;
}
public function buildCommand(string $in_file, string $out_file, string $password): string
{
return $this->getBaseCommand() . ' -password=' . escapeshellarg($password) . ' -decrypt ' . escapeshellarg($in_file) . ' ' . escapeshellarg($out_file);
}
public function runCommand(string $in_file, string $out_file): bool
{
if (file_exists($out_file)) {
return true;
}
foreach ($this->getPasswords() as $password) {
$cmd = $this->buildCommand($in_file, $out_file, $password);
exec($cmd, $output, $retcode);
$success = $retcode == 0;
if ($success) {
return true;
}
if (file_exists($out_file)) {
unlink($out_file);
}
unset($output);
}
return false;
}
}

View File

@ -0,0 +1,158 @@
<?php
namespace ProVM\Common\Service;
use Iterator;
use Generator;
use ProVM\Common\Exception\EmptyMailbox;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Emails\Repository\Message;
class Emails extends Base
{
public function __construct(Mailboxes $mailboxService, Message $messageRepository, string $attachments_folder)
{
$this->setMailboxes($mailboxService);
$this->setMessageRepository($messageRepository);
$this->setAttachmentsFolder($attachments_folder);
}
protected Message $messageRepository;
protected Mailboxes $mailboxService;
protected string $attachments_folder;
public function getMailboxes(): Mailboxes
{
return $this->mailboxService;
}
public function getMessageRepository(): Message
{
return $this->messageRepository;
}
public function getAttachmentsFolder(): string
{
return $this->attachments_folder;
}
public function setMailboxes(Mailboxes $mailboxService): Emails
{
$this->mailboxService = $mailboxService;
return $this;
}
public function setMessageRepository(Message $messageRepository): Emails
{
$this->messageRepository = $messageRepository;
return $this;
}
public function setAttachmentsFolder(string $folder): Emails
{
$this->attachments_folder = $folder;
return $this;
}
//----------------------------------------------------------------
// Messages
public function getMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
$output = [];
$cnt = 0;
$messages = $this->getMessageRepository()->fetchByMailboxAndPosition($mailbox->getName(), $start, $amount ?? 1);
if ($messages) {
foreach ($messages as $message) {
$output []= $message;
$cnt ++;
}
}
if ($amount === null or $cnt < $amount) {
$messages = $this->getMailboxes()->getMessages($mailbox, $cnt + $start, $amount ?? $mailbox->count());
foreach ($messages as $m) {
$message = $this->saveMessage($mailbox, $m, $cnt + $start);
$cnt ++;
if ($message === null) {
continue;
}
$output []= $message;
}
}
return $output;
}
public function saveMessage(MailboxInterface $mailbox, MessageInterface $message, int $position): ?\ProVM\Emails\Model\Message
{
$data = [
'mailbox_id' => $mailbox->getId(),
'position' => $position,
'uid' => $message->getNumber(),
'subject' => $message->getSubject(),
'from' => $message->getFrom()->getFullAddress(),
'date_time' => $message->getDate()->format('Y-m-d H:i:s'),
];
return $this->getMessageRepository()->create($data);
}
public function getValidMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
$messages = $this->getMessages($mailbox, $start, $amount);
$output = array_filter($messages, function(\ProVM\Emails\Model\Message $message) {
return ($message->hasAttachments() and $message->hasValidAttachments());
});
if ($amount === null or count($output) >= $amount) {
return $output;
}
$cnt = $start + $amount;
while (count($output) < $amount) {
\Safe\ini_set('max_execution_time', ((int) \Safe\ini_get('max_execution_time')) + $amount * 5);
$messages = $this->getMailboxes()->getMessages($mailbox, $start + $amount, $amount);
foreach ($messages as $m) {
$message = $this->saveMessage($mailbox, $m, $cnt + $start);
$cnt ++;
if ($message === null) {
continue;
}
if ($message->hasAttachments() and $message->hasValidAttachments() and count($output) < $amount) {
$output []= $message;
}
}
}
return $output;
}
// Attachments
public function saveAttachments(MessageInterface $message, ?string $extension = null): array
{
if (!$message->hasAttachments()) {
return [];
}
$attachments = [];
foreach ($message->getAttachments() as $attachment) {
$this->getLogger()->debug($attachment->getFilename());
if ($extension !== null) {
$extension = trim($extension, '.');
if (!str_contains($attachment->getFilename(), ".{$extension}")) {
continue;
}
}
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getAttachmentsFolder(),
"{$message->getSubject()} - {$message->getDate()->format('Y-m-d')} - {$attachment->getFilename()}"
]);
$this->getLogger()->debug($filename);
\Safe\file_put_contents($filename, $attachment->getDecodedContent());
$attachments []= $filename;
}
return $attachments;
}
public function getAttachments(?string $mailbox = null, int $start = 0, ?int $amount = null, ?string $extension = null): array
{
if ($mailbox === null) {
$mailbox = '/';
}
$mb = $this->getMailboxes()->get($mailbox);
$messages = $this->getMessages($mb, $start, $amount);
$attachments = [];
foreach ($messages as $message) {
$attachments = array_merge($attachments, $this->saveAttachments($message, $extension));
}
return $attachments;
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
use PDO;
class Install
{
public function __construct(LoggerInterface $logger, PDO $pdo)
{
$this->setLogger($logger);
$this->setConnection($pdo);
}
protected LoggerInterface $logger;
protected PDO $connection;
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function getConnection(): PDO
{
return $this->connection;
}
public function setLogger(LoggerInterface $logger): Install
{
$this->logger = $logger;
return $this;
}
public function setConnection(PDO $pdo): Install
{
$this->connection = $pdo;
return $this;
}
public function run(): void
{
$tables = [
'messages' => [
'`mailbox_id` int UNSIGNED NOT NULL',
'`position` int UNSIGNED NOT NULL',
'`uid` int UNSIGNED NOT NULL PRIMARY KEY',
'`subject` varchar(255) NOT NULL',
'`from` varchar(100) NOT NULL',
'`date_time` datetime NOT NULL',
'`has_attachments` int(1) DEFAULT 0',
'`valid_attachments` int(1) DEFAULT 0',
'`downloaded_attachments` int(1) DEFAULT 0'
],
'attachments' => [
'`message_uid` int UNSIGNED NOT NULL',
'`filename` varchar(255) NOT NULL PRIMARY KEY',
'`encrypted` int(1) DEFAULT 0',
'`decrypted` int(1) DEFAULT 0',
'CONSTRAINT `message_uid_fk` FOREIGN KEY (`message_uid`) REFERENCES `messages` (`uid`)'
],
'mailboxes' => [
'`'
]
];
foreach ($tables as $table => $definitions) {
$this->getConnection()->query($this->buildCreateTable($table, $definitions));
}
}
protected function buildCreateTable(string $table_name, array $columns): string
{
$query = ["CREATE TABLE IF NOT EXISTS `{$table_name}` ("];
$query []= implode(',' . PHP_EOL, $columns);
$query []= ')';
return implode(PHP_EOL, $query);
}
}

View File

@ -0,0 +1,151 @@
<?php
namespace ProVM\Common\Service;
use Ddeboer\Imap\Message\AttachmentInterface;
use Iterator;
use Generator;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Common\Exception\EmptyMailbox;
use ProVM\Common\Exception\Mailbox\Invalid;
class Mailboxes extends Base
{
public function __construct(ConnectionInterface $connection, Attachments $attachments, string $username)
{
$this->setConnection($connection)
->setAttachments($attachments)
->setUsername($username);
}
protected ConnectionInterface $connection;
protected Attachments $attachments;
protected string $username;
public function getConnection(): ConnectionInterface
{
return $this->connection;
}
public function getAttachments(): Attachments
{
return $this->attachments;
}
public function getUsername(): string
{
return $this->username;
}
public function setConnection(ConnectionInterface $connection): Mailboxes
{
$this->connection = $connection;
return $this;
}
public function setAttachments(Attachments $attachments): Mailboxes
{
$this->attachments = $attachments;
return $this;
}
public function setUsername(string $username): Mailboxes
{
$this->username = $username;
return $this;
}
protected array $mailboxes;
public function getAll(): array
{
if (!isset($this->mailboxes)) {
$this->mailboxes = $this->getConnection()->getMailboxes();
}
return $this->mailboxes;
}
public function get(string $mailbox): MailboxInterface
{
if (!$this->getConnection()->hasMailbox($mailbox)) {
throw new Invalid();
}
return $this->getConnection()->getMailbox($mailbox);
}
// Messages
protected function advanceIterator(Iterator $iterator, int $up_to): Iterator
{
for ($i = 0; $i < $up_to; $i ++) {
$iterator->next();
}
return $iterator;
}
public function getMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): Generator
{
if ($mailbox->count() === 0) {
$this->getLogger()->notice('No mails found.');
throw new EmptyMailbox();
}
$it = $mailbox->getIterator();
if ($amount === null) {
$amount = $mailbox->count() - $start;
}
$it = $this->advanceIterator($it, $start);
for ($i = $start; $i < min($start + $amount, $mailbox->count()); $i ++) {
yield $it->key() => $it->current();
$it->next();
}
}
public function countValid(MailboxInterface $mailbox): int
{
$cnt = 0;
foreach ($mailbox->getIterator() as $message) {
if ($this->hasAttachments($message) and $this->validAttachments($message)) {
$cnt ++;
}
}
return $cnt;
}
/**
* @param MailboxInterface $mailbox
* @param int $uid
* @return MessageInterface
*/
public function getMessage(MailboxInterface $mailbox, int $uid): MessageInterface
{
return $mailbox->getMessage($uid);
}
protected function validateAddress(array $to): bool
{
foreach ($to as $address) {
if (strtolower($address->getAddress()) === strtolower($this->getUsername())) {
return true;
}
}
return false;
}
public function hasAttachments(MessageInterface $message): bool
{
return ($message->hasAttachments() and $this->validateAddress($message->getTo()));
}
protected function validateAttachment(AttachmentInterface $attachment): bool
{
return str_contains($attachment->getFilename(), '.pdf');
}
public function validAttachments(MessageInterface $message): bool
{
foreach ($message->getAttachments() as $attachment) {
if ($this->validateAttachment($attachment)) {
return true;
}
}
return false;
}
public function downloadAttachments(MessageInterface $message)
{
foreach ($message->getAttachments() as $attachment) {
if ($this->validateAttachment($attachment)) {
$attachment->getContent();
}
}
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace ProVM\Common\Service;
use ProVM\Common\Factory\Model;
use Psr\Log\LoggerInterface;
class Messages
{
public function __construct(Model $factory, LoggerInterface $logger)
{
$this->setFactory($factory)
->setLogger($logger);
}
protected Model $factory;
protected LoggerInterface $logger;
public function getFactory(): Model
{
return $this->factory;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setFactory(Model $factory): Messages
{
$this->factory = $factory;
return $this;
}
public function setLogger(LoggerInterface $logger): Messages
{
$this->logger = $logger;
return $this;
}
}