/), and the uploaded copy is removed, with * any folder the upload made that only held pictures. Pictures uploaded with no .md pointing to * them stay files. * * Make it a document, on an uploaded .md in Files (markdownFileMakeDocument()), does the same for * one already there: its pictures are looked for in the client's Files, copied in and left where * they are. * * Notion's exports add an ID to each page's name and folder ("Network Setup 8f3a...") - it is * taken off, and folders are matched with or without it. */ /** The extensions of Markdown files - lower case. */ function markdownUploadExtensions() { return ['md', 'markdown']; } /** The extensions of the pictures a document can have. */ function markdownPictureExtensions() { return ['png', 'jpg', 'jpeg', 'gif', 'webp']; } /** A name without the ID Notion's exports add to it: "Network Setup 8f3a9c...e1" -> "Network Setup". */ function markdownNotionName($name) { return preg_replace('/\s+[0-9a-f]{32}$/i', '', trim((string) $name)); } /** * Upload's .md files and pictures - file IDs of one upload, all of the client's - made into * documents. $folders_made are the folders the upload made, removed when it leaves them empty. * Returns what happened: 'documents' [[id, name]], 'missing' [document name => [picture, ...]], * 'kept' [[file name, why]] for .md files left as files, 'pictures' how many uploaded pictures * went into documents, and 'folders_removed'. */ function markdownUploadConvert($client_id, array $file_ids, array $folders_made = []) { global $mysqli; $client_id = intval($client_id); $result = ['documents' => [], 'missing' => [], 'kept' => [], 'pictures' => 0, 'folders_removed' => 0]; $file_ids = array_values(array_unique(array_filter(array_map('intval', $file_ids)))); if (!$file_ids || !documentMarkdownReady()) { return $result; } $markdown_files = []; $pictures = []; $sql = mysqli_query($mysqli, "SELECT file_id, file_name, file_description, file_reference_name, file_ext, file_size, file_folder_id, file_client_id FROM files WHERE file_client_id = $client_id AND file_archived_at IS NULL AND file_id IN (" . implode(',', $file_ids) . ") ORDER BY file_id"); while ($row = mysqli_fetch_assoc($sql)) { $ext = strtolower((string) $row['file_ext']); if (in_array($ext, markdownUploadExtensions(), true)) { $markdown_files[] = $row; } elseif (in_array($ext, markdownPictureExtensions(), true)) { $pictures[intval($row['file_id'])] = $row; } } if (!$markdown_files) { return $result; } $context = markdownPictureContext($client_id, $pictures); foreach ($markdown_files as $row) { $made = markdownFileToDocument($row, $context); if ($made['document_id']) { $result['documents'][] = [$made['document_id'], $made['name']]; if ($made['missing']) { $result['missing'][$made['name']] = $made['missing']; } markdownUploadRemoveFile($row); } else { $result['kept'][] = [$row['file_name'], $made['why']]; } } // The pictures that went into documents were uploaded for them - the copies in Files go foreach (array_keys($context['used']) as $picture_id) { if (isset($pictures[$picture_id])) { markdownUploadRemoveFile($pictures[$picture_id]); $result['pictures']++; } } // And a folder the upload made only for pictures goes with them - deepest first $result['folders_removed'] = markdownUploadRemoveEmptyFolders($client_id, $folders_made); return $result; } /** * Make it a document (Files, on an uploaded .md): the file becomes a document in its folder, with * the pictures it points to that are in the client's Files copied in, and the file goes. Returns * ['document_id', 'name', 'missing' [picture, ...], 'why'] - document_id 0, with why, when it * couldn't be made one. The caller has checked access to the file's client. */ function markdownFileMakeDocument($file_id) { global $mysqli; $file_id = intval($file_id); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_id, file_name, file_description, file_reference_name, file_ext, file_size, file_folder_id, file_client_id FROM files WHERE file_id = $file_id AND file_archived_at IS NULL LIMIT 1")); if (!$row) { return ['document_id' => 0, 'name' => '', 'missing' => [], 'why' => 'it is no longer there']; } if (!in_array(strtolower((string) $row['file_ext']), markdownUploadExtensions(), true)) { return ['document_id' => 0, 'name' => '', 'missing' => [], 'why' => 'it is not a .md file']; } if (!documentMarkdownReady()) { return ['document_id' => 0, 'name' => '', 'missing' => [], 'why' => 'Markdown documents need the database update first']; } $context = markdownPictureContext(intval($row['file_client_id']), null); $made = markdownFileToDocument($row, $context); if ($made['document_id']) { markdownUploadRemoveFile($row); } return $made; } /** * Where an .md's pictures are looked for: $pictures, the ones uploaded with it (file_id => row), * or null for anywhere in the client's Files. 'used' collects the uploaded ones that went in. */ function markdownPictureContext($client_id, $pictures) { $context = ['client_id' => intval($client_id), 'tree' => folderTree($client_id), 'pictures' => $pictures, 'used' => [], 'by_place' => [], 'by_name' => []]; foreach ((array) $pictures as $id => $row) { $name = mb_strtolower($row['file_name']); $context['by_place'][intval($row['file_folder_id']) . '/' . $name][] = $id; $context['by_name'][$name][] = $id; } return $context; } /** * One uploaded .md made a document, with its pictures. Returns ['document_id', 'name', 'missing' * [picture, ...], 'why'] - document_id 0, with why, when it can't be read as text. The file itself * is left for the caller. */ function markdownFileToDocument(array $row, array &$context) { global $mysqli, $session_user_id, $session_name; $none = function ($why) { return ['document_id' => 0, 'name' => '', 'missing' => [], 'why' => $why]; }; $client_id = intval($row['file_client_id']); $path = dirname(__DIR__) . "/uploads/clients/$client_id/" . basename((string) $row['file_reference_name']); if (!is_file($path)) { return $none('the file is missing from the server'); } if (filesize($path) > 5 * 1024 * 1024) { return $none('over 5 MB'); } $text = csvTextToUtf8((string) file_get_contents($path)); if (trim($text) !== '' && preg_match_all('/[\x00-\x08\x0E-\x1F]/', $text) > strlen($text) / 100) { return $none('not text'); } $fallback = markdownNotionName(preg_replace('/\.(md|markdown)$/i', '', (string) $row['file_name'])); [$name, $markdown] = markdownImportSplit($text, $fallback); $folder_id = intval($row['file_folder_id']); $folder_id = isset($context['tree'][$folder_id]) ? $folder_id : 0; $name_sql = escapeSql($name); $description_sql = escapeSql(mb_substr((string) $row['file_description'], 0, 250)); mysqli_query($mysqli, "INSERT INTO documents SET document_name = '$name_sql', document_description = '$description_sql', document_content = '', document_content_raw = '', document_client_visible = 0, document_folder_id = $folder_id, document_created_by = " . intval($session_user_id) . ", document_client_id = $client_id"); $document_id = mysqli_insert_id($mysqli); // Pictures in the file itself, then the ones it points to $markdown = markdownSaveImages($markdown, $document_id); $copied = []; $brought = []; [$markdown, $missing] = markdownRewritePictures($markdown, function ($target, $by_name_only) use (&$context, $folder_id, $document_id, &$copied, &$brought) { $picture = markdownFindPicture($context, $folder_id, $target, $by_name_only); if (!$picture) { return ''; } $id = intval($picture['file_id']); if (!isset($copied[$id])) { $copied[$id] = markdownCopyPicture($picture, $document_id); if ($copied[$id] !== '') { $brought[] = $picture['file_name']; if ($context['pictures'] !== null) { $context['used'][$id] = true; } } } return $copied[$id]; }); $html = markdownToHtml($markdown); mysqli_query($mysqli, "UPDATE documents SET document_content = '" . mysqli_real_escape_string($mysqli, $html) . "', document_content_raw = '" . escapeSql(documentContentRaw($name, $html)) . "'" . documentMarkdownSet($markdown) . " WHERE document_id = $document_id"); // What the file was linked to - an asset it was uploaded from, say - the document is now foreach (LINK_RELATIONS as $pair => $relation) { $types = explode('|', $pair); if (!in_array('file', $types, true)) { continue; } $other = $types[0] === 'file' ? $types[1] : $types[0]; if ($other === 'document' || !linkRelation('document', $other)) { continue; } $other_id_column = LINK_ENTITIES[$other]['id']; $ids = array_column(mysqli_fetch_all(mysqli_query($mysqli, "SELECT $other_id_column FROM {$relation['table']} WHERE file_id = " . intval($row['file_id']))), 0); if ($ids) { linkAdd('document', $document_id, $other, $ids); } } logAudit("Document", "Create", "$session_name made document $name_sql from Markdown file " . escapeSql($row['file_name']) . ($brought ? ', with its pictures ' . escapeSql(implode(', ', array_slice($brought, 0, 20))) : ''), $client_id, $document_id); return ['document_id' => $document_id, 'name' => $name, 'missing' => array_values(array_unique($missing)), 'why' => '']; } /** * The pictures Markdown points to, each handed to $find(target, by_name_only) - an image, * ![alt](target), an , a reference "[id]: target" to a picture, or Obsidian's * ![[target]] (found by its name only, as Obsidian does). $find gives the address it is now, or '' * when there is none. Web addresses and this ITFlow's own (/uploads/...) are left alone, and so is * anything in a code block; a path on the computer it was written on (C:\Pictures\..., /Users/..., * file://) is looked for by its name. Returns [Markdown, [the pictures not found]]. */ function markdownRewritePictures($markdown, callable $find) { $missing = []; $local = function ($target) { $target = trim((string) $target); if ($target === '' || $target[0] === '#' || stripos($target, '/uploads/') === 0) { return false; } // A web address or data - but a Windows path (C:\Pictures) or file:// is the computer's if (preg_match('#^([a-z]:[\\\\/]|file:)#i', $target)) { return true; } return !preg_match('#^([a-z][a-z0-9+.\-]*:|//)#i', $target); }; $picture = function ($target) { $path = preg_replace('/[?#].*$/', '', (string) $target); return in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), array_merge(markdownPictureExtensions(), ['svg', 'bmp', 'tif', 'tiff', 'heic']), true); }; $swap = function ($target, $by_name_only = false) use ($find, &$missing) { $address = $find($target, $by_name_only); if ($address === '') { $missing[] = basename(str_replace('\\', '/', rawurldecode(preg_replace('/[?#].*$/', '', $target)))); } return $address; }; // Code blocks are left as they are - split them out, change the rest, put them back $parts = preg_split('/(^(?:```|~~~)[^\n]*\n.*?^(?:```|~~~)[ \t]*$)/ms', (string) $markdown, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($parts as $i => $part) { if ($i % 2) { continue; } // ![alt](target "title") - the target may be or have (one level of) brackets in it $part = preg_replace_callback('/!\[((?:[^\[\]\n]|\[[^\]\n]*\])*)\]\(\s*(<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+)(\s+(?:"[^"\n]*"|\'[^\'\n]*\'|\([^)\n]*\)))?\s*\)/u', function ($m) use ($local, $swap) { $target = $m[2][0] === '<' ? substr($m[2], 1, -1) : $m[2]; if (!$local($target)) { return $m[0]; } $address = $swap($target); return $address === '' ? $m[0] : '![' . $m[1] . '](' . $address . ($m[3] ?? '') . ')'; }, $part); // Obsidian's ![[picture.png|300]] - a picture by its name; a note embedded this way is left alone $part = preg_replace_callback('/!\[\[([^\]\|#\n]+)(#[^\]\|\n]*)?(?:\|([^\]\n]*))?\]\]/u', function ($m) use ($picture, $swap) { $target = trim($m[1]); if (!$picture($target)) { return $m[0]; } $address = $swap($target, true); $alt = isset($m[3]) && trim($m[3]) !== '' && !preg_match('/^\d+(x\d+)?$/', trim($m[3])) ? trim($m[3]) : pathinfo($target, PATHINFO_FILENAME); return $address === '' ? $m[0] : '![' . str_replace(['[', ']'], '', $alt) . '](' . $address . ')'; }, $part); // $part = preg_replace_callback('/(]*?\bsrc\s*=\s*)("([^"]*)"|\'([^\']*)\'|([^\s>"\']+))/i', function ($m) use ($local, $swap) { $target = html_entity_decode($m[3] !== '' ? $m[3] : (($m[4] ?? '') !== '' ? $m[4] : ($m[5] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8'); if (!$local($target)) { return $m[0]; } $address = $swap($target); return $address === '' ? $m[0] : $m[1] . '"' . $address . '"'; }, $part); // [id]: target - only a picture's, as the same is used for links to pages $part = preg_replace_callback('/^( {0,3}\[[^\]\n]+\]:[ \t]*)(<[^>\n]*>|\S+)/mu', function ($m) use ($local, $picture, $swap) { $target = $m[2][0] === '<' ? substr($m[2], 1, -1) : $m[2]; if (!$local($target) || !$picture($target)) { return $m[0]; } $address = $swap($target); return $address === '' ? $m[0] : $m[1] . $address; }, $part); $parts[$i] = $part; } return [implode('', $parts), $missing]; } /** * The picture an .md in $folder_id points to with $target: where its path leads from that folder * (made of the client's folders, Notion's IDs or not, letters' case or not), else - or straight * away, $by_name_only - the one picture of that name: among the pictures uploaded with it, or * with none, in its folder and the folders under it. A file row, or null. */ function markdownFindPicture(array $context, $folder_id, $target, $by_name_only = false) { $target = str_replace('\\', '/', preg_replace('/[?#].*$/', '', trim((string) $target))); $target = preg_replace('#^file:/*#i', '/', $target); $decoded = rawurldecode($target); // A path on someone's computer - /Users/..., C:/... - is only any use for its name $absolute = $decoded !== '' && ($decoded[0] === '/' || preg_match('#^[a-z]:/#i', $decoded)); $name = basename($decoded); if ($name === '' || !in_array(strtolower(pathinfo($name, PATHINFO_EXTENSION)), markdownPictureExtensions(), true)) { return null; } if (!$by_name_only && !$absolute) { foreach (array_unique([$decoded, $target]) as $path) { $place = markdownPathFolder($context['tree'], $folder_id, $path); if ($place !== null) { $found = markdownPictureIn($context, $place, basename($path)); if ($found) { return $found; } } } } // By its name alone - when there is only one of that name if ($context['pictures'] !== null) { $ids = $context['by_name'][mb_strtolower($name)] ?? []; return count($ids) === 1 ? $context['pictures'][$ids[0]] : null; } global $mysqli; $folders = implode(',', array_map('intval', folderSubtree($context['tree'], $folder_id))); $name_sql = escapeSql($name); $rows = mysqli_fetch_all(mysqli_query($mysqli, "SELECT file_id, file_name, file_reference_name, file_ext, file_size, file_folder_id, file_client_id FROM files WHERE file_client_id = {$context['client_id']} AND file_archived_at IS NULL AND file_folder_id IN ($folders) AND file_name = '$name_sql' LIMIT 2"), MYSQLI_ASSOC); return count($rows) === 1 ? $rows[0] : null; } /** The folder a relative path's file is in, from $folder_id: its folders by name, ".." up a level. Null when it leads nowhere. */ function markdownPathFolder(array $tree, $folder_id, $path) { $folder_id = intval($folder_id); $parts = explode('/', (string) $path); array_pop($parts); foreach ($parts as $part) { if ($part === '' || $part === '.') { continue; } if ($part === '..') { if ($folder_id === 0) { return null; } $folder_id = $tree[$folder_id]['parent_folder'] ?? 0; continue; } $next = null; foreach ([$part, mb_strtolower($part), mb_strtolower(markdownNotionName($part))] as $round => $want) { foreach ($tree[$folder_id]['children'] ?? [] as $child) { $have = $tree[$child]['folder_name']; $have = $round === 0 ? $have : ($round === 1 ? mb_strtolower($have) : mb_strtolower(markdownNotionName($have))); if ($have === $want) { $next = $child; break 2; } } } if ($next === null) { return null; } $folder_id = $next; } return $folder_id; } /** The picture called $name in folder $folder_id - one uploaded with the .md, or with none, any there. A file row, or null. */ function markdownPictureIn(array $context, $folder_id, $name) { global $mysqli; $folder_id = intval($folder_id); if ($context['pictures'] !== null) { $ids = $context['by_place']["$folder_id/" . mb_strtolower($name)] ?? []; return $ids ? $context['pictures'][$ids[0]] : null; } $name_sql = escapeSql($name); return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_id, file_name, file_reference_name, file_ext, file_size, file_folder_id, file_client_id FROM files WHERE file_client_id = {$context['client_id']} AND file_archived_at IS NULL AND file_folder_id = $folder_id AND file_name = '$name_sql' ORDER BY file_id DESC LIMIT 1")) ?: null; } /** A picture in Files copied in as the document's own - its address, or '' when it isn't a picture after all. */ function markdownCopyPicture(array $file, $document_id) { $document_id = intval($document_id); $source = dirname(__DIR__) . '/uploads/clients/' . intval($file['file_client_id']) . '/' . basename((string) $file['file_reference_name']); if (!is_file($source) || filesize($source) > 25 * 1024 * 1024) { return ''; } $binary = (string) file_get_contents($source); $info = @getimagesizefromstring($binary); $types = [IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp']; if ($info === false || !isset($types[$info[2]])) { return ''; } $dir = dirname(__DIR__) . "/uploads/documents/$document_id"; if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { return ''; } $filename = 'img_' . bin2hex(random_bytes(16)) . '.' . $types[$info[2]]; if (file_put_contents("$dir/$filename", $binary) === false) { return ''; } return "/uploads/documents/$document_id/$filename"; } /** An uploaded file that is now part of a document - gone from Files, with its links, quietly. */ function markdownUploadRemoveFile(array $row) { global $mysqli; fileRemoveFromDisk(intval($row['file_client_id']), $row['file_reference_name']); linkRemoveAll('file', intval($row['file_id'])); mysqli_query($mysqli, "DELETE FROM files WHERE file_id = " . intval($row['file_id'])); } /** The folders an upload made that are empty now - nothing in them, nothing under them - removed. Returns how many. */ function markdownUploadRemoveEmptyFolders($client_id, array $folder_ids) { global $mysqli, $session_name; $client_id = intval($client_id); $removed = 0; foreach (array_reverse(array_values(array_unique(array_map('intval', $folder_ids)))) as $folder_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT folder_name, (SELECT COUNT(*) FROM files WHERE file_folder_id = $folder_id) + (SELECT COUNT(*) FROM documents WHERE document_folder_id = $folder_id) + (SELECT COUNT(*) FROM folders f2 WHERE f2.parent_folder = $folder_id) AS things FROM folders WHERE folder_id = $folder_id AND folder_client_id = $client_id")); if ($row && intval($row['things']) === 0) { mysqli_query($mysqli, "DELETE FROM folders WHERE folder_id = $folder_id"); logAudit("Folder", "Delete", "$session_name's upload left folder " . escapeSql($row['folder_name']) . " empty - its pictures went into documents", $client_id); $removed++; } } return $removed; } /** * How an upload's Markdown went, for its message: [what was made, what to look at, tone]. Empty * strings when there was no Markdown. */ function markdownUploadSays(array $result) { $made = count($result['documents']); $said = ''; if ($made === 1) { $said = 'made document ' . escapeHtml($result['documents'][0][1]) . ' from Markdown'; } elseif ($made) { $said = "made $made documents from Markdown"; } $notes = []; if ($result['missing']) { $list = []; $count = 0; foreach ($result['missing'] as $document => $pictures) { $count += count($pictures); if (count($list) < 8) { $list[] = escapeHtml(implode(', ', array_slice($pictures, 0, 5))) . (count($pictures) > 5 ? ' and ' . (count($pictures) - 5) . ' more' : '') . ' in ' . escapeHtml($document) . ''; } } $notes[] = ($count === 1 ? 'a picture it uses wasn\'t' : "$count pictures they use weren't") . ' uploaded with ' . ($made === 1 ? 'it' : 'them') . ': ' . implode('; ', $list) . (count($result['missing']) > 8 ? '; and more' : '') . ' - add ' . ($count === 1 ? 'it' : 'them') . ' in the editor'; } if ($result['kept']) { $notes[] = implode(', ', array_map(function ($kept) { return '' . escapeHtml($kept[0]) . ' stayed a file (' . escapeHtml($kept[1]) . ')'; }, array_slice($result['kept'], 0, 10))); } return [$said, implode('. ', $notes), $notes ? 'warning' : 'success']; } /** * An uploaded .md file shown as its Markdown reads - safe HTML, its pictures that are in the * client's Files shown from there, the first megabyte of a bigger one. Checks access to the * file's client; '' for one that isn't a .md file. */ function fileMarkdownPreviewHtml($file_id) { global $mysqli, $client_id; $file_id = intval($file_id); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_client_id, file_reference_name, file_ext, file_folder_id FROM files WHERE file_id = $file_id LIMIT 1")); if (!$row || !in_array(strtolower((string) $row['file_ext']), markdownUploadExtensions(), true)) { return ''; } $client_id = intval($row['file_client_id']); enforceClientAccess(); $path = dirname(__DIR__) . "/uploads/clients/$client_id/" . basename((string) $row['file_reference_name']); if (!is_file($path)) { return ''; } $handle = fopen($path, 'rb'); $text = csvTextToUtf8((string) fread($handle, 1024 * 1024)); fclose($handle); $context = markdownPictureContext($client_id, null); $folder_id = isset($context['tree'][intval($row['file_folder_id'])]) ? intval($row['file_folder_id']) : 0; [$text] = markdownRewritePictures($text, function ($target, $by_name_only) use ($context, $folder_id) { $picture = markdownFindPicture($context, $folder_id, $target, $by_name_only); return $picture ? 'file.php?file_id=' . intval($picture['file_id']) . '&action=view' : ''; }); return markdownToHtml($text); }