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,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;
}
}