Documents in Markdown: a document can be written in Markdown with Write and Preview or in the rich text editor and switched either way, pictures pasted or dropped into the Markdown are kept as files, New Document starts in the way last used, Import Markdown Files beside Upload makes a document from each .md file, a Markdown button beside PDF downloads a document as a .md file, and Markdown pasted into a document's rich text editor goes in as formatting; versions, restore, copy and the API carry the Markdown, and the API's document create and update no longer escape values twice; database 4.2.3 adds documents.document_markdown and document_versions.document_version_markdown, and league/commonmark 2.10 and league/html-to-markdown 5.2 are added to libs/vendor through composer; 26.12.3 changelog entries

This commit is contained in:
johnnyq
2026-11-29 00:48:15 -05:00
parent a84c3eca79
commit 8b4fa5a1a0
484 changed files with 43707 additions and 63 deletions

289
functions/markdown.php Normal file
View File

@@ -0,0 +1,289 @@
<?php
/*
* ITFlow - documents written in Markdown (database 4.2.3, documents.document_markdown).
*
* A document is written in the rich text editor or in Markdown, and can be switched either way.
* A Markdown document keeps what was written in document_markdown, and document_content is the
* HTML made from it each time it is saved - so every page that shows a document (the document,
* its quick look, the portal, shared links, the PDF, search) shows it as it always has, and only
* the places that write one need to know which it is.
*
* Markdown is read as GitHub writes it (league/commonmark): tables, task lists, struck text, links
* typed as they are, and HTML where Markdown has no way to say something - made safe by the same
* HTMLPurifier setup as every other document. HTML goes to Markdown with league/html-to-markdown,
* for switching a document over, its Markdown download and the Markdown pasted into the rich text
* editor (js/document_markdown.js).
*/
/** Whether the database has Markdown documents yet (4.2.3). */
function documentMarkdownReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.2.3', '>=');
}
return $ready;
}
/** The documents column to SELECT for what a Markdown document says - NULL before 4.2.3. */
function documentMarkdownSql($column = 'document_markdown') {
return documentMarkdownReady() ? $column : "NULL AS $column";
}
function markdownLibraries() {
require_once dirname(__DIR__) . '/libs/vendor/autoload.php';
}
/** What the Markdown says, as HTML - safe to store and to show. */
function markdownToHtml($markdown) {
static $converter = null;
$markdown = str_replace(["\r\n", "\r"], "\n", (string) $markdown);
if (trim($markdown) === '') {
return '';
}
if ($converter === null) {
markdownLibraries();
$converter = new \League\CommonMark\GithubFlavoredMarkdownConverter([
'html_input' => 'allow', // made safe by documentHtmlPurify() below
'allow_unsafe_links' => false,
'max_nesting_level' => 50,
'renderer' => ['soft_break' => "\n"],
]);
}
$html = (string) $converter->convert($markdown);
// A task list's boxes - the purifier takes form fields out, so they are drawn as the ticked and empty box
$html = str_replace(['<input checked="" disabled="" type="checkbox">', '<input disabled="" type="checkbox">'],
['<span class="itflow-task is-done">&#9745;</span>', '<span class="itflow-task">&#9744;</span>'], $html);
// Its tables look like the app's
$html = str_replace('<table>', '<table class="table table-bordered table-sm w-auto">', $html);
return documentHtmlPurify('<div class="itflow-markdown">' . $html . '</div>');
}
/**
* HTML as Markdown - a rich text document switched over, or downloaded as Markdown. What Markdown
* has no way to say stays as HTML in it (colours, underlining, a table with merged cells, a
* picture with a size) and is kept when it is shown; $notes says whether there was any ('kept'),
* and whether alignment or indents were dropped ('dropped'), which Markdown has nothing for.
*/
function htmlToMarkdown($html, &$notes = null) {
static $converter = null;
$notes = ['kept' => false, 'dropped' => false];
$html = (string) $html;
if (trim(strip_tags($html, '<img><table><hr>')) === '') {
return '';
}
if ($converter === null) {
markdownLibraries();
$converter = new \League\HTMLToMarkdown\HtmlConverter([
'header_style' => 'atx',
'strip_tags' => false,
'remove_nodes' => 'script style',
'italic_style' => '_',
'bold_style' => '**',
'list_item_style' => '-',
'use_autolinks' => true,
'suppress_errors' => true,
]);
$converter->getEnvironment()->addConverter(new \League\HTMLToMarkdown\Converter\TableConverter());
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?><div id="itflow-md-root">' . $html . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$root = $dom->getElementById('itflow-md-root') ?: $dom->documentElement;
// A task list's boxes, as drawn on the document page, back to [x] and [ ]
foreach (iterator_to_array($xpath->query('.//span[contains(concat(" ", normalize-space(@class), " "), " itflow-task ")]', $root)) as $box) {
$box->parentNode->replaceChild($dom->createTextNode(strpos(' ' . $box->getAttribute('class') . ' ', ' is-done ') !== false ? '[x]' : '[ ]'), $box);
}
// The wrapper a Markdown document's HTML comes in (markdownToHtml()) goes - its contents stay
foreach (iterator_to_array($xpath->query('.//div[contains(concat(" ", normalize-space(@class), " "), " itflow-markdown ")]', $root)) as $wrapper) {
while ($wrapper->firstChild) {
$wrapper->parentNode->insertBefore($wrapper->firstChild, $wrapper);
}
$wrapper->parentNode->removeChild($wrapper);
}
// An empty paragraph is only spacing
foreach (iterator_to_array($xpath->query('.//p', $root)) as $p) {
if (trim(str_replace("\xC2\xA0", ' ', $p->textContent)) === '' && !$xpath->query('.//img', $p)->length) {
$p->parentNode->removeChild($p);
}
}
// A code sample's language is on its <pre> in the editor, on its <code> in Markdown - and the
// line break that ends it would be an empty line at the end of the fence
foreach (iterator_to_array($xpath->query('.//pre', $root)) as $pre) {
$code = $xpath->query('./code', $pre)->item(0);
if ($code && !preg_match('/\blanguage-/', $code->getAttribute('class')) && preg_match('/\blanguage-([\w+-]+)/', $pre->getAttribute('class'), $m)) {
$code->setAttribute('class', 'language-' . $m[1]);
}
$last = ($code ?: $pre)->lastChild;
if ($last && $last->nodeType === XML_TEXT_NODE) {
$last->nodeValue = rtrim($last->nodeValue, "\n");
}
}
// Alignment and indents have nowhere to go
foreach ($xpath->query('.//*[@style]', $root) as $styled) {
if (preg_match('/(text-align|padding-left|margin-left)\s*:/i', $styled->getAttribute('style')) && !in_array(strtolower($styled->nodeName), ['span', 'img', 'table', 'td', 'th'], true)) {
$notes['dropped'] = true;
break;
}
}
// Kept as HTML: a table Markdown can't hold, and a picture with a size
$kept = [];
$keep = function (DOMNode $node, $block) use ($dom, &$kept) {
$token = 'itflowkeep' . count($kept) . 'x';
$kept[$token] = preg_replace("/\n\s*\n/", "\n", $dom->saveHTML($node));
$holder = $block ? $dom->createElement('p', $token) : $dom->createTextNode($token);
$node->parentNode->replaceChild($holder, $node);
};
foreach (iterator_to_array($xpath->query('.//table', $root)) as $table) {
if (!$table->parentNode || $xpath->query('ancestor::table', $table)->length) {
continue;
}
$simple = !$xpath->query('.//table | .//*[@colspan > 1] | .//*[@rowspan > 1]', $table)->length;
foreach ($xpath->query('.//td | .//th', $table) as $cell) {
$blocks = $xpath->query('./ul | ./ol | ./pre | ./blockquote | ./h1 | ./h2 | ./h3 | ./h4 | ./h5 | ./h6 | ./div | ./p', $cell);
if ($blocks->length > 1 || ($blocks->length === 1 && strtolower($blocks->item(0)->nodeName) !== 'p')) {
$simple = false;
}
}
if (!$simple) {
$keep($table, true);
}
}
foreach (iterator_to_array($xpath->query('.//img[@width or @height or @style]', $root)) as $img) {
$keep($img, false);
}
$inner = '';
foreach ($root->childNodes as $child) {
$inner .= $dom->saveHTML($child);
}
$markdown = $converter->convert($inner);
// A single space left at the end of a line is nothing - two are a line break, and stay
$markdown = preg_replace('/(\S) $/m', '$1', $markdown);
// Struck text is Markdown too
$markdown = preg_replace('#<(s|del|strike)>([^\n<]*)</\1>#i', '~~$2~~', $markdown);
// Task boxes went in as text, escaped
$markdown = preg_replace('/^(\s*[-*+]\s+)\\\\\[([ x])\\\\\]/m', '$1[$2]', $markdown);
foreach ($kept as $token => $original) {
$markdown = str_replace($token, $original, $markdown);
$notes['kept'] = true;
}
// Anything else Markdown had no way to say
if (!$notes['kept']) {
$without_code = preg_replace('/^```.*?^```|`[^`\n]*`/ms', '', $markdown);
$notes['kept'] = (bool) preg_match('/<[a-z][a-z0-9]*[\s>\/]/i', $without_code);
}
return trim($markdown) . "\n";
}
/**
* Pictures pasted into a Markdown document arrive as data - each is saved under
* uploads/documents/<id>/, as a picture pasted into the rich text editor is, and the
* Markdown points at the file instead.
*/
function markdownSaveImages($markdown, $document_id) {
$document_id = intval($document_id);
return preg_replace_callback('#data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\r\n]+)#i', function ($m) use ($document_id) {
$binary = base64_decode(preg_replace('/\s+/', '', $m[2]), true);
if ($binary === false || $binary === '' || @getimagesizefromstring($binary) === false) {
return $m[0];
}
$ext = strtolower($m[1]) === 'jpeg' ? 'jpg' : strtolower($m[1]);
$dir = dirname(__DIR__) . "/uploads/documents/$document_id";
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
return $m[0];
}
$filename = 'img_' . bin2hex(random_bytes(16)) . ".$ext";
if (file_put_contents("$dir/$filename", $binary) === false) {
return $m[0];
}
return "/uploads/documents/$document_id/$filename";
}, (string) $markdown);
}
/**
* A .md file read in: [name, Markdown]. Its name is the title in its front matter, or the heading
* it starts with (taken off the top, as the document's name is shown above it), or $fallback. The
* front matter itself - the block of settings some editors put between --- lines - is left out.
*/
function markdownImportSplit($text, $fallback) {
$text = str_replace(["\r\n", "\r"], "\n", preg_replace('/^\xEF\xBB\xBF/', '', (string) $text));
$name = '';
if (preg_match('/\A---\n(.*?)\n(---|\.\.\.)\n/s', $text, $m)) {
if (preg_match('/^title:\s*(["\']?)(.+?)\1\s*$/m', $m[1], $t)) {
$name = trim($t[2]);
}
$text = substr($text, strlen($m[0]));
}
if (preg_match('/\A\s*#[ \t]+(.+?)[ \t#]*\n/', $text . "\n", $h)) {
if ($name === '' || $name === trim($h[1])) {
$name = trim($h[1]);
$text = substr($text . "\n", strlen($h[0]));
}
}
$name = trim(preg_replace('/\s+/u', ' ', strip_tags($name)));
if ($name === '') {
$name = trim((string) $fallback);
}
return [mb_substr($name !== '' ? $name : 'Imported document', 0, 200), trim($text, "\n") . "\n"];
}
/**
* A document as a .md file: its name as the heading on top, then what it says - in Markdown as
* written, or the rich text made Markdown - with this ITFlow's own links and pictures made full
* addresses, so they still lead somewhere from the file.
*/
function documentMarkdownFile($name, $content, $markdown) {
global $config_base_url;
$body = $markdown !== null ? str_replace(["\r\n", "\r"], "\n", (string) $markdown) : htmlToMarkdown($content);
$host = preg_replace('#^https?://#i', '', rtrim(trim((string) $config_base_url), '/'));
if ($host !== '') {
$body = preg_replace('#(\]\(|<img [^>]*src="|<a [^>]*href=")/(?!/)#i', '$1https://' . $host . '/', $body);
}
return '# ' . trim(preg_replace('/\s+/u', ' ', (string) $name)) . "\n\n" . trim($body, "\n") . "\n";
}
/**
* What a document's form posted, ready to store: [HTML, Markdown] - the Markdown null for a
* document written in the rich text editor. Pictures pasted into either become files of the
* document's, so it needs its id first.
*/
function documentPostedContent($document_id) {
if (documentMarkdownReady() && ($_POST['format'] ?? '') === 'markdown') {
$markdown = markdownSaveImages(str_replace(["\r\n", "\r"], "\n", (string) ($_POST['markdown'] ?? '')), $document_id);
return [markdownToHtml($markdown), $markdown];
}
$html = saveBase64Images((string) ($_POST['content'] ?? ''), dirname(__DIR__) . "/uploads/documents/", "uploads/documents/", intval($document_id));
return [$html, null];
}
/** ", document_markdown = ..." for an UPDATE or INSERT of documents - nothing before 4.2.3. */
function documentMarkdownSet($markdown, $column = 'document_markdown') {
global $mysqli;
if (!documentMarkdownReady()) {
return '';
}
return ", $column = " . ($markdown === null ? 'NULL' : "'" . mysqli_real_escape_string($mysqli, (string) $markdown) . "'");
}