Made sure ids in toc are unique
authorMarcel Werk <burntime@woltlab.com>
Sun, 28 Mar 2021 10:48:19 +0000 (12:48 +0200)
committerMarcel Werk <burntime@woltlab.com>
Sun, 28 Mar 2021 10:48:19 +0000 (12:48 +0200)
wcfsetup/install/files/lib/system/html/toc/HtmlToc.class.php

index 436b1c19457b3a4c7ddb431c0986d6424ae43d1e..5d21c4ac4beff5085708aca51b4fd9b0ef7eff7d 100644 (file)
@@ -23,6 +23,7 @@ class HtmlToc {
                $titleRegex = new Regex('[^\p{L}\p{N}]+', Regex::UTF_8);
                
                // fetch all headings in their order of appearance
+               $usedIDs = [];
                /** @var HtmlTocItem[] $headings */
                $headings = [];
                /** @var \DOMElement $hElement */
@@ -38,7 +39,16 @@ class HtmlToc {
                        // trim to 80 characters
                        $id = rtrim(mb_substr($id, 0, 80), '-');
                        $id = mb_strtolower($id);
-                       
+                       if (isset($usedIDs[$id])) {
+                               $i = 2;
+                               do {
+                                       $newID = $id . '--' . ($i++);
+                               }
+                               while (isset($usedIDs[$newID]));
+                               $id = $newID;
+                       }
+                       $usedIDs[$id] = $id;
+
                        // Using the 'normalized' title allows for human-readable anchors that will remain
                        // valid even when new headings are being added or existing ones are removed. This
                        // also covers the relocation of a heading to a new position.