Uploading a .md file makes it a Markdown document in the folder it goes into, with the pictures uploaded with it found by their links or names and copied in, a zip of Markdown pages from Notion, Obsidian or a wiki opened in the Upload window and brought in as its folders, Keep them as files to upload as before, Make it a document for a .md already in Files, uploaded .md files shown as they read in the preview and quick look, and Import Markdown Files removed; 26.12.6 changelog

This commit is contained in:
johnnyq
2026-12-05 00:55:06 -05:00
parent 36503ca768
commit 7ea52c95a8
16 changed files with 1077 additions and 183 deletions

View File

@@ -12,6 +12,7 @@ Update from Maintenance > Update as usual. This release has one database change:
- API keys get a 403 saying which module is off for anything of a module that is switched off - tickets with ticketing off, assets and credentials with IT documentation off, invoices with invoicing off.
- Contacts imported before with a ? in place of an accented letter keep it. Import the same file again with **A contact already here** set to **Update it** and their names are put right - contacts are matched by email. Anything else imported that way, such as a location or vendor, is matched by its name, so correct those by hand.
- The warranty lookup button shows beside **Warranty expires** on the asset form straight after the update, as Lenovo needs no key and is switched on. It only asks Lenovo when someone clicks it. Switch Lenovo off in Admin > Warranty Lookup if you'd rather ITFlow didn't ask Lenovo's support site at all.
- A `.md` file uploaded to a client's Files now becomes a document you can edit. To upload one as a file, as before, turn on **Keep them as files** in the Upload window. **Import Markdown Files** has gone from the Upload menu - Upload does it.
### New Features & Updates
@@ -22,6 +23,8 @@ Update from Maintenance > Update as usual. This release has one database change:
- Audit logs and notifications still name a ticket, invoice or asset of a module that is off, without linking it. The quick looks - a contact, location, vendor or ticket at a glance - leave out what is off too, and a quote's files from the client can still be downloaded with IT documentation off.
- Look up an asset's warranty by its serial number. On an asset's Purchase tab, the search button beside **Warranty expires** asks its maker - Dell, HP or Lenovo - and fills in when its warranty runs out and, as **Purchased**, when it began: for a Dell, the day it shipped. To do many at once, tick them on Assets and choose **Bulk Action > Look Up Warranty** - each one's answer is listed as it comes in. Only empty dates are filled in: a date already on an asset is never changed, and on the form the maker's is offered beside it to use instead. Each date filled in is noted in the asset's History. An asset is matched by its make, or with no make by its model - Latitude, OptiPlex, ThinkPad, EliteBook and the like. HP Enterprise servers aren't looked up.
- Admin > Warranty Lookup, under Integrations, sets up each maker. Dell needs a TechDirect Warranty API key and HP an HP Warranty API key, which each approve by hand - HP doesn't give its to every IT company. Lenovo needs none: ITFlow asks Lenovo's support site as its own pages do, which can stop working when Lenovo changes the site. **Save and test** beside each one tries a serial number with what you've entered. HP works through each lookup as a job, so its answers can take a few minutes. It's part of IT documentation, and goes with it when that module is off.
- Upload a `.md` file and it becomes a document written in Markdown, that you can edit, in the folder it goes into - with **Upload** or by dropping it on the list, no import step. Upload the pictures it uses with it - pick them together, or upload the folder they're in - and they go into the document, found where its links say or by their name; a picture no file uses uploads as a file. A zip of Markdown pages, such as an export from Notion, Obsidian or Confluence, is opened in the Upload window and brought in as the folder it holds: each page a document in its folder with its pictures, its other files uploaded beside them, and Notion's IDs taken off the names. Afterwards ITFlow says which pictures a file uses that weren't uploaded with it, to add in the editor. The Upload window says what will become a document, and **Keep them as files** uploads the `.md` files as they are and a zip as a zip.
- A `.md` already in Files shows as it reads in its preview and quick look, with its pictures that are in the client's files, and **Make it a document**, in its menu and quick look, makes it a document: the pictures it uses are copied in, and the document takes the file's place and its links.
### Bug Fixes
@@ -42,6 +45,8 @@ Update from Maintenance > Update as usual. This release has one database change:
- Saved cards: `billingStripeCardSave($stripe, $client_id, $customer, $pm)` (`functions/billing_pay.php`) is how every client-added card is saved - `autopayCheckoutFinish()`, `cardUpdateFinish()` and the client portal's `stripe_save_card` in `client/post.php`, which matched only Stripe's payment method ID, a new one each time a card is entered. It matches `card.fingerprint` among the cards on the client's Stripe customer (`billingStripeCardTwins()`, one `allPaymentMethods` call), points the oldest saved row at the new payment method and its description, clearing `saved_payment_update_key` when the expiry changed as `cardRefresh()` does, detaches the one it replaced (`billingStripeCardDetach()`) and merges any other copies in (`billingStripeCardMerge()`: `recurring_payments` moved, payment method detached, row deleted), under a per-client `GET_LOCK`. Stripe not answering falls back to saving a new row, as before. `billingStripeCardTwinsNightly()` in `cron/nightly_tasks.php`, before `cardExpiryNightly()`, merges cards already saved twice - only for clients with two saved cards of the same brand and last four digits, keeping the one that runs out last.
- Warranty lookup: `functions/warranty.php`. `warrantyMaker($make, $model)` gives `dell`, `hp`, `lenovo` or `''` (HPE and Hewlett Packard Enterprise `''`); `warrantySettings()` opens the keys, sealed with `secretSeal(..., 'warranty')`, and `warrantyAnyReady()` says whether any maker is set up. `warrantyLookup($items)` takes `key => ['maker', 'serial']` and answers each with `warrantyFound()` or `warrantyNotFound($why, $kind)` - `kind` `found`, `missing`, `skip`, `error` or `pending`, `end` the latest coverage end, `start` Dell's `shipDate` or the earliest start, `coverage` the name of the one ending last. Dell: an OAuth client-credentials token from `auth/oauth/v2/token` (form fields, then Basic), then `PROD/sbil/eapi/v5/asset-entitlements`, 100 tags a call. Lenovo: `us/en/api/v4/mse/getproducts?productId=` for its product ID, then `ds_warranties` from its `products/{id}/warranty` page - active contracts and every base warranty. HP: one `productwarranty/v2/jobs` job a batch (`warrantyHpStart()`), answered `pending` with the job ID, which `warrantyHpCheck()` polls. `warrantyApply()` writes only an empty `asset_warranty_expire` or `asset_purchase_date`, with an `asset_history` row and `logAudit()`. The hosts are `WARRANTY_DELL_URL`, `WARRANTY_HP_URL` and `WARRANTY_LENOVO_URL`, which config.php can define first.
- `agent/ajax.php` answers `warranty_lookup` - an asset form's `make`, `model` and `serial` (`{answer}`), or up to 25 `asset_ids` (`{results}`, written) - and `warranty_hp_check`, an HP job ID asked after with the same `asset_ids` or `serial` (`{done: false}` until HP has finished) - with IT documentation on (`moduleOffText('itdoc')` otherwise), Support at Modify, and `hasClientAccess()` for each asset. `js/warranty_lookup.js` drives the form's `[data-warranty-lookup]` button and `agent/modals/asset/asset_bulk_warranty.php` (up to 500 assets, 5 a request, HP polled every 10 seconds for up to 15 minutes). `admin/settings_warranty.php` and `admin/post/settings_warranty.php` are the `warranty` page in `settingsPages()`, its own group in `adminNavGroups()`, mapped to `itdoc` in `modulePaths()`. Database 4.4.4 adds `config_warranty_dell_client_id`, `config_warranty_dell_client_secret`, `config_warranty_hp_client_id`, `config_warranty_hp_client_secret` and `config_warranty_lenovo` (default 1) to `settings`.
- Markdown uploads: `functions/markdown_upload.php`. `upload_files` (`agent/post/file.php`) collects an upload's .md files and pictures (`markdownUploadExtensions()`, `markdownPictureExtensions()`) and hands them to `markdownUploadConvert($client_id, $file_ids, $folders_made)` at its end; a folder sent in parts keeps them in `$_SESSION['upload_batches'][upload_batch]` until `upload_folder_done`, which now answers `go` - the document's address when one document is all it made. `markdown_keep` turns it off. `markdownFileToDocument()` makes each document with `markdownImportSplit()`, `markdownSaveImages()` and `markdownRewritePictures($markdown, $find)` - `![alt](target)`, `<img src>`, `[id]: target` for a picture and Obsidian's `![[name]]`, code blocks left alone - finding each with `markdownFindPicture()`: through the folder tree from the .md's folder (`markdownPathFolder()`, `..` included, folder names with or without Notion's ID), then by a name only one picture has. `markdownCopyPicture()` checks it with `getimagesizefromstring()` and stores it under `uploads/documents/<id>/` by its real type. The file's links move to the document through `linkAdd()`; the .md and the pictures used go (`markdownUploadRemoveFile()`), and so do folders the upload made that are left empty (`markdownUploadRemoveEmptyFolders()`). `folderForUploadPath()` takes `&$made_ids` and drops Notion's 32-character ID from a folder's name (`markdownNotionName()`).
- `js/zip_reader.js` - `window.itflowZip.list(file)` reads a zip's central directory, `.unpack(file, entry)` takes a file out, inflating with `DecompressionStream('deflate-raw')`; no zip64 or encrypted entries. The upload window sends a zip with Markdown pages as the folder it holds, through the folder upload, so PHP's zip extension isn't needed. Make it a document: `agent/modals/file/file_make_document.php`, `make_file_document`, `markdownFileMakeDocument()`. `get_file_markdown` (`agent/ajax.php`) and `fileMarkdownPreviewHtml()` render an uploaded .md - its pictures in Files as `file.php` links - for the grid previewer (`kind: 'markdown'`) and the file quick look. `agent/modals/document/document_import_markdown.php` and `import_markdown_documents` are removed. `fileUploadExtensions()` takes `.markdown`, and `fileTypeInfo()` calls `.md` Markdown.
## [26.12.5]

View File

@@ -1687,6 +1687,21 @@ if (isset($_GET['get_document_content'])) {
}
/*
* An uploaded .md file as its Markdown reads, for the files grid's previewer and the file's quick
* look - made safe by markdownToHtml(). The pictures it points to that are in the client's Files
* show from there (functions/markdown_upload.php).
*/
if (isset($_GET['get_file_markdown'])) {
header('Content-Type: application/json');
// Whoever can open the files list can preview its files
enforceUserPermission('module_client');
echo json_encode(['content' => fileMarkdownPreviewHtml(intval($_GET['get_file_markdown']))]);
exit;
}
/*
* Returns ordered list of active contacts for a specified client
*/

View File

@@ -245,6 +245,10 @@ function filesItemMenu($item) {
$html .= "<a class=\"dropdown-item ajax-modal\" href=\"#\" data-modal-url=\"modals/file/file_rename.php?id=$id\"><i class=\"fas fa-fw fa-pen me-2\"></i>Rename</a>";
$html .= "<a class=\"dropdown-item ajax-modal\" href=\"#\" data-modal-url=\"modals/file/file_move.php?id=$id\"><i class=\"fas fa-fw fa-folder-open me-2\"></i>Move</a>";
$html .= linkPickerButton('file', $id, '', 'Link', 'dropdown-item', 'fas fa-fw fa-link me-2');
// An uploaded .md can't be edited as a file - it can as a document
if (documentMarkdownReady() && in_array(strtolower((string) ($item['row']['file_ext'] ?? '')), markdownUploadExtensions(), true)) {
$html .= "<a class=\"dropdown-item ajax-modal\" href=\"#\" data-modal-url=\"modals/file/file_make_document.php?id=$id\"><i class=\"fab fa-fw fa-markdown me-2\"></i>Make it a document</a>";
}
}
$archive_name = 'file';
} else {
@@ -357,11 +361,6 @@ $preview = []; // the grid's previewer payload
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/document/document_add_from_template.php?client_id=<?= $client_id ?>&folder_id=<?= $folder_id ?>">
<i class="fas fa-fw fa-puzzle-piece me-2"></i>Document from Template
</a>
<?php if (documentMarkdownReady()) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/document/document_import_markdown.php?client_id=<?= $client_id ?>&folder_id=<?= $folder_id ?>">
<i class="fab fa-fw fa-markdown me-2"></i>Import Markdown Files
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/folder/folder_add.php?client_id=<?= $client_id ?>&current_folder_id=<?= $folder_id ?>">
<i class="fas fa-fw fa-folder-plus me-2"></i>New Folder
@@ -596,7 +595,11 @@ $preview = []; // the grid's previewer payload
} else {
$mime = $row['file_mime_type'];
$excerpt = '';
if (!in_array($mime, getInlineViewableMimeTypes(), true)) {
if (in_array(strtolower($row['file_ext']), markdownUploadExtensions(), true) && strpos((string) $mime, 'text/') === 0) {
// Shown as the Markdown reads (agent/ajax.php get_file_markdown)
$kind = 'markdown';
$excerpt = getFileTextExcerpt($client_id, $row['file_reference_name']);
} elseif (!in_array($mime, getInlineViewableMimeTypes(), true)) {
$kind = 'none';
} elseif ($mime === 'application/pdf') {
$kind = 'pdf';
@@ -606,7 +609,7 @@ $preview = []; // the grid's previewer payload
} else {
$kind = 'image';
}
$preview_url = "file.php?file_id=$id&action=view";
$preview_url = $kind === 'markdown' ? "ajax.php?get_file_markdown=$id" : "file.php?file_id=$id&action=view";
$action_url = "file.php?file_id=$id";
$meta = strtoupper($row['file_ext']) . ' · ' . formatBytes($item['size']);
}

View File

@@ -140,7 +140,8 @@
});
doc.innerHTML = '';
if (item.kind === 'document') {
if (item.kind === 'document' || item.kind === 'markdown') {
// A document, or an uploaded .md shown as the Markdown reads
var requested = current;
doc.innerHTML = '<p class="text-secondary mb-0">Loading...</p>';
doc.classList.remove('d-none');
@@ -151,14 +152,14 @@
return;
}
// HTMLPurifier output - the same the document page renders
doc.innerHTML = data.content || '<p class="text-secondary mb-0">This document is empty.</p>';
doc.innerHTML = data.content || '<p class="text-secondary mb-0">' + (item.kind === 'markdown' ? 'There is nothing in this file.' : 'This document is empty.') + '</p>';
if (typeof prettyContent === 'function') {
prettyContent();
}
})
.catch(function () {
if (requested === current) {
doc.innerHTML = '<p class="text-danger mb-0">Could not load this document.</p>';
doc.innerHTML = '<p class="text-danger mb-0">Could not load this ' + (item.kind === 'markdown' ? 'file' : 'document') + '.</p>';
}
});
} else if (item.kind === 'image') {

View File

@@ -1,71 +0,0 @@
<?php
/*
* Import Markdown files - each .md file picked becomes a document written in Markdown, in the
* folder picked (import_markdown_documents, agent/post/document.php).
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$client_id = intval($_GET['client_id'] ?? 0);
enforceClientAccess();
$folder_id = folderOwnedId($_GET['folder_id'] ?? 0, $client_id);
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fab fa-fw fa-markdown me-2"></i>Import Markdown Files</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="post.php" method="post" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<div class="modal-body">
<?php if (!documentMarkdownReady()) { ?>
<div class="alert alert-warning mb-0">Markdown documents arrive with the next database update - run it from Maintenance &gt; Update first.</div>
<?php } else { ?>
<div class="mb-3">
<label class="form-label">Markdown files <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-file-import"></i></span>
<input type="file" class="form-control" name="files[]" multiple required accept=".md,.markdown,.mdown,.mkd,text/markdown">
</div>
<div class="form-text">Each becomes a document written in Markdown, named by the heading it starts with or its file name - up to 50 at a time. Pictures a file points to on your computer aren't brought in.</div>
</div>
<div class="mb-3">
<label class="form-label">Folder</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-folder"></i></span>
<select class="form-select select2" name="folder">
<?= folderOptionsHtml($client_id, $folder_id) ?>
</select>
</div>
</div>
<?php if (!empty($config_client_portal_enable)) { ?>
<div class="form-check form-switch">
<input type="hidden" name="client_visible" value="0">
<input class="form-check-input" type="checkbox" role="switch" name="client_visible" value="1" id="importMarkdownVisible">
<label class="form-check-label" for="importMarkdownVisible">
<i class="fas fa-fw fa-eye text-body-secondary me-1"></i>Show them in the client portal <span class="text-body-secondary small">- to their technical contacts</span>
</label>
</div>
<?php } ?>
<?php } ?>
</div>
<div class="modal-footer">
<?php if (documentMarkdownReady()) { ?>
<button type="submit" name="import_markdown_documents" class="btn btn-primary fw-bold"><i class="fas fa-file-import me-2"></i>Import</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -34,8 +34,12 @@ $file_archived = !empty($row['file_archived_at']);
$file_info = fileTypeInfo($row['file_ext']);
$file_mime = $row['file_mime_type'];
// What the preview can show - the same rule agent/file.php serves inline by
if (!in_array($file_mime, getInlineViewableMimeTypes(), true)) {
$file_is_markdown = in_array(strtolower((string) $row['file_ext']), markdownUploadExtensions(), true);
// What the preview can show - the same rule agent/file.php serves inline by; a .md as it reads
if ($file_is_markdown && strpos((string) $file_mime, 'text/') === 0) {
$preview_kind = 'markdown';
} elseif (!in_array($file_mime, getInlineViewableMimeTypes(), true)) {
$preview_kind = '';
} elseif ($file_mime === 'application/pdf') {
$preview_kind = 'pdf';
@@ -79,6 +83,9 @@ ob_start();
<a href="file.php?file_id=<?= $file_id ?>&action=view" target="_blank" rel="noopener" title="Open full size"><img src="file.php?file_id=<?= $file_id ?>&thumb=1" alt="<?= $file_name ?>"></a>
<?php } elseif ($preview_kind === 'pdf') { ?>
<iframe src="file.php?file_id=<?= $file_id ?>&action=view#view=FitH" title="<?= $file_name ?>"></iframe>
<?php } elseif ($preview_kind === 'markdown') { ?>
<?php /* markdownToHtml() output - purified, as the document page renders */ ?>
<div class="itflow-file-preview-markdown prettyContent"><?= fileMarkdownPreviewHtml($file_id) ?: '<p class="text-body-secondary mb-0">There is nothing in this file.</p>' ?></div>
<?php } elseif ($preview_kind === 'text') { ?>
<pre><?= escapeHtml(getFileTextExcerpt($client_id, $row['file_reference_name'], 2000)) ?></pre>
<?php } else { ?>
@@ -136,6 +143,9 @@ ob_start();
<?php if ($can_edit && !$file_archived) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/file/file_rename.php?id=<?= $file_id ?>"><i class="fas fa-pen me-2"></i>Rename</button>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/file/file_move.php?id=<?= $file_id ?>"><i class="fas fa-folder-open me-2"></i>Move</button>
<?php if ($file_is_markdown && documentMarkdownReady()) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/file/file_make_document.php?id=<?= $file_id ?>"><i class="fab fa-markdown me-2"></i>Make it a document</button>
<?php } ?>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
</div>

View File

@@ -0,0 +1,58 @@
<?php
/*
* Make it a document - an uploaded .md file becomes a document written in Markdown, in the same
* folder, that can be edited (make_file_document, agent/post/file.php; functions/markdown_upload.php).
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$file_id = intval($_GET['id'] ?? 0);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_client_id, file_ext, file_name, file_folder_id, file_archived_at FROM files WHERE file_id = $file_id LIMIT 1"));
if (!$row) {
echo json_encode(['error' => 'That file no longer exists.']);
exit;
}
$client_id = intval($row['file_client_id']);
enforceClientAccess();
$is_markdown = in_array(strtolower((string) $row['file_ext']), markdownUploadExtensions(), true);
$file_name = escapeHtml($row['file_name']);
$folder_name = escapeHtml(folderDisplayName(folderOwnedId($row['file_folder_id'], $client_id)));
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fab fa-fw fa-markdown me-2"></i>Make <strong><?= $file_name ?></strong> a document</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="file_id" value="<?= $file_id ?>">
<div class="modal-body">
<?php if (!$is_markdown || $row['file_archived_at']) { ?>
<div class="alert alert-warning mb-0">Only a .md file in Files can be made a document.</div>
<?php } elseif (!documentMarkdownReady()) { ?>
<div class="alert alert-warning mb-0">Markdown documents arrive with the next database update - run it from Maintenance &gt; Update first.</div>
<?php } else { ?>
<p>It becomes a document written in Markdown, in <strong><?= $folder_name ?></strong>, that you can edit - named by the heading it starts with.</p>
<ul class="mb-0 ps-3">
<li>The pictures it uses that are in this client's Files are copied into it. Any that aren't are listed after, to add in the editor.</li>
<li>The uploaded file is replaced by the document, with what it was linked to. Its <strong>Export</strong> menu gives you a .md again.</li>
</ul>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($is_markdown && !$row['file_archived_at'] && documentMarkdownReady()) { ?>
<button type="submit" name="make_file_document" class="btn btn-primary fw-bold"><i class="fas fa-file-alt me-2"></i>Make it a document</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -10,6 +10,12 @@
* folders: each file goes with its path under it (file_paths[]), and the
* folders are made as needed. It goes up twenty files at a time (upload_json),
* and upload_folder_done says how it went before the page reloads.
*
* .md files become documents, with the pictures uploaded with them, unless
* Keep them as files is on (functions/markdown_upload.php) - upload_batch ties
* the parts of one upload together for that. A zip with Markdown pages in it -
* a Notion, Obsidian or wiki export - is opened here (js/zip_reader.js) and
* goes up as the folder it holds.
*/
require_once '../../../includes/modal_header.php';
@@ -30,7 +36,7 @@ $vendor_id = assetClientOwnedId('vendor', $_GET['vendor_id'] ?? 0, $client_id);
$link_name = $asset_id ? $asset['name'] : ($contact_id ? getFieldById('contacts', $contact_id, 'contact_name') : ($software_id ? $software['name'] : ($location_id ? getFieldById('locations', $location_id, 'location_name') : ($vendor_id ? getFieldById('vendors', $vendor_id, 'vendor_name') : ''))));
// The extensions agent/post/file.php accepts - offered to the picker so the wrong kind is never chosen
$upload_extensions = ['jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'odt', 'csv', 'xls', 'xlsx', 'ods',
$upload_extensions = ['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', 'key', 'stk', 'bat', 'swb'];
@@ -67,6 +73,24 @@ ob_start();
<ul class="list-unstyled mb-0 mt-2 itflow-upload-list" data-upload-list></ul>
<div class="text-danger small mt-1" data-upload-error hidden></div>
<input type="hidden" name="upload_batch" value="<?= bin2hex(random_bytes(12)) ?>">
<?php if (documentMarkdownReady()) { ?>
<div class="itflow-upload-markdown mt-3" data-upload-markdown hidden>
<div class="d-flex gap-2">
<i class="fab fa-fw fa-markdown fa-lg mt-1"></i>
<div class="small min-w-0 flex-grow-1">
<div class="fw-semibold" data-upload-markdown-title></div>
<ul class="list-unstyled mb-1" data-upload-markdown-list></ul>
<div class="text-body-secondary" data-upload-markdown-note>The pictures they use go into them, from what you upload with them. Everything else uploads as it is.</div>
</div>
</div>
<div class="form-check form-switch small mt-2 mb-0">
<input class="form-check-input" type="checkbox" role="switch" name="markdown_keep" value="1" id="uploadMarkdownKeep" data-upload-markdown-keep>
<label class="form-check-label" for="uploadMarkdownKeep">Keep them as files <span class="text-body-secondary">- each .md uploaded as it is, and a zip as a zip</span></label>
</div>
</div>
<?php } ?>
<div class="mt-3 mb-3">
<label class="form-label">Folder</label>
<div class="input-group">
@@ -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 = '<i class="fas fa-spinner fa-spin me-2"></i>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 = '<i class="fas fa-spinner fa-spin me-2"></i>' + (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 = '<i class="fas fa-spinner fa-spin me-2"></i>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;

View File

@@ -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 <strong>' . escapeHtml($imported[0][1]) . '</strong> 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();

View File

@@ -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 <strong>{$uploaded[0]}</strong>" : "Uploaded <strong>" . count($uploaded) . "</strong> 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 <strong>$files_left</strong> file" . ($files_left === 1 ? '' : 's') . ' and ' : '') . $markdown_said));
$notes = array_filter([$skipped ? 'skipped <strong>' . count($skipped) . '</strong> (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 <strong>{$uploaded[0]}</strong>" : "Uploaded <strong>" . count($uploaded) . "</strong> files") . ($markdown_notes ? " - $markdown_notes" : ''), $markdown_notes ? 'warning' : 'success');
} elseif ($uploaded) {
flashAlert("Uploaded <strong>" . count($uploaded) . "</strong>, skipped <strong>" . count($skipped) . "</strong> (not an allowed type, empty or too big): " . implode(', ', $skipped), 'warning');
flashAlert("Uploaded <strong>" . count($uploaded) . "</strong>, skipped <strong>" . count($skipped) . "</strong> (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 <strong>$folders</strong> folder" . ($folders === 1 ? '' : 's') : '';
if ($uploaded && !$skipped) {
flashAlert("Uploaded <strong>$uploaded</strong> file" . ($uploaded === 1 ? '' : 's') . $made);
} elseif ($uploaded) {
flashAlert("Uploaded <strong>$uploaded</strong>$made, skipped <strong>" . count($skipped) . "</strong> (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 <strong>$uploaded</strong> file" . ($uploaded === 1 ? '' : 's') : '', $markdown_said]));
if ($what !== '' && $folders > 0) {
$what .= $markdown_said !== '' ? ", in <strong>$folders</strong> new folder" . ($folders === 1 ? '' : 's') : " and made <strong>$folders</strong> folder" . ($folders === 1 ? '' : 's');
}
$what = ucfirst($what);
$notes = array_filter([$skipped ? 'skipped <strong>' . count($skipped) . '</strong> (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('<strong>' . escapeHtml($row['file_name']) . '</strong> 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();

View File

@@ -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,

View File

@@ -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';

View File

@@ -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]);
}
}

View File

@@ -0,0 +1,509 @@
<?php
/*
* Markdown files made into documents - an uploaded .md becomes a document written in Markdown, in
* the folder it was uploaded into, with the pictures it points to brought in.
*
* Upload (agent/post/file.php upload_files) uploads everything as files first - a folder, or a zip
* the upload window unpacks in the browser, with its folders made as they were - then hands the
* .md files and pictures of that upload to markdownUploadConvert(). Each .md's pictures are found
* where its links say, from the folder it went into ("images/rack.png", "../shared/logo.png"),
* or by their name among the pictures uploaded with it; each is copied in as the document's own
* picture, as a pasted one is (uploads/documents/<id>/), 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 <img src="target">, 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 <in angle brackets> 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);
// <img src="target">
$part = preg_replace_callback('/(<img\b[^>]*?\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 <strong>' . escapeHtml($result['documents'][0][1]) . '</strong> from Markdown';
} elseif ($made) {
$said = "made <strong>$made</strong> 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 <em>' . escapeHtml($document) . '</em>';
}
}
$notes[] = ($count === 1 ? 'a picture it uses wasn\'t' : "<strong>$count</strong> 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 '<strong>' . escapeHtml($kept[0]) . '</strong> 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);
}

View File

@@ -179,6 +179,7 @@ if ($itflow_pulse) { ?>
<script src="<?= staticFileUrl('/js/client_card.js') ?>"></script>
<script src="<?= staticFileUrl('/js/quick_add.js') ?>"></script>
<script src="<?= staticFileUrl('/js/warranty_lookup.js') ?>"></script>
<script src="<?= staticFileUrl('/js/zip_reader.js') ?>"></script>
<?php } ?>
<script src="<?= staticFileUrl('/js/ticket_timers.js') ?>"></script>
<?php

125
js/zip_reader.js Normal file
View File

@@ -0,0 +1,125 @@
/*
* A .zip read in the browser - the files in it, and each file taken out - for the upload window
* (agent/modals/file/file_upload.php), which unpacks a zip of Markdown pages, an export from
* Notion, Obsidian or a wiki, and sends what's in it up as a folder. Nothing is sent to read it.
*
* A zip keeps its list of files at its end, so only that is read to see what's in it; each file
* is read when it's taken out. Stored and deflated files - what every zip tool writes - are taken
* out, deflated ones through the browser's DecompressionStream. A zip64 (over 4 GB or 65,535
* files) or one with a password isn't.
*/
(function () {
'use strict';
function u16(view, at) {
return view.getUint16(at, true);
}
function u32(view, at) {
return view.getUint32(at, true);
}
function read(file, start, end) {
return file.slice(start, end).arrayBuffer().then(function (buffer) {
return new DataView(buffer);
});
}
// A name is UTF-8 when the zip says so; older tools wrote the computer's own code page
var strictUtf8 = new TextDecoder('utf-8', { fatal: true });
function entryName(view, at, length, utf8) {
var raw = new Uint8Array(view.buffer, view.byteOffset + at, length);
if (utf8) {
return new TextDecoder('utf-8').decode(raw);
}
try {
return strictUtf8.decode(raw);
} catch (e) {
return new TextDecoder('windows-1252').decode(raw);
}
}
/** What's in a zip: [{path, size, packed, method, encrypted, local}], folders left out. Rejects with why it can't be read. */
function list(file) {
var tail = Math.min(file.size, 65535 + 22);
return read(file, file.size - tail, file.size).then(function (view) {
var end = -1;
for (var i = view.byteLength - 22; i >= 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 };
})();