From 1bc3367c9a1a5eb725688802927bd544cc9d9c63 Mon Sep 17 00:00:00 2001
From: =?utf8?q?Paul=20H=C3=A4nsch?= <paul@plutz.net>
Date: Thu, 25 May 2023 12:12:33 +0200
Subject: [PATCH] Set page title in HTML Header

---
 handlers/20_title.sh                | 43 +++++++++++++++++++++++++++++
 handlers/{20_page.sh => 30_page.sh} |  0
 themes/default.sh                   |  2 +-
 3 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100755 handlers/20_title.sh
 rename handlers/{20_page.sh => 30_page.sh} (100%)

diff --git a/handlers/20_title.sh b/handlers/20_title.sh
new file mode 100755
index 0000000..4288b31
--- /dev/null
+++ b/handlers/20_title.sh
@@ -0,0 +1,43 @@
+#!/bin/sh
+
+if acl_read ${PATH_INFO%/*}; then
+  mdfile="$(mdfile "${PATH_INFO%/*}")"
+else
+  PAGE_TITLE="${SITE_TITLE}"
+  return 1
+fi
+
+if [ "$mdfile" ]; then
+  PAGE_TITLE="$(
+    sed -nE '
+      s;^%title[ \t]+([[:graph:]][[:print:]]+)\r?$;\1;p; tQ;
+      b; :Q q;
+    ' "$mdfile"
+  )"
+  [ ! "${PAGE_TITLE}" ] && PAGE_TITLE="$(
+    MD_MACROS="" md <"$mdfile" \
+    | sed -nE '
+      s;^.*<h1[^>]*>(.*>)?([^<]+)(<.*)?</h1>.*$;\2;p; tQ;
+      s;^.*<h2[^>]*>(.*>)?([^<]+)(<.*)?</h2>.*$;\2;p; tQ;
+      b; :Q q;
+    '
+  )"
+else
+  PAGE_TITLE="${SITE_TITLE}"
+  return 1
+fi
+
+case $PATH_INFO in
+  *"/[attachment]")
+    PAGE_TITLE="${PAGE_TITLE} (Attachments)"
+    ;;
+  *"/[revision]")
+    PAGE_TITLE="${PAGE_TITLE} (Revisions)"
+    ;;
+esac
+
+[ "$PAGE_TITLE" ] \
+&& PAGE_TITLE="${PAGE_TITLE}${SITE_TITLE:+ - ${SITE_TITLE}}" \
+|| PAGE_TITLE="${SITE_TITLE}"
+
+return 1
diff --git a/handlers/20_page.sh b/handlers/30_page.sh
similarity index 100%
rename from handlers/20_page.sh
rename to handlers/30_page.sh
diff --git a/themes/default.sh b/themes/default.sh
index 0439f0d..541f713 100755
--- a/themes/default.sh
+++ b/themes/default.sh
@@ -40,7 +40,7 @@ theme_pagemenu(){
 
 theme_page(){
   local page="$1" title="$2"
-  title="$(HTML "${title:-"${page}"}")"
+  title="$(HTML "${title:-"${PAGE_TITLE:-"${page}"}"}")"
 
   # Important! Web Server response including newline
   printf "%s\r\n" "Content-Type: text/html; charset=utf-8" ""
-- 
2.39.5