protected function writeTOC($publishPages = false, $preservedDocument = null)
    {
        $page = $this->form->getRecord();
        $content = '<ul>';

        if ($page) {
            if ($page->Children()->Count() > 0) {
                foreach ($page->Children() as $child) {
                    $content .= '<li><a href="' . $child->Link() . '">' . $child->Title . '</a></li>';
                }
                $page->Content = $content . '</ul>';
            } else {
                $doc = new DOMDocument();
                $doc->loadHTML($page->Content);
                $body = $doc->getElementsByTagName('body')->item(0);
                $node = $body->firstChild;
                $h1 = $h2 = 1;
                while ($node) {
                    if ($node instanceof DOMElement && $node->tagName == 'h1') {
                        $content .= '<li><a href="#h1.' . $h1 . '">' .
                            trim(preg_replace('/\n|\r/', '', Convert::html2raw($node->textContent))) .
                            '</a></li>';
                        $node->setAttributeNode(new DOMAttr("id", "h1.".$h1));
                        $h1++;
                    } elseif ($node instanceof DOMElement && $node->tagName == 'h2') {
                        $content .= '<li class="menu-h2"><a href="#h2.' . $h2 . '">' .
                            trim(preg_replace('/\n|\r/', '', Convert::html2raw($node->textContent))) .
                            '</a></li>';
                        $node->setAttributeNode(new DOMAttr("id", "h2.".$h2));
                        $h2++;
                    }
                    $node = $node->nextSibling;
                }
                $page->Content = $content . '</ul>' . $doc->saveHTML();
            }

            // Add in the link to the original document, if provided.
            if ($preservedDocument) {
                $page->Content = '<a href="' .
                    $preservedDocument->Link() .
                    '" title="download original document">download original document (' .
                    $preservedDocument->getSize() .
                    ')</a>' .
                    $page->Content;
            }

            // Store the result
            $page->write();
            if ($publishPages) {
                $page->publishRecursive();
            }
        }
    }