Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: support Markdown notes with safe rendering
Miguel Ribeiro5a92009ac961
diff --git a/api/subscriptions/get_ical_feed.php b/api/subscriptions/get_ical_feed.phpindex 021fe7d..f9ce494 100644--- a/api/subscriptions/get_ical_feed.php+++ b/api/subscriptions/get_ical_feed.php@@ -162,7 +162,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';$summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));- $notes = icalEscape(html_entity_decode($subscription['notes'], ENT_QUOTES, 'UTF-8'));+ $notes = icalEscape($subscription['notes']);$category = icalEscape($subscription['category']);$paymentMethod = icalEscape($subscription['payment_method']);$payer = icalEscape($subscription['payer_user']);@@ -173,15 +173,22 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');$alarm_trigger = '-P' . $subscription['trigger'] . 'D';+ // Notes can now be multi-paragraph Markdown, so these lines+ // (especially DESCRIPTION) can genuinely exceed the RFC 5545+ // 75-octet limit.+ $summaryLine = icalFold('SUMMARY:' . $summary);+ $descriptionLine = icalFold('DESCRIPTION:' . $description);+ $locationLine = icalFold('LOCATION:' . $location);+$icsContent .= <<<ICSBEGIN:VEVENTUID:$uidDTSTAMP:$dtstamp- SUMMARY:$summary- DESCRIPTION:$description+ $summaryLine+ $descriptionLineDTSTART;VALUE=DATE:$dtstartDTEND;VALUE=DATE:$dtend- LOCATION:$location+ $locationLineSTATUS:CONFIRMEDTRANSP:OPAQUEBEGIN:VALARMdiff --git a/api/subscriptions/set_subscriptions.php b/api/subscriptions/set_subscriptions.phpindex 99e239f..39ec3ba 100644--- a/api/subscriptions/set_subscriptions.php+++ b/api/subscriptions/set_subscriptions.php@@ -18,7 +18,7 @@ For 'add' and 'edit' actions (all optional for 'edit'):- payment_method_id: the payment method ID (integer).- payer_user_id: the household member payer ID (integer).- category_id: the category ID (integer).-- notes: subscription notes (string).+- notes: subscription notes (string, Markdown supported).- url: subscription URL (string).- logo_url: an image URL to download as the logo (string).- logo: direct image file upload for the logo.@@ -375,7 +375,7 @@ switch ($action) {$payerUserId = $_POST['payer_user_id'] ?? null;$categoryId = $_POST['category_id'] ?? null;- $notes = isset($_POST['notes']) ? validate($_POST['notes']) : '';+ $notes = isset($_POST['notes']) ? validate_markdown($_POST['notes']) : '';$url = isset($_POST['url']) ? validate($_POST['url']) : '';$notify = $_POST['notify'] ?? $_POST['notifications'] ?? '0';@@ -662,7 +662,7 @@ switch ($action) {$categoryId = $_POST['category_id'] === '' ? null : intval($_POST['category_id']);}- $notes = isset($_POST['notes']) ? validate($_POST['notes']) : $subscription['notes'];+ $notes = isset($_POST['notes']) ? validate_markdown($_POST['notes']) : $subscription['notes'];$url = isset($_POST['url']) ? validate($_POST['url']) : $subscription['url'];$notify = $subscription['notify'];diff --git a/endpoints/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.phpindex 64ab37e..a2f0c1e 100644--- a/endpoints/cronjobs/sendcancellationnotifications.php+++ b/endpoints/cronjobs/sendcancellationnotifications.php@@ -6,6 +6,7 @@ use PHPMailer\PHPMailer\Exception;require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require_once __DIR__ . '/../../includes/ssrf_helper.php';+require_once __DIR__ . '/../../includes/webhook_helper.php';require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';require __DIR__ . '/../../libs/PHPMailer/SMTP.php';@@ -585,7 +586,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$payload = str_replace("{{subscription_payer}}", $payer, $payload);$payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);$payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);- $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);+ $payload = str_replace("{{subscription_notes}}", webhookJsonEscape($subscription['notes']), $payload);// Initialize cURL for each subscription$ch = curl_init();diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.phpindex d4333ba..02f0b19 100644--- a/endpoints/cronjobs/sendnotifications.php+++ b/endpoints/cronjobs/sendnotifications.php@@ -6,6 +6,7 @@ use PHPMailer\PHPMailer\Exception;require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require_once __DIR__ . '/../../includes/ssrf_helper.php';+require_once __DIR__ . '/../../includes/webhook_helper.php';require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';require __DIR__ . '/../../libs/PHPMailer/SMTP.php';@@ -884,7 +885,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);$payload = str_replace("{{subscription_days_until_payment}}", $subscription['days'], $payload);$payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);- $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);+ $payload = str_replace("{{subscription_notes}}", webhookJsonEscape($subscription['notes']), $payload);// Initialize cURL for each subscription$ch = curl_init();diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex e9d41a8..050ed92 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -244,7 +244,7 @@ $startDate = $_POST["start_date"];$paymentMethodId = $_POST["payment_method_id"];$payerUserId = $_POST["payer_user_id"];$categoryId = $_POST['category_id'];-$notes = validate($_POST["notes"]);+$notes = validate_markdown($_POST["notes"]);$url = validate($_POST['url']);$logoUrl = validate($_POST['logo-url']);$logo = "";diff --git a/endpoints/subscription/exportcalendar.php b/endpoints/subscription/exportcalendar.phpindex ed5ed79..2456375 100644--- a/endpoints/subscription/exportcalendar.php+++ b/endpoints/subscription/exportcalendar.php@@ -34,7 +34,7 @@ if ($subscription) {// Create ICS from subscription information$uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';$summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));- $notes = icalEscape(html_entity_decode($subscription['notes'], ENT_QUOTES, 'UTF-8'));+ $notes = icalEscape($subscription['notes']);$category = icalEscape($subscription['category']);$paymentMethod = icalEscape($subscription['payment_method']);$payer = icalEscape($subscription['payer_user']);@@ -46,6 +46,12 @@ if ($subscription) {$location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');$alarm_trigger = '-P' . $subscription['trigger'] . 'D';+ // Notes can now be multi-paragraph Markdown, so these lines (especially+ // DESCRIPTION) can genuinely exceed the RFC 5545 75-octet limit.+ $summaryLine = icalFold('SUMMARY:' . $summary);+ $descriptionLine = icalFold('DESCRIPTION:' . $description);+ $locationLine = icalFold('LOCATION:' . $location);+$icsContent = <<<ICSBEGIN:VCALENDARVERSION:2.0@@ -55,11 +61,11 @@ if ($subscription) {BEGIN:VEVENTUID:$uidDTSTAMP:$dtstamp- SUMMARY:$summary- DESCRIPTION:$description+ $summaryLine+ $descriptionLineDTSTART;VALUE=DATE:$dtstartDTEND;VALUE=DATE:$dtend- LOCATION:$location+ $locationLineSTATUS:CONFIRMEDTRANSP:OPAQUEBEGIN:VALARMdiff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.phpindex 9e6cfd1..986f8ad 100644--- a/endpoints/subscription/get.php+++ b/endpoints/subscription/get.php@@ -1,5 +1,6 @@<?phprequire_once '../../includes/connect_endpoint.php';+require_once '../../includes/markdown.php';if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {if (isset($_GET['id']) && $_GET['id'] != "") {@@ -25,7 +26,8 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {$subscriptionData['next_payment'] = $row['next_payment'];$subscriptionData['frequency'] = $row['frequency'];$subscriptionData['cycle'] = $row['cycle'];- $subscriptionData['notes'] = htmlspecialchars_decode($row['notes'] ?? "");+ $subscriptionData['notes'] = $row['notes'] ?? "";+ $subscriptionData['notes_html'] = render_notes_markdown($row['notes'] ?? "");$subscriptionData['payment_method_id'] = $row['payment_method_id'];$subscriptionData['payer_user_id'] = $row['payer_user_id'];$subscriptionData['category_id'] = $row['category_id'];diff --git a/includes/i18n/ar.php b/includes/i18n/ar.phpindex fabb6f4..88ec481 100644--- a/includes/i18n/ar.php+++ b/includes/i18n/ar.php@@ -125,6 +125,10 @@ $i18n = ["paid_by" => "يدفعه","url" => "الرابط","notes" => "ملاحظات",+ "notes_bold" => "عريض",+ "notes_italic" => "مائل",+ "notes_list" => "قائمة",+ "notes_link" => "رابط","enable_notifications" => "تفعيل إشعارات هذا الاشتراك","default_value_from_settings" => "القيمة الافتراضية من الإعدادات","cancellation_notification" => "إشعار الإلغاء",diff --git a/includes/i18n/az.php b/includes/i18n/az.phpindex aa0226f..d91a94e 100644--- a/includes/i18n/az.php+++ b/includes/i18n/az.php@@ -125,6 +125,10 @@ $i18n = ["paid_by" => "Ödəyən","url" => "URL","notes" => "Qeydlər",+ "notes_bold" => "Qalın",+ "notes_italic" => "Kursiv",+ "notes_list" => "Siyahı",+ "notes_link" => "Keçid","enable_notifications" => "Bu abunə üçün bildirişləri aktiv et","default_value_from_settings" => "Parametrlərdəki standart dəyər","cancellation_notification" => "Ləğvetmə bildirişi",diff --git a/includes/i18n/ca.php b/includes/i18n/ca.phpindex 2a64127..2e1a6de 100644--- a/includes/i18n/ca.php+++ b/includes/i18n/ca.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Pagat per","url" => "URL","notes" => "Notes",+ "notes_bold" => "Negreta",+ "notes_italic" => "Cursiva",+ "notes_list" => "Llista",+ "notes_link" => "Enllaç","enable_notifications" => "Activar notificacions per aquesta subscripció","default_value_from_settings" => "Valor predeterminat al panell de Configuració","cancellation_notification" => "Notificació de cancel·lació",diff --git a/includes/i18n/cs.php b/includes/i18n/cs.phpindex 719d5c4..b28b383 100644--- a/includes/i18n/cs.php+++ b/includes/i18n/cs.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Platí","url" => "Adresa URL","notes" => "Poznámky",+ "notes_bold" => "Tučné",+ "notes_italic" => "Kurzíva",+ "notes_list" => "Seznam",+ "notes_link" => "Odkaz","enable_notifications" => "Povolit oznámení pro toto předplatné","default_value_from_settings" => "Výchozí hodnota z nastavení","cancellation_notification" => "Oznámení o zrušení",diff --git a/includes/i18n/da.php b/includes/i18n/da.phpindex a6d9f1d..ba1e210 100644--- a/includes/i18n/da.php+++ b/includes/i18n/da.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Betalt af","url" => "URL","notes" => "Noter",+ "notes_bold" => "Fed",+ "notes_italic" => "Kursiv",+ "notes_list" => "Liste",+ "notes_link" => "Link","enable_notifications" => "Aktivér notifikationer for dette abonnement","default_value_from_settings" => "Standardværdi fra indstillinger","cancellation_notification" => "Annulleringsnotifikation",diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex df9900b..373825a 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Gezahlt durch","url" => "URL","notes" => "Notizen",+ "notes_bold" => "Fett",+ "notes_italic" => "Kursiv",+ "notes_list" => "Liste",+ "notes_link" => "Link","enable_notifications" => "Benachrichtigungen für dieses Abonnement aktivieren","default_value_from_settings" => "Standardwert aus den Einstellungen","cancellation_notification" => "Benachrichtigung bei Kündigung",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex 0c71a55..c688bde 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -121,6 +121,10 @@ $i18n = ["paid_by" => "Πληρώνεται από","url" => "URL","notes" => "Σημειώσεις",+ "notes_bold" => "Έντονα",+ "notes_italic" => "Πλάγια",+ "notes_list" => "Λίστα",+ "notes_link" => "Σύνδεσμος","enable_notifications" => "Ενεργοποίηση ειδοποιήσεων για αυτή τη συνδρομή","default_value_from_settings" => "Προεπιλεγμένη τιμή από τις ρυθμίσεις","cancellation_notification" => "Ειδοποίηση ακύρωσης",diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex c79ce74..e1d214d 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -125,6 +125,10 @@ $i18n = ["paid_by" => "Paid by","url" => "URL","notes" => "Notes",+ "notes_bold" => "Bold",+ "notes_italic" => "Italic",+ "notes_list" => "List",+ "notes_link" => "Link","enable_notifications" => "Enable Notifications for this subscription","default_value_from_settings" => "Default value from settings","cancellation_notification" => "Cancellation Notification",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex a2ead4d..320f3b7 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Pagado por","url" => "URL","notes" => "Notas",+ "notes_bold" => "Negrita",+ "notes_italic" => "Cursiva",+ "notes_list" => "Lista",+ "notes_link" => "Enlace","enable_notifications" => "Habilitar notificaciones para esta suscripción","default_value_from_settings" => "Valor predeterminado de la configuración","cancellation_notification" => "Notificación de cancelación",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex 2bb1d9e..596142a 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Payé par","url" => "URL","notes" => "Notes",+ "notes_bold" => "Gras",+ "notes_italic" => "Italique",+ "notes_list" => "Liste",+ "notes_link" => "Lien","enable_notifications" => "Activer les notifications pour cet abonnement","default_value_from_settings" => "Valeur par défaut des paramètres","cancellation_notification" => "Notification d'annulation",diff --git a/includes/i18n/hu.php b/includes/i18n/hu.phpindex 3051822..02dff8f 100644--- a/includes/i18n/hu.php+++ b/includes/i18n/hu.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Fizette","url" => "URL","notes" => "Jegyzetek",+ "notes_bold" => "Félkövér",+ "notes_italic" => "Dőlt",+ "notes_list" => "Lista",+ "notes_link" => "Hivatkozás","enable_notifications" => "Értesítések engedélyezése ehhez az előfizetéshez","default_value_from_settings" => "Alapértelmezett érték a beállításokból","cancellation_notification" => "Lemondási értesítés",diff --git a/includes/i18n/id.php b/includes/i18n/id.phpindex ac4992c..48d4598 100644--- a/includes/i18n/id.php+++ b/includes/i18n/id.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Dibayar oleh","url" => "URL","notes" => "Catatan",+ "notes_bold" => "Tebal",+ "notes_italic" => "Miring",+ "notes_list" => "Daftar",+ "notes_link" => "Tautan","enable_notifications" => "Aktifkan Notifikasi untuk langganan ini","default_value_from_settings" => "Nilai default dari pengaturan","cancellation_notification" => "Notifikasi Pembatalan",diff --git a/includes/i18n/it.php b/includes/i18n/it.phpindex 8c1e602..2d62ed8 100644--- a/includes/i18n/it.php+++ b/includes/i18n/it.php@@ -127,6 +127,10 @@ $i18n = ["paid_by" => 'Pagato da',"url" => 'URL',"notes" => 'Note',+ "notes_bold" => 'Grassetto',+ "notes_italic" => 'Corsivo',+ "notes_list" => 'Elenco',+ "notes_link" => 'Link',"enable_notifications" => 'Abilita notifiche per questo abbonamento',"default_value_from_settings" => 'Valore predefinito dalle impostazioni',"cancellation_notification" => "Notifica di cancellazione",diff --git a/includes/i18n/ja.php b/includes/i18n/ja.phpindex 7326aed..e1b2e01 100644--- a/includes/i18n/ja.php+++ b/includes/i18n/ja.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "支払い元","url" => "URL","notes" => "注釈",+ "notes_bold" => "太字",+ "notes_italic" => "斜体",+ "notes_list" => "リスト",+ "notes_link" => "リンク","enable_notifications" => "この定期購入の通知を有効にする","default_value_from_settings" => "設定からデフォルト値を使用","cancellation_notification" => "キャンセル通知",diff --git a/includes/i18n/ko.php b/includes/i18n/ko.phpindex 8d8b77e..b34e10a 100644--- a/includes/i18n/ko.php+++ b/includes/i18n/ko.php@@ -125,6 +125,10 @@ $i18n = ["paid_by" => "결제 담당","url" => "URL","notes" => "메모",+ "notes_bold" => "굵게",+ "notes_italic" => "기울임꼴",+ "notes_list" => "목록",+ "notes_link" => "링크","enable_notifications" => "이 구독의 알림 활성화","default_value_from_settings" => "설정의 기본값 사용","cancellation_notification" => "구독 취소 전 알림",diff --git a/includes/i18n/nl.php b/includes/i18n/nl.phpindex 2e4056b..20e1d30 100644--- a/includes/i18n/nl.php+++ b/includes/i18n/nl.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Betaald door","url" => "URL","notes" => "Notities",+ "notes_bold" => "Vet",+ "notes_italic" => "Cursief",+ "notes_list" => "Lijst",+ "notes_link" => "Link","enable_notifications" => "Notificaties inschakelen voor dit abonnement","default_value_from_settings" => "Standaardwaarde uit instellingen","cancellation_notification" => "Opzegnotificatie",diff --git a/includes/i18n/pl.php b/includes/i18n/pl.phpindex 7533790..14536d9 100644--- a/includes/i18n/pl.php+++ b/includes/i18n/pl.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Zapłacone przez","url" => "URL","notes" => "Notatki",+ "notes_bold" => "Pogrubienie",+ "notes_italic" => "Kursywa",+ "notes_list" => "Lista",+ "notes_link" => "Link","enable_notifications" => "Włącz powiadomienia dla tej subskrypcji","default_value_from_settings" => "Wartość domyślna z ustawień","cancellation_notification" => "Powiadomienie o anulowaniu",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex e9067e6..fefe458 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Pago por","url" => "URL","notes" => "Notas",+ "notes_bold" => "Negrito",+ "notes_italic" => "Itálico",+ "notes_list" => "Lista",+ "notes_link" => "Link","enable_notifications" => "Activar notificações para esta subscrição","default_value_from_settings" => "Valor por defeito das definições","cancellation_notification" => "Notificação de cancelamento",diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.phpindex 270d7f8..2d3c1e0 100644--- a/includes/i18n/pt_br.php+++ b/includes/i18n/pt_br.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Pago por","url" => "URL","notes" => "Anotações",+ "notes_bold" => "Negrito",+ "notes_italic" => "Itálico",+ "notes_list" => "Lista",+ "notes_link" => "Link","enable_notifications" => "Ativar notificações para essa assinatura","default_value_from_settings" => "Valor padrão das configurações","cancellation_notification" => "Notificação de cancelamento",diff --git a/includes/i18n/ro.php b/includes/i18n/ro.phpindex 2a28861..b8ee493 100644--- a/includes/i18n/ro.php+++ b/includes/i18n/ro.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Plătit de","url" => "URL","notes" => "Notițe",+ "notes_bold" => "Aldin",+ "notes_italic" => "Cursiv",+ "notes_list" => "Listă",+ "notes_link" => "Link","enable_notifications" => "Activează notificările pentru acest abonament","default_value_from_settings" => "Valoarea standard din setări","cancellation_notification" => "Notificare de anulare",diff --git a/includes/i18n/ru.php b/includes/i18n/ru.phpindex 77c81ff..3e06f8a 100644--- a/includes/i18n/ru.php+++ b/includes/i18n/ru.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Оплачивает","url" => "URL","notes" => "Примечания",+ "notes_bold" => "Жирный",+ "notes_italic" => "Курсив",+ "notes_list" => "Список",+ "notes_link" => "Ссылка","enable_notifications" => "Включить уведомления для этой подписки","default_value_from_settings" => "Значение по умолчанию из настроек","cancellation_notification" => "Уведомление об отмене",diff --git a/includes/i18n/sl.php b/includes/i18n/sl.phpindex bc03ecc..076f65a 100644--- a/includes/i18n/sl.php+++ b/includes/i18n/sl.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Plačal","url" => "URL","notes" => "Opombe",+ "notes_bold" => "Krepko",+ "notes_italic" => "Ležeče",+ "notes_list" => "Seznam",+ "notes_link" => "Povezava","enable_notifications" => "Omogoči obvestila za to naročnino","default_value_from_settings" => "Privzeta vrednost iz nastavitev","cancellation_notification" => "Obvestilo o preklicu",diff --git a/includes/i18n/sr.php b/includes/i18n/sr.phpindex 53e4a9d..4dead3a 100644--- a/includes/i18n/sr.php+++ b/includes/i18n/sr.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Плаћено од","url" => "URL","notes" => "Напомене",+ "notes_bold" => "Подебљано",+ "notes_italic" => "Курзив",+ "notes_list" => "Листа",+ "notes_link" => "Веза","enable_notifications" => "Омогући обавештења за ову претплату","default_value_from_settings" => "Подразумевана вредност из подешавања","cancellation_notification" => "Обавештење о отказивању",diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.phpindex d0a965c..da8764f 100644--- a/includes/i18n/sr_lat.php+++ b/includes/i18n/sr_lat.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Plaćeno od strane","url" => "URL","notes" => "Beleške",+ "notes_bold" => "Podebljano",+ "notes_italic" => "Kurziv",+ "notes_list" => "Lista",+ "notes_link" => "Veza","enable_notifications" => "Omogući obaveštenja za ovu pretplatu","default_value_from_settings" => "Podrazumevana vrednost iz podešavanja","cancellation_notification" => "Obaveštenje o otkazivanju",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex efd41f8..de074c0 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Ödeyen","url" => "URL","notes" => "Notlar",+ "notes_bold" => "Kalın",+ "notes_italic" => "İtalik",+ "notes_list" => "Liste",+ "notes_link" => "Bağlantı","enable_notifications" => "Bu abonelik için bildirimleri etkinleştir","default_value_from_settings" => "Ayarlar'dan varsayılan değeri al","cancellation_notification" => "İptal Bildirimi",diff --git a/includes/i18n/uk.php b/includes/i18n/uk.phpindex c0883ec..f3ca4d5 100644--- a/includes/i18n/uk.php+++ b/includes/i18n/uk.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Оплачує","url" => "URL","notes" => "Примітки",+ "notes_bold" => "Жирний",+ "notes_italic" => "Курсив",+ "notes_list" => "Список",+ "notes_link" => "Посилання","enable_notifications" => "Увімкнути сповіщення для цієї підписки","default_value_from_settings" => "Значення за замовчуванням з налаштувань","cancellation_notification" => "Сповіщення про скасування",diff --git a/includes/i18n/vi.php b/includes/i18n/vi.phpindex 16fa582..8b28791 100644--- a/includes/i18n/vi.php+++ b/includes/i18n/vi.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "Người thanh toán","url" => "URL","notes" => "Ghi chú",+ "notes_bold" => "Đậm",+ "notes_italic" => "Nghiêng",+ "notes_list" => "Danh sách",+ "notes_link" => "Liên kết","enable_notifications" => "Bật thông báo cho đăng ký này","default_value_from_settings" => "Giá trị mặc định từ cài đặt","cancellation_notification" => "Thông báo hủy",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex df86745..3d8c3d7 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -128,6 +128,10 @@ $i18n = ["paid_by" => "付款人","url" => "链接","notes" => "备注",+ "notes_bold" => "粗体",+ "notes_italic" => "斜体",+ "notes_list" => "列表",+ "notes_link" => "链接","enable_notifications" => "为此订阅启用通知","default_value_from_settings" => "默认值从设置中获取","cancellation_notification" => "取消通知",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex 009bcb4..0b0eacc 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -123,6 +123,10 @@ $i18n = ["paid_by" => "付款人","url" => "網址","notes" => "備註",+ "notes_bold" => "粗體",+ "notes_italic" => "斜體",+ "notes_list" => "清單",+ "notes_link" => "連結","enable_notifications" => "啟用此訂閱的通知","default_value_from_settings" => "使用設定中的預設值","cancellation_notification" => "取消通知",diff --git a/includes/ical_helper.php b/includes/ical_helper.phpindex 4610f14..3a3dcb4 100644--- a/includes/ical_helper.php+++ b/includes/ical_helper.php@@ -20,4 +20,49 @@ function icalEscape($value)return $value;}+/**+ * Folds a content line to RFC 5545's 75-octet limit: continuation lines+ * are joined with CRLF + a single leading space. Splits only on UTF-8+ * character boundaries so accented/multi-byte text is never cut mid-+ * character. Pass the whole line including its "PROPERTY:" prefix.+ *+ * Notes can now be multi-paragraph Markdown, so DESCRIPTION (built from+ * price/category/payment method/payer/notes) can genuinely exceed 75+ * octets, where before it rarely did - stricter calendar clients can+ * mis-parse an unfolded long line.+ *+ * @param string $line+ * @return string+ */+function icalFold($line)+{+ $limit = 75;++ if (strlen($line) <= $limit) {+ return $line;+ }++ $characters = preg_split('//u', $line, -1, PREG_SPLIT_NO_EMPTY);+ if ($characters === false) {+ // Not valid UTF-8 (shouldn't happen for our text); fall back to a+ // plain byte split rather than leaving the line unfolded.+ return chunk_split($line, $limit, "\r\n ");+ }++ $folded = '';+ $lineLength = 0;++ foreach ($characters as $character) {+ $characterLength = strlen($character);+ if ($lineLength + $characterLength > $limit) {+ $folded .= "\r\n ";+ $lineLength = 0;+ }+ $folded .= $character;+ $lineLength += $characterLength;+ }++ return $folded;+}+?>diff --git a/includes/inputvalidation.php b/includes/inputvalidation.phpindex fdd1c85..0982981 100644--- a/includes/inputvalidation.php+++ b/includes/inputvalidation.php@@ -8,4 +8,19 @@ function validate($value)return $value;}+/**+ * Like validate(), but for fields rendered through render_notes_markdown()+ * (includes/markdown.php) rather than echoed directly: HTML-escaping happens+ * at render time there, so it must not also happen at storage time here.+ *+ * @param string $value+ * @return string+ */+function validate_markdown($value)+{+ $value = trim($value);+ $value = stripslashes($value);+ return $value;+}+?>\ No newline at end of filediff --git a/includes/markdown.php b/includes/markdown.phpnew file mode 100644index 0000000..f5e7861--- /dev/null+++ b/includes/markdown.php@@ -0,0 +1,29 @@+<?php++/**+ * Render subscription notes (Markdown source) to safe HTML.+ *+ * Uses Parsedown's safe mode: any raw HTML the user typed is escaped as+ * text rather than rendered as markup, and link/image URLs are filtered+ * against a scheme allowlist (javascript: is not in it). The output is+ * restricted by construction to the tags Parsedown itself emits from real+ * Markdown syntax, so it's safe to insert with innerHTML.+ *+ * @param string|null $text+ * @return string+ */+function render_notes_markdown($text)+{+ require_once __DIR__ . '/../libs/Parsedown.php';++ static $parser;+ if ($parser === null) {+ $parser = new Parsedown();+ $parser->setSafeMode(true);+ $parser->setBreaksEnabled(true);+ }++ return $parser->text((string) $text);+}++?>diff --git a/includes/subscription_details_popup.php b/includes/subscription_details_popup.phpindex eec0eb6..f2982ec 100644--- a/includes/subscription_details_popup.php+++ b/includes/subscription_details_popup.php@@ -78,7 +78,7 @@ require_once __DIR__ . '/getdbkeys.php';</dl><div class="details-notes hide" id="details-notes-item"><i class="fa-solid fa-note-sticky"></i>- <span id="details-notes"></span>+ <div id="details-notes"></div></div></section>diff --git a/includes/webhook_helper.php b/includes/webhook_helper.phpnew file mode 100644index 0000000..dad0391--- /dev/null+++ b/includes/webhook_helper.php@@ -0,0 +1,21 @@+<?php++/**+ * Escapes a value for safe interpolation into a JSON string field via plain+ * str_replace() templating (the webhook payload template uses+ * "{{placeholder}}" substitution, not real JSON building).+ *+ * Notes can now be multi-line Markdown containing quotes/backslashes, which+ * would otherwise break the payload's JSON structure - json_encode() quotes+ * and escapes the value correctly; the surrounding quotes it adds are+ * trimmed off since the template already supplies them.+ *+ * @param string $value+ * @return string+ */+function webhookJsonEscape($value)+{+ return trim(json_encode((string) $value), '"');+}++?>diff --git a/libs/Parsedown-LICENSE.txt b/libs/Parsedown-LICENSE.txtnew file mode 100644index 0000000..8e7c764--- /dev/null+++ b/libs/Parsedown-LICENSE.txt@@ -0,0 +1,20 @@+The MIT License (MIT)++Copyright (c) 2013-2018 Emanuil Rusev, erusev.com++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/libs/Parsedown.php b/libs/Parsedown.phpnew file mode 100644index 0000000..2f01d5c--- /dev/null+++ b/libs/Parsedown.php@@ -0,0 +1,1995 @@+<?php++#+#+# Parsedown+# http://parsedown.org+#+# (c) Emanuil Rusev+# http://erusev.com+#+# For the full license information, view the LICENSE file that was distributed+# with this source code.+#+#++class Parsedown+{+ # ~++ const version = '1.8.0';++ # ~++ function text($text)+ {+ $Elements = $this->textElements($text);++ # convert to markup+ $markup = $this->elements($Elements);++ # trim line breaks+ $markup = trim($markup, "\n");++ return $markup;+ }++ protected function textElements($text)+ {+ # make sure no definitions are set+ $this->DefinitionData = array();++ # standardize line breaks+ $text = str_replace(array("\r\n", "\r"), "\n", $text);++ # remove surrounding line breaks+ $text = trim($text, "\n");++ # split text into lines+ $lines = explode("\n", $text);++ # iterate through lines to identify blocks+ return $this->linesElements($lines);+ }++ #+ # Setters+ #++ function setBreaksEnabled($breaksEnabled)+ {+ $this->breaksEnabled = $breaksEnabled;++ return $this;+ }++ protected $breaksEnabled;++ function setMarkupEscaped($markupEscaped)+ {+ $this->markupEscaped = $markupEscaped;++ return $this;+ }++ protected $markupEscaped;++ function setUrlsLinked($urlsLinked)+ {+ $this->urlsLinked = $urlsLinked;++ return $this;+ }++ protected $urlsLinked = true;++ function setSafeMode($safeMode)+ {+ $this->safeMode = (bool) $safeMode;++ return $this;+ }++ protected $safeMode;++ function setStrictMode($strictMode)+ {+ $this->strictMode = (bool) $strictMode;++ return $this;+ }++ protected $strictMode;++ protected $safeLinksWhitelist = array(+ 'http://',+ 'https://',+ 'ftp://',+ 'ftps://',+ 'mailto:',+ 'tel:',+ 'data:image/png;base64,',+ 'data:image/gif;base64,',+ 'data:image/jpeg;base64,',+ 'irc:',+ 'ircs:',+ 'git:',+ 'ssh:',+ 'news:',+ 'steam:',+ );++ #+ # Lines+ #++ protected $BlockTypes = array(+ '#' => array('Header'),+ '*' => array('Rule', 'List'),+ '+' => array('List'),+ '-' => array('SetextHeader', 'Table', 'Rule', 'List'),+ '0' => array('List'),+ '1' => array('List'),+ '2' => array('List'),+ '3' => array('List'),+ '4' => array('List'),+ '5' => array('List'),+ '6' => array('List'),+ '7' => array('List'),+ '8' => array('List'),+ '9' => array('List'),+ ':' => array('Table'),+ '<' => array('Comment', 'Markup'),+ '=' => array('SetextHeader'),+ '>' => array('Quote'),+ '[' => array('Reference'),+ '_' => array('Rule'),+ '`' => array('FencedCode'),+ '|' => array('Table'),+ '~' => array('FencedCode'),+ );++ # ~++ protected $unmarkedBlockTypes = array(+ 'Code',+ );++ #+ # Blocks+ #++ protected function lines(array $lines)+ {+ return $this->elements($this->linesElements($lines));+ }++ protected function linesElements(array $lines)+ {+ $Elements = array();+ $CurrentBlock = null;++ foreach ($lines as $line)+ {+ if (chop($line) === '')+ {+ if (isset($CurrentBlock))+ {+ $CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted'])+ ? $CurrentBlock['interrupted'] + 1 : 1+ );+ }++ continue;+ }++ while (($beforeTab = strstr($line, "\t", true)) !== false)+ {+ $shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4;++ $line = $beforeTab+ . str_repeat(' ', $shortage)+ . substr($line, strlen($beforeTab) + 1)+ ;+ }++ $indent = strspn($line, ' ');++ $text = $indent > 0 ? substr($line, $indent) : $line;++ # ~++ $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);++ # ~++ if (isset($CurrentBlock['continuable']))+ {+ $methodName = 'block' . $CurrentBlock['type'] . 'Continue';+ $Block = $this->$methodName($Line, $CurrentBlock);++ if (isset($Block))+ {+ $CurrentBlock = $Block;++ continue;+ }+ else+ {+ if ($this->isBlockCompletable($CurrentBlock['type']))+ {+ $methodName = 'block' . $CurrentBlock['type'] . 'Complete';+ $CurrentBlock = $this->$methodName($CurrentBlock);+ }+ }+ }++ # ~++ $marker = $text[0];++ # ~++ $blockTypes = $this->unmarkedBlockTypes;++ if (isset($this->BlockTypes[$marker]))+ {+ foreach ($this->BlockTypes[$marker] as $blockType)+ {+ $blockTypes []= $blockType;+ }+ }++ #+ # ~++ foreach ($blockTypes as $blockType)+ {+ $Block = $this->{"block$blockType"}($Line, $CurrentBlock);++ if (isset($Block))+ {+ $Block['type'] = $blockType;++ if ( ! isset($Block['identified']))+ {+ if (isset($CurrentBlock))+ {+ $Elements[] = $this->extractElement($CurrentBlock);+ }++ $Block['identified'] = true;+ }++ if ($this->isBlockContinuable($blockType))+ {+ $Block['continuable'] = true;+ }++ $CurrentBlock = $Block;++ continue 2;+ }+ }++ # ~++ if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph')+ {+ $Block = $this->paragraphContinue($Line, $CurrentBlock);+ }++ if (isset($Block))+ {+ $CurrentBlock = $Block;+ }+ else+ {+ if (isset($CurrentBlock))+ {+ $Elements[] = $this->extractElement($CurrentBlock);+ }++ $CurrentBlock = $this->paragraph($Line);++ $CurrentBlock['identified'] = true;+ }+ }++ # ~++ if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))+ {+ $methodName = 'block' . $CurrentBlock['type'] . 'Complete';+ $CurrentBlock = $this->$methodName($CurrentBlock);+ }++ # ~++ if (isset($CurrentBlock))+ {+ $Elements[] = $this->extractElement($CurrentBlock);+ }++ # ~++ return $Elements;+ }++ protected function extractElement(array $Component)+ {+ if ( ! isset($Component['element']))+ {+ if (isset($Component['markup']))+ {+ $Component['element'] = array('rawHtml' => $Component['markup']);+ }+ elseif (isset($Component['hidden']))+ {+ $Component['element'] = array();+ }+ }++ return $Component['element'];+ }++ protected function isBlockContinuable($Type)+ {+ return method_exists($this, 'block' . $Type . 'Continue');+ }++ protected function isBlockCompletable($Type)+ {+ return method_exists($this, 'block' . $Type . 'Complete');+ }++ #+ # Code++ protected function blockCode($Line, $Block = null)+ {+ if (isset($Block) and $Block['type'] === 'Paragraph' and ! isset($Block['interrupted']))+ {+ return;+ }++ if ($Line['indent'] >= 4)+ {+ $text = substr($Line['body'], 4);++ $Block = array(+ 'element' => array(+ 'name' => 'pre',+ 'element' => array(+ 'name' => 'code',+ 'text' => $text,+ ),+ ),+ );++ return $Block;+ }+ }++ protected function blockCodeContinue($Line, $Block)+ {+ if ($Line['indent'] >= 4)+ {+ if (isset($Block['interrupted']))+ {+ $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']);++ unset($Block['interrupted']);+ }++ $Block['element']['element']['text'] .= "\n";++ $text = substr($Line['body'], 4);++ $Block['element']['element']['text'] .= $text;++ return $Block;+ }+ }++ protected function blockCodeComplete($Block)+ {+ return $Block;+ }++ #+ # Comment++ protected function blockComment($Line)+ {+ if ($this->markupEscaped or $this->safeMode)+ {+ return;+ }++ if (strpos($Line['text'], '<!--') === 0)+ {+ $Block = array(+ 'element' => array(+ 'rawHtml' => $Line['body'],+ 'autobreak' => true,+ ),+ );++ if (strpos($Line['text'], '-->') !== false)+ {+ $Block['closed'] = true;+ }++ return $Block;+ }+ }++ protected function blockCommentContinue($Line, array $Block)+ {+ if (isset($Block['closed']))+ {+ return;+ }++ $Block['element']['rawHtml'] .= "\n" . $Line['body'];++ if (strpos($Line['text'], '-->') !== false)+ {+ $Block['closed'] = true;+ }++ return $Block;+ }++ #+ # Fenced Code++ protected function blockFencedCode($Line)+ {+ $marker = $Line['text'][0];++ $openerLength = strspn($Line['text'], $marker);++ if ($openerLength < 3)+ {+ return;+ }++ $infostring = trim(substr($Line['text'], $openerLength), "\t ");++ if (strpos($infostring, '`') !== false)+ {+ return;+ }++ $Element = array(+ 'name' => 'code',+ 'text' => '',+ );++ if ($infostring !== '')+ {+ /**+ * https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes+ * Every HTML element may have a class attribute specified.+ * The attribute, if specified, must have a value that is a set+ * of space-separated tokens representing the various classes+ * that the element belongs to.+ * [...]+ * The space characters, for the purposes of this specification,+ * are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab),+ * U+000A LINE FEED (LF), U+000C FORM FEED (FF), and+ * U+000D CARRIAGE RETURN (CR).+ */+ $language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r"));++ $Element['attributes'] = array('class' => "language-$language");+ }++ $Block = array(+ 'char' => $marker,+ 'openerLength' => $openerLength,+ 'element' => array(+ 'name' => 'pre',+ 'element' => $Element,+ ),+ );++ return $Block;+ }++ protected function blockFencedCodeContinue($Line, $Block)+ {+ if (isset($Block['complete']))+ {+ return;+ }++ if (isset($Block['interrupted']))+ {+ $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']);++ unset($Block['interrupted']);+ }++ if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength']+ and chop(substr($Line['text'], $len), ' ') === ''+ ) {+ $Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1);++ $Block['complete'] = true;++ return $Block;+ }++ $Block['element']['element']['text'] .= "\n" . $Line['body'];++ return $Block;+ }++ protected function blockFencedCodeComplete($Block)+ {+ return $Block;+ }++ #+ # Header++ protected function blockHeader($Line)+ {+ $level = strspn($Line['text'], '#');++ if ($level > 6)+ {+ return;+ }++ $text = trim($Line['text'], '#');++ if ($this->strictMode and isset($text[0]) and $text[0] !== ' ')+ {+ return;+ }++ $text = trim($text, ' ');++ $Block = array(+ 'element' => array(+ 'name' => 'h' . $level,+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $text,+ 'destination' => 'elements',+ )+ ),+ );++ return $Block;+ }++ #+ # List++ protected function blockList($Line, ?array $CurrentBlock = null)+ {+ list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]');++ if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches))+ {+ $contentIndent = strlen($matches[2]);++ if ($contentIndent >= 5)+ {+ $contentIndent -= 1;+ $matches[1] = substr($matches[1], 0, -$contentIndent);+ $matches[3] = str_repeat(' ', $contentIndent) . $matches[3];+ }+ elseif ($contentIndent === 0)+ {+ $matches[1] .= ' ';+ }++ $markerWithoutWhitespace = strstr($matches[1], ' ', true);++ $Block = array(+ 'indent' => $Line['indent'],+ 'pattern' => $pattern,+ 'data' => array(+ 'type' => $name,+ 'marker' => $matches[1],+ 'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1)),+ ),+ 'element' => array(+ 'name' => $name,+ 'elements' => array(),+ ),+ );+ $Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/');++ if ($name === 'ol')+ {+ $listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0';++ if ($listStart !== '1')+ {+ if (+ isset($CurrentBlock)+ and $CurrentBlock['type'] === 'Paragraph'+ and ! isset($CurrentBlock['interrupted'])+ ) {+ return;+ }++ $Block['element']['attributes'] = array('start' => $listStart);+ }+ }++ $Block['li'] = array(+ 'name' => 'li',+ 'handler' => array(+ 'function' => 'li',+ 'argument' => !empty($matches[3]) ? array($matches[3]) : array(),+ 'destination' => 'elements'+ )+ );++ $Block['element']['elements'] []= & $Block['li'];++ return $Block;+ }+ }++ protected function blockListContinue($Line, array $Block)+ {+ if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument']))+ {+ return null;+ }++ $requiredIndent = ($Block['indent'] + strlen($Block['data']['marker']));++ if ($Line['indent'] < $requiredIndent+ and (+ (+ $Block['data']['type'] === 'ol'+ and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches)+ ) or (+ $Block['data']['type'] === 'ul'+ and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches)+ )+ )+ ) {+ if (isset($Block['interrupted']))+ {+ $Block['li']['handler']['argument'] []= '';++ $Block['loose'] = true;++ unset($Block['interrupted']);+ }++ unset($Block['li']);++ $text = isset($matches[1]) ? $matches[1] : '';++ $Block['indent'] = $Line['indent'];++ $Block['li'] = array(+ 'name' => 'li',+ 'handler' => array(+ 'function' => 'li',+ 'argument' => array($text),+ 'destination' => 'elements'+ )+ );++ $Block['element']['elements'] []= & $Block['li'];++ return $Block;+ }+ elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line))+ {+ return null;+ }++ if ($Line['text'][0] === '[' and $this->blockReference($Line))+ {+ return $Block;+ }++ if ($Line['indent'] >= $requiredIndent)+ {+ if (isset($Block['interrupted']))+ {+ $Block['li']['handler']['argument'] []= '';++ $Block['loose'] = true;++ unset($Block['interrupted']);+ }++ $text = substr($Line['body'], $requiredIndent);++ $Block['li']['handler']['argument'] []= $text;++ return $Block;+ }++ if ( ! isset($Block['interrupted']))+ {+ $text = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']);++ $Block['li']['handler']['argument'] []= $text;++ return $Block;+ }+ }++ protected function blockListComplete(array $Block)+ {+ if (isset($Block['loose']))+ {+ foreach ($Block['element']['elements'] as &$li)+ {+ if (end($li['handler']['argument']) !== '')+ {+ $li['handler']['argument'] []= '';+ }+ }+ }++ return $Block;+ }++ #+ # Quote++ protected function blockQuote($Line)+ {+ if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches))+ {+ $Block = array(+ 'element' => array(+ 'name' => 'blockquote',+ 'handler' => array(+ 'function' => 'linesElements',+ 'argument' => (array) $matches[1],+ 'destination' => 'elements',+ )+ ),+ );++ return $Block;+ }+ }++ protected function blockQuoteContinue($Line, array $Block)+ {+ if (isset($Block['interrupted']))+ {+ return;+ }++ if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches))+ {+ $Block['element']['handler']['argument'] []= $matches[1];++ return $Block;+ }++ if ( ! isset($Block['interrupted']))+ {+ $Block['element']['handler']['argument'] []= $Line['text'];++ return $Block;+ }+ }++ #+ # Rule++ protected function blockRule($Line)+ {+ $marker = $Line['text'][0];++ if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '')+ {+ $Block = array(+ 'element' => array(+ 'name' => 'hr',+ ),+ );++ return $Block;+ }+ }++ #+ # Setext++ protected function blockSetextHeader($Line, ?array $Block = null)+ {+ if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted']))+ {+ return;+ }++ if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '')+ {+ $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';++ return $Block;+ }+ }++ #+ # Markup++ protected function blockMarkup($Line)+ {+ if ($this->markupEscaped or $this->safeMode)+ {+ return;+ }++ if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches))+ {+ $element = strtolower($matches[1]);++ if (in_array($element, $this->textLevelElements))+ {+ return;+ }++ $Block = array(+ 'name' => $matches[1],+ 'element' => array(+ 'rawHtml' => $Line['text'],+ 'autobreak' => true,+ ),+ );++ return $Block;+ }+ }++ protected function blockMarkupContinue($Line, array $Block)+ {+ if (isset($Block['closed']) or isset($Block['interrupted']))+ {+ return;+ }++ $Block['element']['rawHtml'] .= "\n" . $Line['body'];++ return $Block;+ }++ #+ # Reference++ protected function blockReference($Line)+ {+ if (strpos($Line['text'], ']') !== false+ and preg_match('/^\[(.+?)\]:[ ]*+<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches)+ ) {+ $id = strtolower($matches[1]);++ $Data = array(+ 'url' => $matches[2],+ 'title' => isset($matches[3]) ? $matches[3] : null,+ );++ $this->DefinitionData['Reference'][$id] = $Data;++ $Block = array(+ 'element' => array(),+ );++ return $Block;+ }+ }++ #+ # Table++ protected function blockTable($Line, ?array $Block = null)+ {+ if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted']))+ {+ return;+ }++ if (+ strpos($Block['element']['handler']['argument'], '|') === false+ and strpos($Line['text'], '|') === false+ and strpos($Line['text'], ':') === false+ or strpos($Block['element']['handler']['argument'], "\n") !== false+ ) {+ return;+ }++ if (chop($Line['text'], ' -:|') !== '')+ {+ return;+ }++ $alignments = array();++ $divider = $Line['text'];++ $divider = trim($divider);+ $divider = trim($divider, '|');++ $dividerCells = explode('|', $divider);++ foreach ($dividerCells as $dividerCell)+ {+ $dividerCell = trim($dividerCell);++ if ($dividerCell === '')+ {+ return;+ }++ $alignment = null;++ if ($dividerCell[0] === ':')+ {+ $alignment = 'left';+ }++ if (substr($dividerCell, - 1) === ':')+ {+ $alignment = $alignment === 'left' ? 'center' : 'right';+ }++ $alignments []= $alignment;+ }++ # ~++ $HeaderElements = array();++ $header = $Block['element']['handler']['argument'];++ $header = trim($header);+ $header = trim($header, '|');++ $headerCells = explode('|', $header);++ if (count($headerCells) !== count($alignments))+ {+ return;+ }++ foreach ($headerCells as $index => $headerCell)+ {+ $headerCell = trim($headerCell);++ $HeaderElement = array(+ 'name' => 'th',+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $headerCell,+ 'destination' => 'elements',+ )+ );++ if (isset($alignments[$index]))+ {+ $alignment = $alignments[$index];++ $HeaderElement['attributes'] = array(+ 'style' => "text-align: $alignment;",+ );+ }++ $HeaderElements []= $HeaderElement;+ }++ # ~++ $Block = array(+ 'alignments' => $alignments,+ 'identified' => true,+ 'element' => array(+ 'name' => 'table',+ 'elements' => array(),+ ),+ );++ $Block['element']['elements'] []= array(+ 'name' => 'thead',+ );++ $Block['element']['elements'] []= array(+ 'name' => 'tbody',+ 'elements' => array(),+ );++ $Block['element']['elements'][0]['elements'] []= array(+ 'name' => 'tr',+ 'elements' => $HeaderElements,+ );++ return $Block;+ }++ protected function blockTableContinue($Line, array $Block)+ {+ if (isset($Block['interrupted']))+ {+ return;+ }++ if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|'))+ {+ $Elements = array();++ $row = $Line['text'];++ $row = trim($row);+ $row = trim($row, '|');++ preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches);++ $cells = array_slice($matches[0], 0, count($Block['alignments']));++ foreach ($cells as $index => $cell)+ {+ $cell = trim($cell);++ $Element = array(+ 'name' => 'td',+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $cell,+ 'destination' => 'elements',+ )+ );++ if (isset($Block['alignments'][$index]))+ {+ $Element['attributes'] = array(+ 'style' => 'text-align: ' . $Block['alignments'][$index] . ';',+ );+ }++ $Elements []= $Element;+ }++ $Element = array(+ 'name' => 'tr',+ 'elements' => $Elements,+ );++ $Block['element']['elements'][1]['elements'] []= $Element;++ return $Block;+ }+ }++ #+ # ~+ #++ protected function paragraph($Line)+ {+ return array(+ 'type' => 'Paragraph',+ 'element' => array(+ 'name' => 'p',+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $Line['text'],+ 'destination' => 'elements',+ ),+ ),+ );+ }++ protected function paragraphContinue($Line, array $Block)+ {+ if (isset($Block['interrupted']))+ {+ return;+ }++ $Block['element']['handler']['argument'] .= "\n".$Line['text'];++ return $Block;+ }++ #+ # Inline Elements+ #++ protected $InlineTypes = array(+ '!' => array('Image'),+ '&' => array('SpecialCharacter'),+ '*' => array('Emphasis'),+ ':' => array('Url'),+ '<' => array('UrlTag', 'EmailTag', 'Markup'),+ '[' => array('Link'),+ '_' => array('Emphasis'),+ '`' => array('Code'),+ '~' => array('Strikethrough'),+ '\\' => array('EscapeSequence'),+ );++ # ~++ protected $inlineMarkerList = '!*_&[:<`~\\';++ #+ # ~+ #++ public function line($text, $nonNestables = array())+ {+ return $this->elements($this->lineElements($text, $nonNestables));+ }++ protected function lineElements($text, $nonNestables = array())+ {+ # standardize line breaks+ $text = str_replace(array("\r\n", "\r"), "\n", $text);++ $Elements = array();++ $nonNestables = (empty($nonNestables)+ ? array()+ : array_combine($nonNestables, $nonNestables)+ );++ # $excerpt is based on the first occurrence of a marker++ while ($excerpt = strpbrk($text, $this->inlineMarkerList))+ {+ $marker = $excerpt[0];++ $markerPosition = strlen($text) - strlen($excerpt);++ $Excerpt = array('text' => $excerpt, 'context' => $text);++ foreach ($this->InlineTypes[$marker] as $inlineType)+ {+ # check to see if the current inline type is nestable in the current context++ if (isset($nonNestables[$inlineType]))+ {+ continue;+ }++ $Inline = $this->{"inline$inlineType"}($Excerpt);++ if ( ! isset($Inline))+ {+ continue;+ }++ # makes sure that the inline belongs to "our" marker++ if (isset($Inline['position']) and $Inline['position'] > $markerPosition)+ {+ continue;+ }++ # sets a default inline position++ if ( ! isset($Inline['position']))+ {+ $Inline['position'] = $markerPosition;+ }++ # cause the new element to 'inherit' our non nestables+++ $Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables'])+ ? array_merge($Inline['element']['nonNestables'], $nonNestables)+ : $nonNestables+ ;++ # the text that comes before the inline+ $unmarkedText = substr($text, 0, $Inline['position']);++ # compile the unmarked text+ $InlineText = $this->inlineText($unmarkedText);+ $Elements[] = $InlineText['element'];++ # compile the inline+ $Elements[] = $this->extractElement($Inline);++ # remove the examined text+ $text = substr($text, $Inline['position'] + $Inline['extent']);++ continue 2;+ }++ # the marker does not belong to an inline++ $unmarkedText = substr($text, 0, $markerPosition + 1);++ $InlineText = $this->inlineText($unmarkedText);+ $Elements[] = $InlineText['element'];++ $text = substr($text, $markerPosition + 1);+ }++ $InlineText = $this->inlineText($text);+ $Elements[] = $InlineText['element'];++ foreach ($Elements as &$Element)+ {+ if ( ! isset($Element['autobreak']))+ {+ $Element['autobreak'] = false;+ }+ }++ return $Elements;+ }++ #+ # ~+ #++ protected function inlineText($text)+ {+ $Inline = array(+ 'extent' => strlen($text),+ 'element' => array(),+ );++ $Inline['element']['elements'] = self::pregReplaceElements(+ $this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/',+ array(+ array('name' => 'br'),+ array('text' => "\n"),+ ),+ $text+ );++ return $Inline;+ }++ protected function inlineCode($Excerpt)+ {+ $marker = $Excerpt['text'][0];++ if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(?<!['.$marker.'])\1(?!'.$marker.')/s', $Excerpt['text'], $matches))+ {+ $text = $matches[2];+ $text = preg_replace('/[ ]*+\n/', ' ', $text);++ return array(+ 'extent' => strlen($matches[0]),+ 'element' => array(+ 'name' => 'code',+ 'text' => $text,+ ),+ );+ }+ }++ protected function inlineEmailTag($Excerpt)+ {+ $hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?';++ $commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@'+ . $hostnameLabel . '(?:\.' . $hostnameLabel . ')*';++ if (strpos($Excerpt['text'], '>') !== false+ and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches)+ ){+ $url = $matches[1];++ if ( ! isset($matches[2]))+ {+ $url = "mailto:$url";+ }++ return array(+ 'extent' => strlen($matches[0]),+ 'element' => array(+ 'name' => 'a',+ 'text' => $matches[1],+ 'attributes' => array(+ 'href' => $url,+ ),+ ),+ );+ }+ }++ protected function inlineEmphasis($Excerpt)+ {+ if ( ! isset($Excerpt['text'][1]))+ {+ return;+ }++ $marker = $Excerpt['text'][0];++ if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))+ {+ $emphasis = 'strong';+ }+ elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))+ {+ $emphasis = 'em';+ }+ else+ {+ return;+ }++ return array(+ 'extent' => strlen($matches[0]),+ 'element' => array(+ 'name' => $emphasis,+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $matches[1],+ 'destination' => 'elements',+ )+ ),+ );+ }++ protected function inlineEscapeSequence($Excerpt)+ {+ if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))+ {+ return array(+ 'element' => array('rawHtml' => $Excerpt['text'][1]),+ 'extent' => 2,+ );+ }+ }++ protected function inlineImage($Excerpt)+ {+ if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')+ {+ return;+ }++ $Excerpt['text']= substr($Excerpt['text'], 1);++ $Link = $this->inlineLink($Excerpt);++ if ($Link === null)+ {+ return;+ }++ $Inline = array(+ 'extent' => $Link['extent'] + 1,+ 'element' => array(+ 'name' => 'img',+ 'attributes' => array(+ 'src' => $Link['element']['attributes']['href'],+ 'alt' => $Link['element']['handler']['argument'],+ ),+ 'autobreak' => true,+ ),+ );++ $Inline['element']['attributes'] += $Link['element']['attributes'];++ unset($Inline['element']['attributes']['href']);++ return $Inline;+ }++ protected function inlineLink($Excerpt)+ {+ $Element = array(+ 'name' => 'a',+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => null,+ 'destination' => 'elements',+ ),+ 'nonNestables' => array('Url', 'Link'),+ 'attributes' => array(+ 'href' => null,+ 'title' => null,+ ),+ );++ $extent = 0;++ $remainder = $Excerpt['text'];++ if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches))+ {+ $Element['handler']['argument'] = $matches[1];++ $extent += strlen($matches[0]);++ $remainder = substr($remainder, $extent);+ }+ else+ {+ return;+ }++ if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*+"|\'[^\']*+\'))?\s*+[)]/', $remainder, $matches))+ {+ $Element['attributes']['href'] = $matches[1];++ if (isset($matches[2]))+ {+ $Element['attributes']['title'] = substr($matches[2], 1, - 1);+ }++ $extent += strlen($matches[0]);+ }+ else+ {+ if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))+ {+ $definition = strlen($matches[1]) ? $matches[1] : $Element['handler']['argument'];+ $definition = strtolower($definition);++ $extent += strlen($matches[0]);+ }+ else+ {+ $definition = strtolower($Element['handler']['argument']);+ }++ if ( ! isset($this->DefinitionData['Reference'][$definition]))+ {+ return;+ }++ $Definition = $this->DefinitionData['Reference'][$definition];++ $Element['attributes']['href'] = $Definition['url'];+ $Element['attributes']['title'] = $Definition['title'];+ }++ return array(+ 'extent' => $extent,+ 'element' => $Element,+ );+ }++ protected function inlineMarkup($Excerpt)+ {+ if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false)+ {+ return;+ }++ if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches))+ {+ return array(+ 'element' => array('rawHtml' => $matches[0]),+ 'extent' => strlen($matches[0]),+ );+ }++ if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?+[^-])*-->/s', $Excerpt['text'], $matches))+ {+ return array(+ 'element' => array('rawHtml' => $matches[0]),+ 'extent' => strlen($matches[0]),+ );+ }++ if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w[\w-]*+(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+\/?>/s', $Excerpt['text'], $matches))+ {+ return array(+ 'element' => array('rawHtml' => $matches[0]),+ 'extent' => strlen($matches[0]),+ );+ }+ }++ protected function inlineSpecialCharacter($Excerpt)+ {+ if (substr($Excerpt['text'], 1, 1) !== ' ' and strpos($Excerpt['text'], ';') !== false+ and preg_match('/^&(#?+[0-9a-zA-Z]++);/', $Excerpt['text'], $matches)+ ) {+ return array(+ 'element' => array('rawHtml' => '&' . $matches[1] . ';'),+ 'extent' => strlen($matches[0]),+ );+ }+ }++ protected function inlineStrikethrough($Excerpt)+ {+ if ( ! isset($Excerpt['text'][1]))+ {+ return;+ }++ if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))+ {+ return array(+ 'extent' => strlen($matches[0]),+ 'element' => array(+ 'name' => 'del',+ 'handler' => array(+ 'function' => 'lineElements',+ 'argument' => $matches[1],+ 'destination' => 'elements',+ )+ ),+ );+ }+ }++ protected function inlineUrl($Excerpt)+ {+ if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')+ {+ return;+ }++ if (strpos($Excerpt['context'], 'http') !== false+ and preg_match('/\bhttps?+:[\/]{2}[^\s<]+\b\/*+/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)+ ) {+ $url = $matches[0][0];++ $Inline = array(+ 'extent' => strlen($matches[0][0]),+ 'position' => $matches[0][1],+ 'element' => array(+ 'name' => 'a',+ 'text' => $url,+ 'attributes' => array(+ 'href' => $url,+ ),+ ),+ );++ return $Inline;+ }+ }++ protected function inlineUrlTag($Excerpt)+ {+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w++:\/{2}[^ >]++)>/i', $Excerpt['text'], $matches))+ {+ $url = $matches[1];++ return array(+ 'extent' => strlen($matches[0]),+ 'element' => array(+ 'name' => 'a',+ 'text' => $url,+ 'attributes' => array(+ 'href' => $url,+ ),+ ),+ );+ }+ }++ # ~++ protected function unmarkedText($text)+ {+ $Inline = $this->inlineText($text);+ return $this->element($Inline['element']);+ }++ #+ # Handlers+ #++ protected function handle(array $Element)+ {+ if (isset($Element['handler']))+ {+ if (!isset($Element['nonNestables']))+ {+ $Element['nonNestables'] = array();+ }++ if (is_string($Element['handler']))+ {+ $function = $Element['handler'];+ $argument = $Element['text'];+ unset($Element['text']);+ $destination = 'rawHtml';+ }+ else+ {+ $function = $Element['handler']['function'];+ $argument = $Element['handler']['argument'];+ $destination = $Element['handler']['destination'];+ }++ $Element[$destination] = $this->{$function}($argument, $Element['nonNestables']);++ if ($destination === 'handler')+ {+ $Element = $this->handle($Element);+ }++ unset($Element['handler']);+ }++ return $Element;+ }++ protected function handleElementRecursive(array $Element)+ {+ return $this->elementApplyRecursive(array($this, 'handle'), $Element);+ }++ protected function handleElementsRecursive(array $Elements)+ {+ return $this->elementsApplyRecursive(array($this, 'handle'), $Elements);+ }++ protected function elementApplyRecursive($closure, array $Element)+ {+ $Element = call_user_func($closure, $Element);++ if (isset($Element['elements']))+ {+ $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']);+ }+ elseif (isset($Element['element']))+ {+ $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']);+ }++ return $Element;+ }++ protected function elementApplyRecursiveDepthFirst($closure, array $Element)+ {+ if (isset($Element['elements']))+ {+ $Element['elements'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['elements']);+ }+ elseif (isset($Element['element']))+ {+ $Element['element'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['element']);+ }++ $Element = call_user_func($closure, $Element);++ return $Element;+ }++ protected function elementsApplyRecursive($closure, array $Elements)+ {+ foreach ($Elements as &$Element)+ {+ $Element = $this->elementApplyRecursive($closure, $Element);+ }++ return $Elements;+ }++ protected function elementsApplyRecursiveDepthFirst($closure, array $Elements)+ {+ foreach ($Elements as &$Element)+ {+ $Element = $this->elementApplyRecursiveDepthFirst($closure, $Element);+ }++ return $Elements;+ }++ protected function element(array $Element)+ {+ if ($this->safeMode)+ {+ $Element = $this->sanitiseElement($Element);+ }++ # identity map if element has no handler+ $Element = $this->handle($Element);++ $hasName = isset($Element['name']);++ $markup = '';++ if ($hasName)+ {+ $markup .= '<' . $Element['name'];++ if (isset($Element['attributes']))+ {+ foreach ($Element['attributes'] as $name => $value)+ {+ if ($value === null)+ {+ continue;+ }++ $markup .= " $name=\"".self::escape($value).'"';+ }+ }+ }++ $permitRawHtml = false;++ if (isset($Element['text']))+ {+ $text = $Element['text'];+ }+ // very strongly consider an alternative if you're writing an+ // extension+ elseif (isset($Element['rawHtml']))+ {+ $text = $Element['rawHtml'];++ $allowRawHtmlInSafeMode = isset($Element['allowRawHtmlInSafeMode']) && $Element['allowRawHtmlInSafeMode'];+ $permitRawHtml = !$this->safeMode || $allowRawHtmlInSafeMode;+ }++ $hasContent = isset($text) || isset($Element['element']) || isset($Element['elements']);++ if ($hasContent)+ {+ $markup .= $hasName ? '>' : '';++ if (isset($Element['elements']))+ {+ $markup .= $this->elements($Element['elements']);+ }+ elseif (isset($Element['element']))+ {+ $markup .= $this->element($Element['element']);+ }+ else+ {+ if (!$permitRawHtml)+ {+ $markup .= self::escape($text, true);+ }+ else+ {+ $markup .= $text;+ }+ }++ $markup .= $hasName ? '</' . $Element['name'] . '>' : '';+ }+ elseif ($hasName)+ {+ $markup .= ' />';+ }++ return $markup;+ }++ protected function elements(array $Elements)+ {+ $markup = '';++ $autoBreak = true;++ foreach ($Elements as $Element)+ {+ if (empty($Element))+ {+ continue;+ }++ $autoBreakNext = (isset($Element['autobreak'])+ ? $Element['autobreak'] : isset($Element['name'])+ );+ // (autobreak === false) covers both sides of an element+ $autoBreak = !$autoBreak ? $autoBreak : $autoBreakNext;++ $markup .= ($autoBreak ? "\n" : '') . $this->element($Element);+ $autoBreak = $autoBreakNext;+ }++ $markup .= $autoBreak ? "\n" : '';++ return $markup;+ }++ # ~++ protected function li($lines)+ {+ $Elements = $this->linesElements($lines);++ if ( ! in_array('', $lines)+ and isset($Elements[0]) and isset($Elements[0]['name'])+ and $Elements[0]['name'] === 'p'+ ) {+ unset($Elements[0]['name']);+ }++ return $Elements;+ }++ #+ # AST Convenience+ #++ /**+ * Replace occurrences $regexp with $Elements in $text. Return an array of+ * elements representing the replacement.+ */+ protected static function pregReplaceElements($regexp, $Elements, $text)+ {+ $newElements = array();++ while (preg_match($regexp, $text, $matches, PREG_OFFSET_CAPTURE))+ {+ $offset = $matches[0][1];+ $before = substr($text, 0, $offset);+ $after = substr($text, $offset + strlen($matches[0][0]));++ $newElements[] = array('text' => $before);++ foreach ($Elements as $Element)+ {+ $newElements[] = $Element;+ }++ $text = $after;+ }++ $newElements[] = array('text' => $text);++ return $newElements;+ }++ #+ # Deprecated Methods+ #++ /**+ * @deprecated use text() instead+ */+ function parse($text)+ {+ $markup = $this->text($text);++ return $markup;+ }++ protected function sanitiseElement(array $Element)+ {+ static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/';+ static $safeUrlNameToAtt = array(+ 'a' => 'href',+ 'img' => 'src',+ );++ if ( ! isset($Element['name']))+ {+ unset($Element['attributes']);+ return $Element;+ }++ if (isset($safeUrlNameToAtt[$Element['name']]))+ {+ $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]);+ }++ if ( ! empty($Element['attributes']))+ {+ foreach ($Element['attributes'] as $att => $val)+ {+ # filter out badly parsed attribute+ if ( ! preg_match($goodAttribute, $att))+ {+ unset($Element['attributes'][$att]);+ }+ # dump onevent attribute+ elseif (self::striAtStart($att, 'on'))+ {+ unset($Element['attributes'][$att]);+ }+ }+ }++ return $Element;+ }++ protected function filterUnsafeUrlInAttribute(array $Element, $attribute)+ {+ foreach ($this->safeLinksWhitelist as $scheme)+ {+ if (self::striAtStart($Element['attributes'][$attribute], $scheme))+ {+ return $Element;+ }+ }++ $Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]);++ return $Element;+ }++ #+ # Static Methods+ #++ protected static function escape($text, $allowQuotes = false)+ {+ return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8');+ }++ protected static function striAtStart($string, $needle)+ {+ $len = strlen($needle);++ if ($len > strlen($string))+ {+ return false;+ }+ else+ {+ return strtolower(substr($string, 0, $len)) === strtolower($needle);+ }+ }++ static function instance($name = 'default')+ {+ if (isset(self::$instances[$name]))+ {+ return self::$instances[$name];+ }++ $instance = new static();++ self::$instances[$name] = $instance;++ return $instance;+ }++ private static $instances = array();++ #+ # Fields+ #++ protected $DefinitionData;++ #+ # Read-Only++ protected $specialCharacters = array(+ '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', '~'+ );++ protected $StrongRegex = array(+ '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s',+ '_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us',+ );++ protected $EmRegex = array(+ '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',+ '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',+ );++ protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+';++ protected $voidElements = array(+ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',+ );++ protected $textLevelElements = array(+ 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',+ 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',+ 'i', 'rp', 'del', 'code', 'strike', 'marquee',+ 'q', 'rt', 'ins', 'font', 'strong',+ 's', 'tt', 'kbd', 'mark',+ 'u', 'xm', 'sub', 'nobr',+ 'sup', 'ruby',+ 'var', 'span',+ 'wbr', 'time',+ );+}diff --git a/migrations/000058.php b/migrations/000058.phpnew file mode 100644index 0000000..ea37337--- /dev/null+++ b/migrations/000058.php@@ -0,0 +1,22 @@+<?php++// Subscription notes used to be stored HTML-escaped (htmlspecialchars() at+// save time, decoded back only when populating the edit form). Notes are+// now rendered through a Markdown parser instead, which escapes at render+// time, so storage must go back to holding plain text. This one-time+// migration decodes existing rows so old notes don't render double-escaped+// (or with literal &/') under the new renderer.+//+// Safe to run twice: decoding plain text (no entities) is a no-op.++$result = $db->query("SELECT id, notes FROM subscriptions WHERE notes IS NOT NULL AND notes != ''");++$stmt = $db->prepare('UPDATE subscriptions SET notes = :notes WHERE id = :id');+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $decoded = html_entity_decode($row['notes'], ENT_QUOTES, 'UTF-8');+ $stmt->bindValue(':notes', $decoded, SQLITE3_TEXT);+ $stmt->bindValue(':id', $row['id'], SQLITE3_INTEGER);+ $stmt->execute();+}++?>diff --git a/scripts/profile.js b/scripts/profile.jsindex e9a90d3..bfe84c6 100644--- a/scripts/profile.js+++ b/scripts/profile.js@@ -324,14 +324,25 @@ function exportAsJson() {});}+function csvField(value) {+ const stringValue = String(value ?? '');+ // Notes can now be multi-paragraph Markdown, so a field with an embedded+ // newline is common, not an edge case - quote (RFC 4180) whenever a+ // comma, quote, or newline would otherwise corrupt the row structure.+ if (/[",\r\n]/.test(stringValue)) {+ return '"' + stringValue.replace(/"/g, '""') + '"';+ }+ return stringValue;+}+function exportAsCsv() {fetch("endpoints/subscriptions/export.php").then(response => response.json()).then(data => {if (data.success) {const subscriptions = data.subscriptions;- const header = Object.keys(subscriptions[0]).join(',');- const csv = subscriptions.map(subscription => Object.values(subscription).join(',')).join('\n');+ const header = Object.keys(subscriptions[0]).map(csvField).join(',');+ const csv = subscriptions.map(subscription => Object.values(subscription).map(csvField).join(',')).join('\n');const csvWithHeader = header + '\n' + csv;const element = document.createElement('a');element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csvWithHeader));diff --git a/scripts/subscription-details.js b/scripts/subscription-details.jsindex eb7fa36..d18511a 100644--- a/scripts/subscription-details.js+++ b/scripts/subscription-details.js@@ -203,7 +203,9 @@ function renderSubscriptionDetails(subscription) {const notesItem = document.querySelector('#details-notes-item');if (subscription.notes) {notesItem.classList.remove('hide');- document.querySelector('#details-notes').textContent = subscription.notes;+ // notes_html is rendered server-side through render_notes_markdown()+ // (Parsedown safe mode) - never raw user text.+ document.querySelector('#details-notes').innerHTML = subscription.notes_html;} else {notesItem.classList.add('hide');}diff --git a/scripts/subscriptions.js b/scripts/subscriptions.jsindex 60767ae..d4fb907 100644--- a/scripts/subscriptions.js+++ b/scripts/subscriptions.js@@ -1213,6 +1213,42 @@ function toISOStringWithTimezone(date) {':' + minutesOffset;}+function insertMarkdownSyntax(textarea, prefix, suffix, placeholder) {+ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ const selected = textarea.value.slice(start, end) || placeholder;++ textarea.setRangeText(prefix + selected + suffix, start, end, 'select');+ textarea.focus();+ textarea.setSelectionRange(start + prefix.length, start + prefix.length + selected.length);+}++function applyNotesMarkdown(action) {+ const textarea = document.querySelector('#notes');+ if (!textarea) {+ return;+ }++ switch (action) {+ case 'bold':+ insertMarkdownSyntax(textarea, '**', '**', translate('notes_bold'));+ break;+ case 'italic':+ insertMarkdownSyntax(textarea, '_', '_', translate('notes_italic'));+ break;+ case 'list': {+ const start = textarea.selectionStart;+ const lineStart = textarea.value.lastIndexOf('\n', start - 1) + 1;+ textarea.setRangeText('- ', lineStart, lineStart, 'end');+ textarea.focus();+ break;+ }+ case 'link':+ insertMarkdownSyntax(textarea, '[', '](https://)', translate('notes_link'));+ break;+ }+}+window.addEventListener('load', () => {if (document.querySelector('.subscription')) {swipeHintAnimation();diff --git a/styles/styles.css b/styles/styles.cssindex 5e75b51..38c5f6b 100644--- a/styles/styles.css+++ b/styles/styles.css@@ -1362,6 +1362,61 @@ header #avatar {margin-bottom: 20px;}+.notes-editor {+ border: 1px solid var(--input-border-color);+ border-radius: 10px;+ background-color: var(--input-background-color);+ overflow: hidden;+ transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;+}++.notes-editor:focus-within {+ border-color: var(--main-color);+ box-shadow: var(--focus-ring);+}++.notes-toolbar {+ display: flex;+ flex-direction: row;+ flex-wrap: wrap;+ align-items: center;+ gap: 2px;+ padding: 6px;+ background-color: var(--surface-hover);+ border-bottom: 1px solid var(--input-border-color);+}++.notes-toolbar-button {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ padding: 0;+ border: none;+ border-radius: 6px;+ background: transparent;+ color: var(--text-color);+ cursor: pointer;+ transition: background-color .15s ease-in-out, color .15s ease-in-out;+}++.notes-toolbar-button:hover {+ background-color: var(--hover-color);+ color: #fff;+}++.notes-editor textarea {+ display: block;+ border: none;+ border-radius: 0;+ background: transparent;+}++.notes-editor textarea:focus {+ box-shadow: none;+}+.form-group-inline {display: flex;flex-direction: row;@@ -1632,6 +1687,7 @@ textarea {color: var(--text-color);width: 100%;height: 245px;+ box-sizing: border-box;}textarea:focus {@@ -4060,21 +4116,20 @@ body.details-open {}.details-notes {- display: flex;- flex-direction: row;- align-items: flex-start;- gap: 10px;+ position: relative;background-color: var(--surface-hover);border-radius: 12px;- padding: 12px 14px;+ padding: 12px 34px 12px 14px;font-size: 14px;margin-bottom: 16px;overflow-wrap: anywhere;}.details-notes i {+ position: absolute;+ top: 12px;+ right: 14px;color: var(--main-color);- margin-top: 2px;}@media (max-width: 768px) {diff --git a/subscriptions.php b/subscriptions.phpindex da06cd6..2a66892 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -516,7 +516,23 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip</div><div class="form-group">- <input type="text" id="notes" name="notes" autocomplete="off" placeholder="<?= translate('notes', $i18n) ?>">+ <div class="notes-editor">+ <div class="notes-toolbar">+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_bold', $i18n) ?>" onClick="applyNotesMarkdown('bold')">+ <i class="fa-solid fa-bold"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_italic', $i18n) ?>" onClick="applyNotesMarkdown('italic')">+ <i class="fa-solid fa-italic"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_list', $i18n) ?>" onClick="applyNotesMarkdown('list')">+ <i class="fa-solid fa-list-ul"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_link', $i18n) ?>" onClick="applyNotesMarkdown('link')">+ <i class="fa-solid fa-link"></i>+ </button>+ </div>+ <textarea id="notes" name="notes" class="thin" autocomplete="off" placeholder="<?= translate('notes', $i18n) ?>"></textarea>+ </div></div><div class="form-group">diff --git a/tests/cases/ical_export_test.php b/tests/cases/ical_export_test.phpnew file mode 100644index 0000000..122f7f9--- /dev/null+++ b/tests/cases/ical_export_test.php@@ -0,0 +1,68 @@+<?php+/*+ Notes can now be multi-paragraph Markdown instead of a single short line,+ so the calendar export's DESCRIPTION line (built from price/category/+ payment method/payer/notes) can genuinely exceed RFC 5545's 75-octet+ line-length limit, where before it rarely did. icalFold() (includes/+ ical_helper.php) folds long lines so stricter calendar clients don't+ mis-parse them.++ Also asserts endpoints/subscription/exportcalendar.php no longer decodes+ notes as HTML entities before escaping them: notes stopped being stored+ HTML-escaped, so that decode is now wrong (it would mangle a literal "&"+ a user typed in a note).+*/++require_once WALLOS_ROOT . '/includes/ical_helper.php';++wallos_test('a short line is returned unfolded', function () {+ assert_same('SUMMARY:Netflix', icalFold('SUMMARY:Netflix'),+ 'nothing to fold, nothing changes');+});++wallos_test('a long line is folded at 75 octets, with a leading space on continuations', function () {+ $line = 'DESCRIPTION:' . str_repeat('a', 100);+ $folded = icalFold($line);+ $parts = explode("\r\n", $folded);++ assert_true(count($parts) > 1, 'the line was actually split');+ foreach ($parts as $i => $part) {+ assert_true(strlen($part) <= 76, "part $i is within the fold budget (75 content + 1 leading space)");+ if ($i > 0) {+ assert_same(' ', $part[0], "continuation part $i starts with the RFC 5545 single leading space");+ }+ }+});++wallos_test('folding a line and stripping the fold markers recovers the original bytes', function () {+ $line = 'DESCRIPTION:Price: 28.00 EUR\\nNotes: ' . str_repeat('Família ', 20);+ $folded = icalFold($line);+ $unfolded = str_replace("\r\n ", '', $folded);++ assert_same($line, $unfolded, 'folding is lossless');+});++wallos_test('folding never splits a multi-byte UTF-8 character across lines', function () {+ // Every character here is a 2-byte UTF-8 sequence, chosen so a naive+ // byte-count split would land mid-character somewhere in 200 bytes.+ $line = 'DESCRIPTION:' . str_repeat('é', 100);+ $folded = icalFold($line);++ foreach (explode("\r\n", $folded) as $part) {+ $part = ltrim($part, ' ');+ assert_true(json_encode($part) !== false, 'each folded chunk is still valid UTF-8 on its own (json_encode rejects a truncated multi-byte sequence)');+ }+});++wallos_test('the two ICS export code paths no longer HTML-decode notes before escaping them', function () {+ foreach (['endpoints/subscription/exportcalendar.php', 'api/subscriptions/get_ical_feed.php'] as $file) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $file);++ assert_not_contains("html_entity_decode(\$subscription['notes']", $source,+ $file . ': notes are no longer stored HTML-escaped, so decoding them here would corrupt a literal & or \' a user typed');+ assert_contains("icalEscape(\$subscription['notes'])", $source,+ $file . ': notes still go through icalEscape() directly');+ assert_contains("icalFold('DESCRIPTION:' . \$description)", $source,+ $file . ': the DESCRIPTION line is folded to the RFC 5545 limit');+ }+});diff --git a/tests/cases/notes_markdown_test.php b/tests/cases/notes_markdown_test.phpnew file mode 100644index 0000000..7349f33--- /dev/null+++ b/tests/cases/notes_markdown_test.php@@ -0,0 +1,101 @@+<?php+/*+ Subscription notes are Markdown source, rendered through+ render_notes_markdown() (includes/markdown.php) in Parsedown safe mode.+ Nothing typed by a user is ever trusted as HTML: literal markup is escaped+ as text, and link/image URLs are filtered against a scheme allowlist. This+ matters because subscriptions are visible to other household members, so a+ malicious note is a stored-XSS path, not just a theoretical one.++ These tests assert the real render function and the real migration, not+ copies of their logic.+*/++require_once WALLOS_ROOT . '/includes/markdown.php';+require_once WALLOS_ROOT . '/includes/inputvalidation.php';+require_once WALLOS_ROOT . '/includes/webhook_helper.php';++wallos_test('markdown syntax renders to the expected safe HTML', function () {+ assert_contains('<strong>bold</strong>', render_notes_markdown('**bold**'),+ 'bold syntax renders as <strong>');+ assert_contains('<em>italic</em>', render_notes_markdown('_italic_'),+ 'italic syntax renders as <em>');+ assert_contains('<li>one</li>', render_notes_markdown("- one\n- two"),+ 'a dash list renders as <li> items');+ assert_contains('<a href="https://example.com">link</a>', render_notes_markdown('[link](https://example.com)'),+ 'a markdown link renders with its href');+});++wallos_test('a literal newline is preserved as a line break', function () {+ assert_contains('one<br', render_notes_markdown("one\ntwo"),+ 'breaks-enabled mode turns a single newline into a <br>, giving real multi-line notes');+});++wallos_test('raw HTML typed as "markdown" is escaped, never rendered as markup', function () {+ $html = render_notes_markdown('<script>alert(1)</script>');+ assert_not_contains('<script>', $html, 'a literal <script> tag is not passed through');+ assert_contains('<script>', $html, 'it is escaped to text instead');++ $imgHtml = render_notes_markdown('<img src=x onerror=alert(1)>');+ assert_not_contains('<img', $imgHtml, 'no live <img> element is emitted');+ assert_contains('<img', $imgHtml, 'the tag is escaped to inert text instead, onerror included');+});++wallos_test('a javascript: link does not produce a javascript: href', function () {+ $html = render_notes_markdown('[click me](javascript:alert(1))');+ assert_not_contains('javascript:', $html, 'the scheme is not in the safe-mode allowlist, so the href is dropped');+});++wallos_test('validate_markdown() does not HTML-escape, unlike validate()', function () {+ assert_same('AT&T "great" deal', validate_markdown(' AT&T "great" deal '),+ 'only trimmed, not escaped: escaping now happens at render time');+ assert_contains('&', validate(' AT&T '),+ 'validate() (used for other fields) still escapes, for contrast');+});++wallos_test('the notes migration decodes existing escaped notes, and is safe to run twice', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ // What validate() (the pre-Markdown behaviour) would have stored for:+ // AT&T "great" deal's+ $escaped = 'AT&T "great" deal's';++ $stmt = $db->prepare("INSERT INTO subscriptions (user_id, name, price, currency_id, next_payment, cycle, frequency, inactive, notes)+ VALUES (1, 'Netflix', 9.99, :currencyId, date('now', '+5 days'), 3, 1, 0, :notes)");+ $stmt->bindValue(':currencyId', wallos_test_currency_id(1, 0), SQLITE3_INTEGER);+ $stmt->bindValue(':notes', $escaped, SQLITE3_TEXT);+ $stmt->execute();++ require WALLOS_ROOT . '/migrations/000058.php';++ $decoded = $db->querySingle("SELECT notes FROM subscriptions WHERE user_id = 1");+ assert_same("AT&T \"great\" deal's", $decoded, 'the stored notes are decoded back to plain text');++ require WALLOS_ROOT . '/migrations/000058.php';++ $decodedAgain = $db->querySingle("SELECT notes FROM subscriptions WHERE user_id = 1");+ assert_same("AT&T \"great\" deal's", $decodedAgain, 'running it again does not double-decode');++ $db->close();+});++wallos_test('webhookJsonEscape() keeps a multi-line note from breaking the payload JSON', function () {+ $note = "Family Plan \"shared\"\nCancelled\\pending\n\n- Alice\n- Bob";+ $escaped = webhookJsonEscape($note);++ $payload = '{"notes": "' . $escaped . '"}';+ $decoded = json_decode($payload, true);++ assert_true($decoded !== null, 'the templated payload is valid JSON');+ assert_same($note, $decoded['notes'] ?? null, 'and decodes back to the exact original note');+});++wallos_test('both notification crons use the shared webhookJsonEscape() helper for notes', function () {+ foreach (['endpoints/cronjobs/sendnotifications.php', 'endpoints/cronjobs/sendcancellationnotifications.php'] as $file) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $file);++ assert_contains('webhookJsonEscape($subscription[\'notes\'])', $source,+ $file . ' escapes notes before templating them into the webhook payload');+ }+});