Files
fossbilling-mailgateway/NotificationSettings.php
T

77 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Box\Mod\Mailgateway;
use Pimple\Container;
class NotificationSettings
{
private const CODES = ['mod_support_ticket_open', 'mod_support_ticket_staff_reply',
'mod_support_ticket_staff_open', 'mod_support_ticket_staff_close'];
public function __construct(private Container $di) {}
private function hasMarker(string $subject): bool
{
return (bool) preg_match('/\[Ticket\s+#\s*{{\s*ticket\.id\s*}}\s*\]/i', $subject);
}
public function repair(): array
{
$email = $this->di['mod_service']('email');
foreach (self::CODES as $code) {
$template = $email->getTemplateRepository()->findOneByActionCode($code);
if ($template === null) {
$source = file_get_contents(dirname(__DIR__) . '/Support/templates/email/' . $code . '.html.twig');
if (!is_string($source)
|| !preg_match('/{%\s*block subject\s*%}(.*?){%\s*endblock\s*%}/s', $source, $subject)
|| !preg_match('/{%\s*block content\s*%}(.*?){%\s*endblock\s*%}/s', $source, $content)) {
throw new \FOSSBilling\InformationException("Cannot configure $code: its default template is missing or invalid.");
}
$template = $email->templateCreate($code, trim($subject[1]), trim($content[1]),
$code === 'mod_support_ticket_open' ? 1 : 0, 'support');
}
$data = $email->templateToApiArray($template);
if ($code !== 'mod_support_ticket_open' && !$data['enabled']) {
continue;
}
$subject = $data['subject'] ?? '';
$enabled = $code === 'mod_support_ticket_open' ? true : null;
if (!$this->hasMarker($subject)) {
// Keep the existing subject and body, adding only the routing marker.
$email->updateTemplate($template, $enabled, null, '[Ticket #{{ ticket.id }}] ' . $subject);
} elseif ($code === 'mod_support_ticket_open' && !$data['enabled']) {
$email->updateTemplate($template, true);
}
}
return $this->status();
}
public function status(): array
{
$email = $this->di['mod_service']('email');
$errors = [];
foreach (self::CODES as $code) {
$template = $email->getTemplateRepository()->findOneByActionCode($code);
if ($template === null) {
$errors[] = "Open FOSSBilling Email settings and configure $code before enabling importing.";
continue;
}
$data = $email->templateToApiArray($template);
if (!$data['enabled']) {
if ($code === 'mod_support_ticket_open') {
$errors[] = 'Enable mod_support_ticket_open in FOSSBilling Email settings to send ticket acknowledgements.';
}
continue;
}
// Check the documented dynamic marker without executing custom template code.
if (!$this->hasMarker($data['subject'] ?? '')) {
$errors[] = "Include [Ticket #{{ ticket.id }}] in the subject of $code in FOSSBilling Email settings.";
}
}
return ['ready' => $errors === [], 'errors' => $errors];
}
}