' . $html . '
');
}
/**
* 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, '
')) === '') {
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('' . $html . '
', 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 in the editor, on its 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//, 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('#(\]\(|
]*src="|]*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) . "'");
}