103 lines
2.9 KiB
PHP
103 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier\mailer;
|
|
|
|
use PDO;
|
|
|
|
|
|
/**
|
|
* Queues up mails and sends them when appropriate.
|
|
*/
|
|
class MailManager
|
|
{
|
|
/**
|
|
* @var PDO the database connection to interact with
|
|
*/
|
|
private PDO $conn;
|
|
|
|
|
|
/**
|
|
* Constructs a new mailer.
|
|
*
|
|
* @param PDO $conn the connection to the email database
|
|
*/
|
|
public function __construct(PDO $conn)
|
|
{
|
|
$this->conn = $conn;
|
|
}
|
|
|
|
|
|
/**
|
|
* Populates the database with the necessary structures for emails.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function install(): void
|
|
{
|
|
$this->conn->exec("CREATE TABLE email_tasks(type TEXT NOT NULL,
|
|
recipient TEXT NOT NULL,
|
|
arg1 TEXT NOT NULL DEFAULT(''),
|
|
arg2 TEXT NOT NULL DEFAULT(''),
|
|
PRIMARY KEY (type, recipient, arg1, arg2));");
|
|
}
|
|
|
|
|
|
/**
|
|
* Queues an email to be sent.
|
|
*
|
|
* @param Email $email the email to queue
|
|
* @return void
|
|
*/
|
|
public function queue_email(Email $email): void
|
|
{
|
|
$stmt = $this->conn->prepare("INSERT OR IGNORE INTO email_tasks (type, recipient, arg1, arg2)
|
|
VALUES (:type, :recipient, :arg1, :arg2);");
|
|
$stmt->bindValue(":type", $email->type);
|
|
$stmt->bindValue(":recipient", $email->recipient);
|
|
$stmt->bindValue(":arg1", $email->arg1);
|
|
$stmt->bindValue(":arg2", $email->arg2);
|
|
$stmt->execute();
|
|
}
|
|
|
|
/**
|
|
* Returns all queued emails.
|
|
*
|
|
* @return array<Email> the queued emails
|
|
*/
|
|
public function get_queue(): array
|
|
{
|
|
$stmt = $this->conn->prepare("SELECT type, recipient, arg1, arg2 FROM email_tasks;");
|
|
$stmt->execute();
|
|
$emails = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
return array_map(
|
|
fn($row) => Email::deserialize($row["type"], $row["recipient"], $row["arg1"], $row["arg2"]),
|
|
$emails
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Removes mails from the queue.
|
|
*
|
|
* @param array<Email> $emails the emails to remove from the queue
|
|
* @return void
|
|
*/
|
|
public function unqueue_emails(array $emails): void
|
|
{
|
|
$stmt = $this->conn->prepare("DELETE FROM email_tasks
|
|
WHERE type=:type AND recipient=:recipient AND arg1=:arg1 AND arg2=:arg2;");
|
|
$stmt->bindParam(":type", $type);
|
|
$stmt->bindParam(":recipient", $recipient);
|
|
$stmt->bindParam(":arg1", $arg1);
|
|
$stmt->bindParam(":arg2", $arg2);
|
|
|
|
foreach ($emails as $email) {
|
|
$type = $email->type;
|
|
$recipient = $email->recipient;
|
|
$arg1 = $email->arg1;
|
|
$arg2 = $email->arg2;
|
|
|
|
$stmt->execute();
|
|
}
|
|
}
|
|
}
|