From 686fff945e0b4697aa74da404ce90534bb7b121d Mon Sep 17 00:00:00 2001 From: Jonas Kohl Date: Thu, 26 Dec 2024 20:12:34 +0100 Subject: Add async email and topic subscribing --- Dockerfile | 16 ++++++- crontab | 1 + entrypoint.sh | 6 +++ src/application/actions/subscribetopic/post.php | 39 ++++++++++++++++ src/application/actions/viewtopic/get.php | 15 ++++++ src/application/actions/viewtopic/post.php | 52 +++++++++++++++++++++ src/application/appdef.php | 2 +- src/application/common.php | 12 +++++ src/application/cron.php | 42 +++++++++++++++++ src/application/jobs/email.php | 33 +++++++++++++ src/application/messages/de.msg | 31 ++++++++++++ src/application/mystic/forum/Database.php | 4 +- src/application/mystic/forum/orm/PendingEmail.php | 19 ++++++++ src/application/mystic/forum/orm/Subscription.php | 14 ++++++ src/application/mystic/forum/utils/StringUtils.php | 2 + .../templates/bootstrap-3/view_topic.twig | 40 +++++++++++++--- src/application/templates/modern/view_topic.twig | 34 +++++++++++++- src/application/templates/old/view_topic.twig | 29 +++++++++++- src/index.php | 11 +++-- src/ui/theme-files/modern/theme.css | 3 ++ src/ui/theme-files/old/subscribe.gif | Bin 0 -> 1017 bytes src/ui/theme-files/old/subscribe.png | Bin 0 -> 696 bytes src/ui/theme-files/old/unsubscribe.gif | Bin 0 -> 1035 bytes src/ui/theme-files/old/unsubscribe.png | Bin 0 -> 778 bytes with-env | 5 ++ 25 files changed, 395 insertions(+), 15 deletions(-) create mode 100644 crontab create mode 100644 entrypoint.sh create mode 100644 src/application/actions/subscribetopic/post.php create mode 100644 src/application/common.php create mode 100644 src/application/cron.php create mode 100644 src/application/jobs/email.php create mode 100644 src/application/mystic/forum/orm/PendingEmail.php create mode 100644 src/application/mystic/forum/orm/Subscription.php create mode 100644 src/ui/theme-files/old/subscribe.gif create mode 100644 src/ui/theme-files/old/subscribe.png create mode 100644 src/ui/theme-files/old/unsubscribe.gif create mode 100644 src/ui/theme-files/old/unsubscribe.png create mode 100644 with-env diff --git a/Dockerfile b/Dockerfile index ccbf6e7..59b961a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,7 @@ FROM php:8.3-apache-bookworm AS base RUN a2enmod rewrite RUN apt update && apt install -y \ + cron \ curl \ git \ libzip-dev \ @@ -21,7 +22,20 @@ RUN docker-php-ext-configure gd \ RUN docker-php-ext-install gd zip pgsql intl RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer -FROM base AS dev +FROM base AS with-cronjob +COPY --chmod=644 ./crontab /tmp/crontab.tmp +RUN crontab /tmp/crontab.tmp && \ + rm -f /tmp/crontab.tmp +RUN touch /var/log/cron.log && \ + touch /var/log/jobs.log && \ + touch /var/log/job-errors.log + +FROM with-cronjob AS with-scripts +COPY --chmod=700 ./entrypoint.sh /entrypoint.sh +COPY --chmod=700 ./with-env /with-env + +FROM with-scripts AS dev +CMD ["/entrypoint.sh"] COPY ./000-default.conf /etc/apache2/sites-available/000-default.conf WORKDIR /var/www/html diff --git a/crontab b/crontab new file mode 100644 index 0000000..225f276 --- /dev/null +++ b/crontab @@ -0,0 +1 @@ +* * * * * /with-env /usr/local/bin/php /var/www/html/application/cron.php email >/var/log/jobs.log 2>/var/log/job-errors.log diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..f559966 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e +/etc/init.d/cron start +tail -f /var/log/jobs.log /var/log/job-errors.log & +apache2-foreground diff --git a/src/application/actions/subscribetopic/post.php b/src/application/actions/subscribetopic/post.php new file mode 100644 index 0000000..78dad04 --- /dev/null +++ b/src/application/actions/subscribetopic/post.php @@ -0,0 +1,39 @@ +id = $topicId; + +if (!$db->fetch($topic)) { + http_response_code(404); + msg_error(__("No topic exists with this id")); + exit; +} + +$subscription = new Subscription; +$subscription->userId = $currentUser->id; +$subscription->topicId = $topic->id; + +if ($db->fetchWhere($subscription, ["user_id", "topic_id"])) { + $db->delete($subscription); +} else { + $subscription->id = $db->generateId(); + $db->insert($subscription); +} + +header("Location: ?_action=viewtopic&topic=" . urlencode($topic->id)); diff --git a/src/application/actions/viewtopic/get.php b/src/application/actions/viewtopic/get.php index 636d791..56308bf 100644 --- a/src/application/actions/viewtopic/get.php +++ b/src/application/actions/viewtopic/get.php @@ -1,9 +1,12 @@ userId = $currentUser->id; + $subscription->topicId = $topic->id; + if (!$db->fetchWhere($subscription, ["user_id", "topic_id"])) { + $subscription = null; + } +} + render("view_topic.twig", [ "topic" => $topic, "topicAuthor" => $topicAuthor, "allItems" => &$allItems, + "subscription" => $subscription, + "subscription_count" => count($db->fetchCustom(Subscription::class, "WHERE topic_id = $1", [ $topic->id ])), ]); diff --git a/src/application/actions/viewtopic/post.php b/src/application/actions/viewtopic/post.php index 1038222..b50a2e9 100644 --- a/src/application/actions/viewtopic/post.php +++ b/src/application/actions/viewtopic/post.php @@ -1,8 +1,18 @@ insert($attachment); } +if (($_POST["subscribe"] ?? null) === "on") { + $subscription = new Subscription; + $subscription->userId = $currentUser->id; + $subscription->topicId = $topic->id; + + if (!$db->fetchWhere($subscription, ["user_id", "topic_id"])) { + $subscription->id = $db->generateId(); + $db->insert($subscription); + } +} + +/** @var Subscription[] $allSubscriptions */ +$allSubscriptions = $db->fetchCustom(Subscription::class, "WHERE topic_id = $1 AND user_id <> $2", [ $topicId, $currentUser->id ]); + +foreach ($allSubscriptions as $subscription) { + $subUser = new User; + $subUser->id = $subscription->userId; + if (!$db->fetch($subUser)) + continue; + + $email = new PendingEmail; + $email->id = $db->generateId(); + $email->sender = env("MAILER_FROM"); + $email->recipient = (new Address($subUser->email, $subUser->displayName))->toString(); + $email->subject = __("Someone made a new post in \"%topic%\"", [ + "topic" => $topic->title, + ]); + $email->plaintextBody = __("Hello %name%,\n" . + "\n" . + "%otherName% has added the following post to \"%topic%\":\n" . + "%content%\n" . + "\n" . + "Click here to view: %link%\n", [ + "name" => $subUser->displayName, + "otherName" => $currentUser->displayName, + "topic" => $topic->title, + "content" => quote_message(html_entity_decode(renderPostSummary($message))), + "link" => env("PUBLIC_URL") . "?_action=viewtopic&topic=" . urlencode($topicId) . "#post-" . urlencode($item->id), + ]); + $db->insert($email); +} + header("Location: ?_action=viewtopic&topic=" . urlencode($topicId) . "#form"); diff --git a/src/application/appdef.php b/src/application/appdef.php index 1f51d97..d623cd1 100644 --- a/src/application/appdef.php +++ b/src/application/appdef.php @@ -1,3 +1,3 @@ "> $ln", preg_split('~(*BSR_ANYCRLF)\R~', trim($message)))); +} diff --git a/src/application/cron.php b/src/application/cron.php new file mode 100644 index 0000000..094fe50 --- /dev/null +++ b/src/application/cron.php @@ -0,0 +1,42 @@ +\n"); + exit(1); +} + +$jobsDir = __DIR__ . "/jobs"; + +$availableJobs = array_map(fn($i) => pathinfo($i, PATHINFO_FILENAME), array_values(array_filter(scandir($jobsDir), + fn($i) => is_file($jobsDir . "/" . $i) && $i[0] !== "." && pathinfo($i, PATHINFO_EXTENSION) === "php"))); + +if (!in_array($job, $availableJobs)) { + print_error("Error: Invalid job specified\nAvailable jobs are:\n" . implode("", array_map(fn($i) => " $i\n", $availableJobs))); + exit(1); +} + +$jobFile = $jobsDir . "/" . $job . ".php"; + +include $jobFile; diff --git a/src/application/jobs/email.php b/src/application/jobs/email.php new file mode 100644 index 0000000..8bb97dc --- /dev/null +++ b/src/application/jobs/email.php @@ -0,0 +1,33 @@ +fetchAll(PendingEmail::class); + +$transport = Transport::fromDsn(getenv("MAILER_DSN")); + +foreach ($pendingEmails as $pendingEmail) { + try { + $mail = (new Email) + ->from($pendingEmail->sender) + ->to($pendingEmail->recipient) + ->subject($pendingEmail->subject) + ; + if (!empty($pendingEmail->htmlBody)) + $mail->html($pendingEmail->htmlBody); + if (!empty($pendingEmail->plaintextBody)) + $mail->text($pendingEmail->plaintextBody); + $transport->send($mail); + } catch (TransportExceptionInterface $ex) { + print_error("Failed to send mail: " . $ex->getMessage() . "\n"); + } + $db->delete($pendingEmail); +} diff --git a/src/application/messages/de.msg b/src/application/messages/de.msg index 3ce96d4..c16d1d1 100644 --- a/src/application/messages/de.msg +++ b/src/application/messages/de.msg @@ -540,3 +540,34 @@ metadata({ : "Page generation took %dur% second(s)" = "Seitenaufbau dauerte %dur% Sekunde(n)" + +: "Unsubscribe from topic" += "Thema deabonnieren" + +: "Subscribe to topic" += "Thema abonnieren" + +: "Someone made a new post in \"%topic%\"" += "Jemand hat einen neuen Beitrag zu \"%topic%\" hinzugefügt" + +: "Hello %name%,\n" + "\n" + "%otherName% has added the following post to \"%topic%\":\n" + "%content%\n" + "\n" + "Click here to view: %link%\n" += "Hallo %name%,\n" + "\n" + "%otherName% hat den folgenden Beitrag zu \"%topic%\" hinzugefügt:\n" + "%content%\n" + "\n" + "Den Beitrag ansehen: %link%\n" + +:... +- "%n% person is watching this topic" +- "%n% people are watching this topic" +- "Nobody is watching this topic" +=... +- "%n% Person beobachtet dieses Thema" +- "%n% Personen beobachten dieses Thema" +- "Niemand beobachtet dieses Thema" diff --git a/src/application/mystic/forum/Database.php b/src/application/mystic/forum/Database.php index 1c2d710..bca4ac9 100644 --- a/src/application/mystic/forum/Database.php +++ b/src/application/mystic/forum/Database.php @@ -46,12 +46,12 @@ class Database { protected function queryParams(string $query, array $params): Result|false { ++$this->queryCount; - return \pg_query_params ($this->connection, $query, $params); + return \pg_query_params($this->connection, $query, $params); } protected function query(string $query): Result|false { ++$this->queryCount; - return \pg_query ($this->connection, $query); + return \pg_query($this->connection, $query); } public static function generateId(int $length = 64): string { diff --git a/src/application/mystic/forum/orm/PendingEmail.php b/src/application/mystic/forum/orm/PendingEmail.php new file mode 100644 index 0000000..70622b3 --- /dev/null +++ b/src/application/mystic/forum/orm/PendingEmail.php @@ -0,0 +1,19 @@ + {% if canEdit and not ctx.topic.isLocked %} - + {% endif %} {% if canReply %} - + + {% endif %} + {% if canSubscribe %} +
{% endif %} {% if canEdit %} {% if ctx.topic.isLocked %} {% else %} {% endif %} {% endif %} {% if canDelete %} {% endif %} @@ -209,7 +225,14 @@ {{ __("Started by %user% on %date%", { "user": (ctx.topicAuthor is not null) ? ('' ~ ctx.topicAuthor.displayName|e("html") ~ '') : __("(deleted)"), "date": '' ~ ctx.topic.creationDate.format("c")|e("html") ~ '', - }) }} + }) }} • {{ ___( + "%n% person is watching this topic", + "%n% people are watching this topic", + ctx.subscription_count, + { + n: ctx.subscription_count, + }, + ) }} {% if canEdit %} {% else %} diff --git a/src/application/templates/modern/view_topic.twig b/src/application/templates/modern/view_topic.twig index 733ce1b..c064b1c 100644 --- a/src/application/templates/modern/view_topic.twig +++ b/src/application/templates/modern/view_topic.twig @@ -30,6 +30,12 @@ or currentUser.hasPermission(permission("DELETE_OTHER_TOPIC")) ) %} +{% set canSubscribe = currentUser is not null %} + +{% set isSubscribed = + currentUser is not null + and ctx.subscription is not null %} + {% set title = ctx.topic.title %} {% extends "base.twig" %} @@ -189,6 +195,20 @@ {% endif %} + {% if canSubscribe %} + + {% endif %} {% if canEdit %} {% if ctx.topic.isLocked %} {%- endif -%} {%- endif -%} + {%- if canSubscribe -%} + + {%- endif -%} {%- if canDelete -%} {% else %} diff --git a/src/index.php b/src/index.php index 8036a19..0580523 100644 --- a/src/index.php +++ b/src/index.php @@ -9,6 +9,8 @@ use mystic\forum\orm\Topic; use mystic\forum\orm\TopicLogMessage; use mystic\forum\orm\User; use mystic\forum\orm\UserPermissions; +use mystic\forum\orm\PendingEmail; +use mystic\forum\orm\Subscription; use mystic\forum\utils\RequestUtils; use mystic\forum\utils\StringUtils; use Twig\Environment; @@ -244,11 +246,11 @@ function expandTags(string $contents): string { }, $contents); } -function renderPostSummary(string $contents): string { +function renderPostSummary(string $contents, int $maxLength = 100): string { $contents = renderPost($contents); // remove spoiler contents so they don't appear in summaries $contents = preg_replace('/(.*?)/s', '[ ' . __("Spoiler") . ' ]', $contents); - return htmlentities(html_entity_decode(StringUtils::truncate(strip_tags($contents), 100))); + return htmlentities(html_entity_decode(StringUtils::truncate(strip_tags($contents), $maxLength))); } function renderPost(string $contents): string { @@ -299,6 +301,7 @@ function env(string $key): ?string { require_once __DIR__ . "/vendor/autoload.php"; require_once __DIR__ . "/application/i18n.php"; +require_once __DIR__ . "/application/common.php"; if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["lang"])) { parse_str($_SERVER["QUERY_STRING"], $query); @@ -319,7 +322,7 @@ i18n_locale($user_locale); $db = null; try { - $db = new Database(Database::getConnectionString("db", getenv("POSTGRES_USER"), getenv("POSTGRES_PASSWORD"), getenv("POSTGRES_DBNAME"))); + $db = get_db(); } catch (DatabaseConnectionException $ex) { msg_error( __("Failed to connect to database:\n%details%", [ @@ -337,6 +340,8 @@ $db->ensureTable(Topic::class); $db->ensureTable(Post::class); $db->ensureTable(Attachment::class); $db->ensureTable(TopicLogMessage::class); +$db->ensureTable(PendingEmail::class); +$db->ensureTable(Subscription::class); $superuser = new User(); $superuser->id = "SUPERUSER"; diff --git a/src/ui/theme-files/modern/theme.css b/src/ui/theme-files/modern/theme.css index 1f1cc3a..3a5f4af 100644 --- a/src/ui/theme-files/modern/theme.css +++ b/src/ui/theme-files/modern/theme.css @@ -224,6 +224,9 @@ footer { display: block; } } +.checkbox { + margin-block: 8px; +} .form-inline { display: inline-flex; margin: 0; diff --git a/src/ui/theme-files/old/subscribe.gif b/src/ui/theme-files/old/subscribe.gif new file mode 100644 index 0000000..195067c Binary files /dev/null and b/src/ui/theme-files/old/subscribe.gif differ diff --git a/src/ui/theme-files/old/subscribe.png b/src/ui/theme-files/old/subscribe.png new file mode 100644 index 0000000..2d3049d Binary files /dev/null and b/src/ui/theme-files/old/subscribe.png differ diff --git a/src/ui/theme-files/old/unsubscribe.gif b/src/ui/theme-files/old/unsubscribe.gif new file mode 100644 index 0000000..27f230a Binary files /dev/null and b/src/ui/theme-files/old/unsubscribe.gif differ diff --git a/src/ui/theme-files/old/unsubscribe.png b/src/ui/theme-files/old/unsubscribe.png new file mode 100644 index 0000000..396f009 Binary files /dev/null and b/src/ui/theme-files/old/unsubscribe.png differ diff --git a/with-env b/with-env new file mode 100644 index 0000000..aabba50 --- /dev/null +++ b/with-env @@ -0,0 +1,5 @@ +#!/bin/bash + +set -e +. <(xargs -0 bash -c 'printf "export %q\n" "$@"' -- < /proc/1/environ) +$@ -- cgit v1.2.3