@@ -120,6 +144,102 @@ ob_start();
var list = form.querySelector('[data-upload-list]');
var error = form.querySelector('[data-upload-error]');
var submit = form.querySelector('[data-upload-submit]');
+ var markdown = form.querySelector('[data-upload-markdown]'); // none until the database has Markdown documents
+ var keep = form.querySelector('[data-upload-markdown-keep]');
+ var zips = new Map(); // a zip picked -> what's in it: {state: reading, pages, none or error, ...}
+
+ function isMarkdown(name) {
+ return /\.(md|markdown)$/i.test(name);
+ }
+
+ function plural(count, one, many) {
+ return count + ' ' + (count === 1 ? one : many);
+ }
+
+ // What a zip holds - its Markdown pages, and the folder they'd go in
+ function zipLook(file) {
+ if (zips.has(file)) {
+ return;
+ }
+ if (!window.itflowZip || !window.itflowZip.canUnpack) {
+ zips.set(file, { state: 'error', why: 'this browser can\'t open zips' });
+ return;
+ }
+ zips.set(file, { state: 'reading' });
+ window.itflowZip.list(file).then(function (entries) {
+ // Leave out what computers keep beside files - __MACOSX, .DS_Store, hidden folders
+ entries = entries.filter(function (entry) {
+ return !/(^|\/)(__MACOSX\/|\.)/.test(entry.path) && !/(^|\/)(Thumbs\.db|desktop\.ini)$/i.test(entry.path);
+ });
+ var pages = entries.filter(function (entry) { return isMarkdown(entry.path); }).length;
+ var tops = {};
+ entries.forEach(function (entry) {
+ tops[entry.path.indexOf('/') > 0 ? entry.path.split('/')[0] : ''] = true;
+ });
+ var top = Object.keys(tops);
+ // All in one folder - that folder; otherwise a folder named after the zip
+ var prefix = top.length === 1 && top[0] !== '' ? '' : file.name.replace(/\.zip$/i, '') + '/';
+ zips.set(file, {
+ state: pages ? 'pages' : 'none',
+ pages: pages,
+ entries: entries,
+ prefix: prefix,
+ folder: (prefix ? prefix.slice(0, -1) : top[0]).replace(/\s+[0-9a-f]{32}$/i, ''),
+ bytes: entries.reduce(function (sum, entry) { return sum + entry.size; }, 0)
+ });
+ show();
+ }, function (problem) {
+ zips.set(file, { state: 'error', why: problem.message });
+ show();
+ });
+ }
+
+ // The zips that will be opened and sent up as folders
+ function zipsToOpen(files) {
+ if (picked || !markdown || keep.checked) {
+ return [];
+ }
+ return files.filter(function (file) {
+ return (zips.get(file) || {}).state === 'pages';
+ });
+ }
+
+ // What becomes a document - the panel, when there's Markdown
+ function showMarkdown(items, files) {
+ if (!markdown) {
+ return;
+ }
+ var list = markdown.querySelector('[data-upload-markdown-list]');
+ list.innerHTML = '';
+ function line(text, muted) {
+ var li = document.createElement('li');
+ li.className = 'text-break' + (muted ? ' text-body-secondary' : '');
+ li.textContent = text;
+ list.appendChild(li);
+ }
+ var pages = items.filter(function (item) { return isMarkdown(item.path || item.file.name); });
+ if (pages.length) {
+ line(plural(pages.length, '.md file', '.md files') + ' - ' + pages.slice(0, 3).map(function (item) { return item.file.name; }).join(', ') + (pages.length > 3 ? ' and more' : ''));
+ }
+ var zipped = 0;
+ (picked ? [] : files.filter(function (file) { return /\.zip$/i.test(file.name); })).forEach(function (file) {
+ zipLook(file);
+ var look = zips.get(file);
+ if (look.state === 'reading') {
+ line('Looking in ' + file.name + '...', true);
+ } else if (look.state === 'pages') {
+ zipped++;
+ line(file.name + ' - ' + plural(look.pages, 'Markdown page', 'Markdown pages') + (keep.checked ? ', uploaded as a zip' : ', into a folder ' + look.folder));
+ } else if (look.state === 'error') {
+ line(file.name + ' uploads as a zip - ' + look.why, true);
+ }
+ });
+ var any = pages.length > 0 || zipped > 0;
+ markdown.hidden = !list.children.length;
+ markdown.querySelector('[data-upload-markdown-title]').textContent = keep.checked ? 'Uploaded as they are:' : 'These become documents you can edit:';
+ markdown.querySelector('[data-upload-markdown-note]').hidden = keep.checked || !any;
+ keep.closest('.form-check').hidden = !any;
+ }
function size(bytes) {
var units = ['B', 'KB', 'MB', 'GB'], i = 0;
@@ -156,17 +276,57 @@ ob_start();
more.textContent = 'and ' + (items.length - 20) + ' more';
list.appendChild(more);
}
+ showMarkdown(items, files);
+ // A zip that's opened goes up as a folder, by what's in it
+ var opening = zipsToOpen(files);
+ var opened = opening.reduce(function (sum, file) { return sum + zips.get(file).entries.length - 1; }, files.length);
+ var openedBytes = opening.reduce(function (sum, file) { return sum + zips.get(file).bytes - file.size; }, total);
var problem = picked
? (files.length > FOLDER_MAX_FILES ? 'That is ' + files.length + ' files - upload a folder of up to ' + FOLDER_MAX_FILES + '.'
: total > FOLDER_MAX_BYTES ? 'That is ' + size(total) + ' - keep a folder under 2 GB.' : '')
+ : opening.length
+ ? (opened > FOLDER_MAX_FILES ? 'That is ' + opened + ' files once the zip is opened - upload up to ' + FOLDER_MAX_FILES + ' at a time.'
+ : openedBytes > FOLDER_MAX_BYTES ? 'That is ' + size(openedBytes) + ' once the zip is opened - keep it under 2 GB.' : '')
: files.length > MAX_FILES ? 'That is ' + files.length + ' files - upload up to ' + MAX_FILES + ' at a time, or choose a folder.'
: total > MAX_BYTES ? 'That is ' + size(total) + ' - keep each upload under 500 MB.' : '';
+ var reading = files.some(function (file) { return (zips.get(file) || {}).state === 'reading'; });
error.textContent = problem;
error.hidden = !problem;
- submit.disabled = !files.length || !!problem;
+ submit.disabled = !files.length || !!problem || reading;
drop.classList.toggle('has-files', files.length > 0);
}
+ if (keep) {
+ keep.addEventListener('change', show);
+ }
+
+ // The zips opened, one file at a time - the picked files, with what's in each zip in its place
+ function openZips(files, opening) {
+ var items = [];
+ var skipped = [];
+ var chain = Promise.resolve();
+ files.forEach(function (file) {
+ if (opening.indexOf(file) === -1) {
+ chain = chain.then(function () { items.push({ file: file, path: file.name }); });
+ return;
+ }
+ var look = zips.get(file);
+ look.entries.forEach(function (entry, index) {
+ chain = chain.then(function () {
+ submit.innerHTML = '
Opening ' + (index + 1) + ' of ' + look.entries.length + '...';
+ return window.itflowZip.unpack(file, entry).then(function (unpacked) {
+ items.push({ file: unpacked, path: look.prefix + entry.path });
+ }, function (problem) {
+ skipped.push(look.prefix + entry.path + ' (' + problem.message + ')');
+ });
+ });
+ });
+ });
+ return chain.then(function () {
+ return { items: items, skipped: skipped };
+ });
+ }
+
// A folder's files, with where each sits under it
function takeFolder(items) {
picked = items.filter(function (item) {
@@ -246,7 +406,7 @@ ob_start();
});
// A folder goes up twenty files at a time, then the page reloads with how it went
- function sendFolder() {
+ function sendFolder(skippedBefore) {
var parts = [], part = [], bytes = 0;
picked.forEach(function (item) {
if (part.length && (part.length >= PART_FILES || bytes + item.file.size > PART_BYTES)) {
@@ -260,7 +420,7 @@ ob_start();
if (part.length) {
parts.push(part);
}
- var done = { uploaded: 0, folders: 0, skipped: [] };
+ var done = { uploaded: 0, folders: 0, skipped: (skippedBefore || []).slice() };
var sent = 0;
submit.disabled = true;
(function next(index) {
@@ -268,12 +428,27 @@ ob_start();
var finish = new FormData();
finish.append('csrf_token', form.querySelector('[name="csrf_token"]').value);
finish.append('upload_folder_done', '1');
+ finish.append('upload_batch', form.querySelector('[name="upload_batch"]').value);
+ if (keep && keep.checked) {
+ finish.append('markdown_keep', '1');
+ }
finish.append('uploaded', done.uploaded);
finish.append('folders', done.folders);
done.skipped.forEach(function (name) { finish.append('skipped[]', name); });
- fetch(form.action, { method: 'POST', body: finish, credentials: 'same-origin' }).finally(function () {
- window.location.reload();
- });
+ submit.innerHTML = '
' + (markdown && !(keep && keep.checked) ? 'Making documents...' : 'Finishing...');
+ // One document made, and nothing else - it opens; otherwise the list reloads with how it went
+ fetch(form.action, { method: 'POST', body: finish, credentials: 'same-origin' })
+ .then(function (r) { return r.json(); })
+ .then(function (answer) {
+ if (answer && answer.go) {
+ window.location.href = answer.go;
+ } else {
+ window.location.reload();
+ }
+ })
+ .catch(function () {
+ window.location.reload();
+ });
return;
}
submit.innerHTML = '
Uploading ' + (sent + 1) + ' of ' + picked.length + '...';
@@ -312,6 +487,18 @@ ob_start();
sendFolder();
return;
}
+ // A zip of Markdown pages is opened here and goes up as the folder it holds
+ var files = Array.prototype.slice.call(input.files || []);
+ var opening = zipsToOpen(files);
+ if (opening.length) {
+ e.preventDefault();
+ submit.disabled = true;
+ openZips(files, opening).then(function (opened) {
+ picked = opened.items;
+ sendFolder(opened.skipped);
+ });
+ return;
+ }
// Disabled after the browser has read the submitter, so upload_files still posts
setTimeout(function () {
submit.disabled = true;
diff --git a/agent/post/document.php b/agent/post/document.php
index d340f70ff..e04d1dd67 100644
--- a/agent/post/document.php
+++ b/agent/post/document.php
@@ -478,81 +478,6 @@ if (isset($_GET['export_document_markdown'])) {
}
-/*
- * Markdown files made into documents (agent/modals/document/document_import_markdown.php) - one
- * each, written in Markdown, in the folder picked. Each is named by the title in its front
- * matter or the heading it starts with, else its file name (markdownImportSplit()).
- */
-if (isset($_POST['import_markdown_documents'])) {
-
- validateCSRFToken();
-
- enforceUserPermission('module_support', 2);
-
- $client_id = intval($_POST['client_id'] ?? 0);
- enforceClientAccess();
- if (!documentMarkdownReady() || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id"))) {
- flashAlert('Markdown files can\'t be imported here yet.', 'error');
- redirect();
- }
- $folder_id = folderOwnedId($_POST['folder'] ?? 0, $client_id);
- $client_visible = !empty($config_client_portal_enable) && intval($_POST['client_visible'] ?? 0) ? 1 : 0;
-
- $files = $_FILES['files'] ?? null;
- $count = is_array($files['name'] ?? null) ? count($files['name']) : 0;
- $imported = [];
- $skipped = [];
- for ($i = 0; $i < $count && count($imported) < 50; $i++) {
- $original = basename((string) $files['name'][$i]);
- if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) {
- continue;
- }
- if ($files['error'][$i] !== UPLOAD_ERR_OK || !is_uploaded_file($files['tmp_name'][$i])) {
- $skipped[] = "$original (it didn't upload)";
- continue;
- }
- if (!preg_match('/\.(md|markdown|mdown|mkd)$/i', $original)) {
- $skipped[] = "$original (not a .md file)";
- continue;
- }
- if ($files['size'][$i] > 5 * 1024 * 1024) {
- $skipped[] = "$original (over 5 MB)";
- continue;
- }
- $text = (string) file_get_contents($files['tmp_name'][$i]);
- if (!mb_check_encoding($text, 'UTF-8')) {
- $skipped[] = "$original (not UTF-8 text)";
- continue;
- }
-
- [$name, $markdown] = markdownImportSplit($text, preg_replace('/\.(md|markdown|mdown|mkd)$/i', '', $original));
- $name_sql = escapeSql($name);
- mysqli_query($mysqli, "INSERT INTO documents SET document_name = '$name_sql', document_description = '', document_content = '', document_content_raw = '',
- document_client_visible = $client_visible, document_folder_id = $folder_id, document_created_by = $session_user_id, document_client_id = $client_id");
- $document_id = mysqli_insert_id($mysqli);
-
- $markdown = markdownSaveImages($markdown, $document_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");
-
- logAudit("Document", "Create", "$session_name imported document $name_sql from " . escapeSql($original), $client_id, $document_id);
- $imported[] = [$document_id, $name];
- }
-
- if (!$imported) {
- flashAlert('Nothing was imported' . ($skipped ? ': ' . escapeHtml(implode(', ', $skipped)) : ' - pick the .md files to import.'), 'error');
- redirect();
- }
-
- $what = count($imported) === 1 ? 'Document
' . escapeHtml($imported[0][1]) . ' imported' : count($imported) . ' documents imported';
- flashAlert($what . ($skipped ? ' - left out ' . escapeHtml(implode(', ', $skipped)) : ''), $skipped ? 'warning' : 'success');
-
- // One goes straight to it; several, to the folder they are in
- redirect(count($imported) === 1 ? "document.php?client_id=$client_id&document_id={$imported[0][0]}" : "files.php?client_id=$client_id&folder_id=$folder_id&type=document");
-
-}
-
if (isset($_GET['archive_document'])) {
validateCSRFToken();
diff --git a/agent/post/file.php b/agent/post/file.php
index 100c53806..badd211ff 100644
--- a/agent/post/file.php
+++ b/agent/post/file.php
@@ -52,6 +52,11 @@ if (isset($_POST['upload_files'])) {
$upload_paths = (array) ($_POST['file_paths'] ?? []);
$upload_folders = [];
$folders_made = 0;
+ $folders_made_ids = [];
+
+ // .md files become documents, with the pictures uploaded with them (functions/markdown_upload.php) - unless kept as files
+ $markdown_on = empty($_POST['markdown_keep']) && documentMarkdownReady();
+ $markdown_ids = []; // the .md files and pictures of this upload
foreach ((array) $names as $index => $original_name) {
@@ -82,7 +87,7 @@ if (isset($_POST['upload_files'])) {
$file_mime_type = escapeSql($detected_mime !== '' && $detected_mime !== 'application/octet-stream' ? $detected_mime : $single_file['type']);
$file_size = intval($single_file['size']);
- $file_folder_id = isset($upload_paths[$index]) ? folderForUploadPath($client_id, $folder_id, $upload_paths[$index], $upload_folders, $folders_made) : $folder_id;
+ $file_folder_id = isset($upload_paths[$index]) ? folderForUploadPath($client_id, $folder_id, $upload_paths[$index], $upload_folders, $folders_made, $folders_made_ids) : $folder_id;
mysqli_query($mysqli, "INSERT INTO files SET
file_reference_name = '$file_reference_name',
@@ -115,19 +120,45 @@ if (isset($_POST['upload_files'])) {
logAudit("File", "Upload", "$session_name uploaded file $file_name", $client_id, $file_id);
$uploaded[] = basename($original_name);
+ if ($markdown_on && in_array(strtolower(pathinfo($original_name, PATHINFO_EXTENSION)), array_merge(markdownUploadExtensions(), markdownPictureExtensions()), true)) {
+ $markdown_ids[] = $file_id;
+ }
}
- // A folder goes up in parts from the upload window, which adds up what each part says
+ // A folder goes up in parts from the upload window, which adds up what each part says - its
+ // Markdown waits for the last part, as a picture may come after the .md that uses it
if (!empty($_POST['upload_json'])) {
+ $batch = preg_replace('/[^A-Za-z0-9]/', '', (string) ($_POST['upload_batch'] ?? ''));
+ if ($markdown_on && strlen($batch) >= 16 && ($markdown_ids || $folders_made_ids)) {
+ $batches = array_slice((array) ($_SESSION['upload_batches'] ?? []), -4, null, true);
+ $batches[$batch] = $batches[$batch] ?? ['client_id' => $client_id, 'file_ids' => [], 'folder_ids' => []];
+ if (intval($batches[$batch]['client_id']) === $client_id) {
+ $batches[$batch]['file_ids'] = array_slice(array_merge($batches[$batch]['file_ids'], $markdown_ids), 0, 5000);
+ $batches[$batch]['folder_ids'] = array_slice(array_merge($batches[$batch]['folder_ids'], $folders_made_ids), 0, 5000);
+ }
+ $_SESSION['upload_batches'] = $batches;
+ }
header('Content-Type: application/json');
echo json_encode(['uploaded' => count($uploaded), 'skipped' => array_values(array_map('strval', $skipped)), 'folders' => $folders_made]);
exit;
}
- if ($uploaded && !$skipped) {
- flashAlert(count($uploaded) === 1 ? "Uploaded
{$uploaded[0]}" : "Uploaded
" . count($uploaded) . " files");
+ $markdown = markdownUploadConvert($client_id, $markdown_ids, $folders_made_ids);
+ $files_left = count($uploaded) - count($markdown['documents']) - $markdown['pictures'];
+ [$markdown_said, $markdown_notes, $markdown_tone] = markdownUploadSays($markdown);
+
+ if ($uploaded && $markdown['documents']) {
+ $said = ucfirst(trim(($files_left ? "uploaded
$files_left file" . ($files_left === 1 ? '' : 's') . ' and ' : '') . $markdown_said));
+ $notes = array_filter([$skipped ? 'skipped
' . count($skipped) . ' (not an allowed type, empty or too big): ' . implode(', ', $skipped) : '', $markdown_notes]);
+ flashAlert($said . ($notes ? ' - ' . implode('. ', $notes) : ''), $skipped ? 'warning' : $markdown_tone);
+ // One document and nothing else - straight to it
+ if (count($markdown['documents']) === 1 && !$files_left && !$notes) {
+ redirect("document.php?client_id=$client_id&document_id={$markdown['documents'][0][0]}");
+ }
+ } elseif ($uploaded && !$skipped) {
+ flashAlert((count($uploaded) === 1 ? "Uploaded
{$uploaded[0]}" : "Uploaded
" . count($uploaded) . " files") . ($markdown_notes ? " - $markdown_notes" : ''), $markdown_notes ? 'warning' : 'success');
} elseif ($uploaded) {
- flashAlert("Uploaded
" . count($uploaded) . ", skipped
" . count($skipped) . " (not an allowed type, empty or too big): " . implode(', ', $skipped), 'warning');
+ flashAlert("Uploaded
" . count($uploaded) . ", skipped
" . count($skipped) . " (not an allowed type, empty or too big): " . implode(', ', $skipped) . ($markdown_notes ? ". $markdown_notes" : ''), 'warning');
} else {
flashAlert($skipped ? "Nothing uploaded - not an allowed type, empty or too big: " . implode(', ', $skipped) : 'Choose a file to upload.', 'error');
}
@@ -149,18 +180,41 @@ if (isset($_POST['upload_folder_done'])) {
$uploaded = intval($_POST['uploaded'] ?? 0);
$folders = intval($_POST['folders'] ?? 0);
$skipped = array_slice(array_map(function ($name) { return escapeHtml(mb_substr((string) $name, 0, 200)); }, (array) ($_POST['skipped'] ?? [])), 0, 50);
- $made = $folders ? " and made
$folders folder" . ($folders === 1 ? '' : 's') : '';
- if ($uploaded && !$skipped) {
- flashAlert("Uploaded
$uploaded file" . ($uploaded === 1 ? '' : 's') . $made);
- } elseif ($uploaded) {
- flashAlert("Uploaded
$uploaded$made, skipped
" . count($skipped) . " (not an allowed type, empty or too big): " . implode(', ', $skipped), 'warning');
+ // Its .md files made documents, now every picture is in
+ $batch = preg_replace('/[^A-Za-z0-9]/', '', (string) ($_POST['upload_batch'] ?? ''));
+ $batches = (array) ($_SESSION['upload_batches'] ?? []);
+ $markdown = ['documents' => [], 'missing' => [], 'kept' => [], 'pictures' => 0, 'folders_removed' => 0];
+ $client_id = 0;
+ if ($batch !== '' && isset($batches[$batch])) {
+ $upload = $batches[$batch];
+ unset($batches[$batch]);
+ $_SESSION['upload_batches'] = $batches;
+ $client_id = intval($upload['client_id']);
+ enforceClientAccess();
+ if (empty($_POST['markdown_keep'])) {
+ $markdown = markdownUploadConvert($client_id, (array) $upload['file_ids'], (array) $upload['folder_ids']);
+ }
+ }
+
+ $uploaded -= count($markdown['documents']) + $markdown['pictures'];
+ $folders -= $markdown['folders_removed'];
+ [$markdown_said, $markdown_notes, $markdown_tone] = markdownUploadSays($markdown);
+ $what = implode(' and ', array_filter([$uploaded > 0 ? "uploaded
$uploaded file" . ($uploaded === 1 ? '' : 's') : '', $markdown_said]));
+ if ($what !== '' && $folders > 0) {
+ $what .= $markdown_said !== '' ? ", in
$folders new folder" . ($folders === 1 ? '' : 's') : " and made
$folders folder" . ($folders === 1 ? '' : 's');
+ }
+ $what = ucfirst($what);
+ $notes = array_filter([$skipped ? 'skipped
' . count($skipped) . ' (not an allowed type, empty or too big): ' . implode(', ', $skipped) : '', $markdown_notes]);
+
+ if ($what !== '') {
+ flashAlert($what . ($notes ? ' - ' . implode('. ', $notes) : ''), $skipped ? 'warning' : $markdown_tone);
} else {
flashAlert('Nothing uploaded - not an allowed type, empty or too big' . ($skipped ? ': ' . implode(', ', $skipped) : ''), 'error');
}
header('Content-Type: application/json');
- echo json_encode(['ok' => true]);
+ echo json_encode(['ok' => true, 'go' => count($markdown['documents']) === 1 && $uploaded <= 0 && !$notes ? "document.php?client_id=$client_id&document_id={$markdown['documents'][0][0]}" : '']);
exit;
}
@@ -207,6 +261,38 @@ if (isset($_GET['download_folder_zip']) || isset($_POST['bulk_download_files']))
}
+/*
+ * Make it a document (agent/modals/file/file_make_document.php) - an uploaded .md file becomes a
+ * Markdown document in its folder, with the pictures it uses that are in the client's Files
+ * (functions/markdown_upload.php). The file goes; the document opens.
+ */
+if (isset($_POST['make_file_document'])) {
+
+ validateCSRFToken();
+
+ enforceUserPermission('module_support', 2);
+
+ $file_id = intval($_POST['file_id'] ?? 0);
+ $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_name, file_client_id FROM files WHERE file_id = $file_id"));
+ if (!$row) {
+ flashAlert('That file no longer exists.', 'error');
+ redirect();
+ }
+ $client_id = intval($row['file_client_id']);
+ enforceClientAccess();
+
+ $made = markdownFileMakeDocument($file_id);
+ if (!$made['document_id']) {
+ flashAlert('
' . escapeHtml($row['file_name']) . ' couldn\'t be made a document - ' . escapeHtml($made['why']) . '.', 'error');
+ redirect();
+ }
+
+ [$said, $notes, $tone] = markdownUploadSays(['documents' => [[$made['document_id'], $made['name']]], 'missing' => $made['missing'] ? [$made['name'] => $made['missing']] : [], 'kept' => [], 'pictures' => 0, 'folders_removed' => 0]);
+ flashAlert(ucfirst($said) . ($notes ? " - $notes" : ''), $tone);
+ redirect("document.php?client_id=$client_id&document_id={$made['document_id']}");
+
+}
+
if (isset($_POST['rename_file'])) {
validateCSRFToken();
diff --git a/css/itflow_custom.css b/css/itflow_custom.css
index c67322948..0119006fe 100644
--- a/css/itflow_custom.css
+++ b/css/itflow_custom.css
@@ -5339,6 +5339,20 @@ tr:hover .itflow-files-rename,
padding: .2rem .25rem;
border-bottom: 1px solid var(--bs-border-color-translucent);
}
+/* What becomes a document - .md files, and zips of Markdown pages */
+.itflow-upload-markdown {
+ padding: .65rem .8rem;
+ border: 1px solid var(--bs-info-border-subtle);
+ border-radius: var(--bs-border-radius-lg);
+ background-color: var(--bs-info-bg-subtle);
+ color: var(--bs-info-text-emphasis);
+}
+.itflow-upload-markdown[hidden] {
+ display: none;
+}
+.itflow-upload-markdown .text-body-secondary {
+ color: color-mix(in srgb, var(--bs-info-text-emphasis) 75%, transparent) !important;
+}
/* File quick look preview */
.itflow-file-preview {
@@ -5373,6 +5387,26 @@ tr:hover .itflow-files-rename,
.itflow-file-preview .itflow-asset-empty {
border: 0;
}
+/* An uploaded .md, as it reads */
+.itflow-file-preview-markdown {
+ max-height: 26rem;
+ padding: 1rem 1.25rem;
+ overflow: auto;
+ text-align: left;
+ background-color: var(--bs-body-bg);
+}
+.itflow-file-preview-markdown > :last-child {
+ margin-bottom: 0;
+}
+.itflow-file-preview-markdown h1 {
+ font-size: 1.5rem;
+}
+.itflow-file-preview-markdown h2 {
+ font-size: 1.25rem;
+}
+.itflow-file-preview-markdown h3 {
+ font-size: 1.1rem;
+}
/* Linked records - linkGroupsHtml() in functions/links.php */
.itflow-link-group + .itflow-link-group,
diff --git a/functions.php b/functions.php
index 501de84eb..2b260e7fd 100644
--- a/functions.php
+++ b/functions.php
@@ -19,6 +19,7 @@ require_once __DIR__ . '/functions/request_fields.php';
require_once __DIR__ . '/functions/files.php';
require_once __DIR__ . '/functions/text_diff.php';
require_once __DIR__ . '/functions/markdown.php';
+require_once __DIR__ . '/functions/markdown_upload.php';
require_once __DIR__ . '/functions/domain.php';
require_once __DIR__ . '/functions/certificate.php';
require_once __DIR__ . '/functions/network.php';
diff --git a/functions/files.php b/functions/files.php
index eeee7e665..e9306761a 100644
--- a/functions/files.php
+++ b/functions/files.php
@@ -493,7 +493,8 @@ function fileTypeInfo($extension) {
['media', ['mp4', 'mov', 'av1', 'avi', 'mkv', 'webm', 'wmv'], 'file-video', 'Video'],
['media', ['mp3', 'wav', 'ogg', 'flac', 'm4a'], 'file-audio', 'Audio'],
['archive', ['zip', 'tar', 'gz', 'tgz', '7z', 'rar'], 'file-archive', 'Archive'],
- ['text', ['txt', 'md', 'log'], 'file-alt', 'Text'],
+ ['text', ['md', 'markdown'], 'file-alt', 'Markdown'],
+ ['text', ['txt', 'log'], 'file-alt', 'Text'],
['text', ['msg', 'eml'], 'envelope', 'Email'],
['code', ['json', 'cfg', 'conf', 'ini', 'xml', 'yaml', 'yml', 'ovpn', 'ps1', 'bat', 'sh', 'unf', 'unifi', 'stk', 'swb'], 'file-code', 'Config / script'],
['drawing', ['vsdx', 'drawio'], 'project-diagram', 'Diagram'],
@@ -602,7 +603,7 @@ function folderOptionsHtml($client_id, $selected = 0, $exclude = 0) {
/** The kinds of file a client's Files take - by extension. Upload Files and the API's files/create both check against it. */
function fileUploadExtensions() {
return [
- 'jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx',
+ 'jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'markdown', 'doc', 'docx',
'odt', 'csv', 'xls', 'xlsx', 'ods', 'pptx', 'odp', 'zip', 'tar', 'gz',
'msg', 'json', 'wav', 'mp3', 'ogg', 'mov', 'mp4', 'av1', 'ovpn',
'cfg', 'ps1', 'vsdx', 'drawio', 'pfx', 'pages', 'numbers', 'unf', 'unifi',
@@ -630,11 +631,12 @@ function folderDisplayName($folder_id) {
/**
* For an uploaded folder (Upload > Choose a folder): the folder a file goes in, given the path it
* had on the computer under the folder it was uploaded into - "Network/Configs/router.cfg" puts
- * it in Network, then Configs, made as needed. $made counts the folders made, and $cache keeps
- * what was found for the rest of the upload. Names are tidied; "." and ".." and empty ones are
- * left out, and only the first ten levels are kept.
+ * it in Network, then Configs, made as needed. $made counts the folders made, $made_ids gets their
+ * IDs, and $cache keeps what was found for the rest of the upload. Names are tidied - the ID a
+ * Notion export adds to a folder's name is taken off; "." and ".." and empty ones are left out,
+ * and only the first ten levels are kept.
*/
-function folderForUploadPath($client_id, $parent_id, $relative_path, array &$cache, &$made) {
+function folderForUploadPath($client_id, $parent_id, $relative_path, array &$cache, &$made, &$made_ids = null) {
global $mysqli, $session_name;
$client_id = intval($client_id);
$folder_id = intval($parent_id);
@@ -642,7 +644,7 @@ function folderForUploadPath($client_id, $parent_id, $relative_path, array &$cac
array_pop($parts); // the file's own name
$depth = 0;
foreach ($parts as $part) {
- $name = trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $part) ?? '');
+ $name = markdownNotionName(preg_replace('/[\x00-\x1F\x7F]/u', '', $part) ?? '');
if ($name === '' || $name === '.' || $name === '..' || ++$depth > 10) {
continue;
}
@@ -657,6 +659,9 @@ function folderForUploadPath($client_id, $parent_id, $relative_path, array &$cac
mysqli_query($mysqli, "INSERT INTO folders SET folder_name = '$name_sql', parent_folder = $folder_id, folder_location = 0, folder_client_id = $client_id");
$cache[$key] = mysqli_insert_id($mysqli);
$made++;
+ if (is_array($made_ids)) {
+ $made_ids[] = $cache[$key];
+ }
logAudit("Folder", "Create", "$session_name created folder $name_sql uploading a folder", $client_id, $cache[$key]);
}
}
diff --git a/functions/markdown_upload.php b/functions/markdown_upload.php
new file mode 100644
index 000000000..e7cba859c
--- /dev/null
+++ b/functions/markdown_upload.php
@@ -0,0 +1,509 @@
+/), 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,
+ * , 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;
+ }
+ //  - 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);
+}
diff --git a/includes/footer.php b/includes/footer.php
index a239ac2a2..9ab0689df 100644
--- a/includes/footer.php
+++ b/includes/footer.php
@@ -179,6 +179,7 @@ if ($itflow_pulse) { ?>
+
= 0; i--) {
+ if (u32(view, i) === 0x06054b50) {
+ end = i;
+ break;
+ }
+ }
+ if (end < 0) {
+ throw new Error('it isn\'t a zip');
+ }
+ var count = u16(view, end + 10);
+ var size = u32(view, end + 12);
+ var offset = u32(view, end + 16);
+ if (count === 0xFFFF || size === 0xFFFFFFFF || offset === 0xFFFFFFFF) {
+ throw new Error('it\'s too big to open here');
+ }
+ if (offset + size > file.size) {
+ throw new Error('it isn\'t a complete zip');
+ }
+ return read(file, offset, offset + size).then(function (dir) {
+ var entries = [];
+ var at = 0;
+ for (var n = 0; n < count; n++) {
+ if (at + 46 > dir.byteLength || u32(dir, at) !== 0x02014b50) {
+ throw new Error('it isn\'t a complete zip');
+ }
+ var flags = u16(dir, at + 8);
+ var nameLength = u16(dir, at + 28);
+ var path = entryName(dir, at + 46, nameLength, flags & 0x800).replace(/\\/g, '/').replace(/^\/+/, '');
+ var entry = {
+ path: path,
+ method: u16(dir, at + 10),
+ packed: u32(dir, at + 20),
+ size: u32(dir, at + 24),
+ encrypted: (flags & 1) === 1,
+ local: u32(dir, at + 42)
+ };
+ at += 46 + nameLength + u16(dir, at + 30) + u16(dir, at + 32);
+ if (path !== '' && !/\/$/.test(path)) {
+ entries.push(entry);
+ }
+ }
+ return entries;
+ });
+ });
+ }
+
+ /** One file taken out of the zip, as a File with its own name. */
+ function unpack(file, entry) {
+ if (entry.encrypted) {
+ return Promise.reject(new Error('it has a password'));
+ }
+ if (entry.method !== 0 && entry.method !== 8) {
+ return Promise.reject(new Error('it\'s packed in a way the browser can\'t open'));
+ }
+ return read(file, entry.local, entry.local + 30).then(function (head) {
+ if (u32(head, 0) !== 0x04034b50) {
+ throw new Error('it isn\'t a complete zip');
+ }
+ var start = entry.local + 30 + u16(head, 26) + u16(head, 28);
+ var packed = file.slice(start, start + entry.packed);
+ var name = entry.path.split('/').pop();
+ if (entry.method === 0) {
+ return new File([packed], name);
+ }
+ return new Response(packed.stream().pipeThrough(new DecompressionStream('deflate-raw'))).blob().then(function (blob) {
+ return new File([blob], name);
+ });
+ });
+ }
+
+ var canUnpack = false;
+ try {
+ canUnpack = typeof DecompressionStream === 'function' && !!new DecompressionStream('deflate-raw');
+ } catch (e) {
+ canUnpack = false;
+ }
+
+ window.itflowZip = { canUnpack: canUnpack, list: list, unpack: unpack };
+})();