$document_count document" . ($document_count === 1 ? '' : 's') : '', $file_count ? "$file_count file" . ($file_count === 1 ? '' : 's') : '', ])) ?: 'nothing'; } if (isset($_POST['upload_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $client_id = intval($_POST['client_id']); $description = escapeSql($_POST['description'] ?? ''); $client_dir = "../uploads/clients/$client_id"; enforceClientAccess(); // Only the client's own folder, contact, asset, license, location and vendor $folder_id = folderOwnedId($_POST['folder_id'] ?? 0, $client_id); $contact_id = assetClientOwnedId('contact', $_POST['contact_id'] ?? 0, $client_id); $asset = linkRecord('asset', $_POST['asset_id'] ?? 0); $asset_id = $asset && intval($asset['client_id']) === $client_id ? intval($asset['id']) : 0; $software = linkRecord('software', $_POST['software_id'] ?? 0); $software_id = $software && intval($software['client_id']) === $client_id ? intval($software['id']) : 0; $location_id = assetClientOwnedId('location', $_POST['location_id'] ?? 0, $client_id); $vendor_id = assetClientOwnedId('vendor', $_POST['vendor_id'] ?? 0, $client_id); if (!is_dir($client_dir)) { mkdir($client_dir, 0755, true); } $allowedExtensions = fileUploadExtensions(); $uploaded = []; $skipped = []; $names = $_FILES['file']['name'] ?? []; // A folder from the computer - each file's path under it, its folders made as needed (functions/files.php) $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) { $single_file = [ 'name' => $_FILES['file']['name'][$index], 'type' => $_FILES['file']['type'][$index], 'tmp_name' => $_FILES['file']['tmp_name'][$index], 'error' => $_FILES['file']['error'][$index], 'size' => $_FILES['file']['size'][$index] ]; $file_reference_name = checkFileUpload($single_file, $allowedExtensions); if (!$file_reference_name) { $skipped[] = $original_name; continue; } $dest_path = "$client_dir/$file_reference_name"; if (!move_uploaded_file($single_file['tmp_name'], $dest_path)) { $skipped[] = $original_name; continue; } $file_name = escapeSql(basename($original_name)); $file_extension = escapeSql(strtolower(pathinfo($original_name, PATHINFO_EXTENSION))); // What the file is, read from the file - not what the browser said it was $detected_mime = function_exists('finfo_open') ? (string) finfo_file(finfo_open(FILEINFO_MIME_TYPE), $dest_path) : ''; $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, $folders_made_ids) : $folder_id; mysqli_query($mysqli, "INSERT INTO files SET file_reference_name = '$file_reference_name', file_name = '$file_name', file_description = '$description', file_ext = '$file_extension', file_mime_type = '$file_mime_type', file_size = $file_size, file_created_by = $session_user_id, file_folder_id = $file_folder_id, file_client_id = $client_id"); $file_id = mysqli_insert_id($mysqli); if ($contact_id) { mysqli_query($mysqli, "INSERT IGNORE INTO contact_files SET contact_id = $contact_id, file_id = $file_id"); } if ($asset_id) { mysqli_query($mysqli, "INSERT IGNORE INTO asset_files SET asset_id = $asset_id, file_id = $file_id"); } if ($software_id) { mysqli_query($mysqli, "INSERT IGNORE INTO software_files SET software_id = $software_id, file_id = $file_id"); } if ($location_id) { mysqli_query($mysqli, "INSERT IGNORE INTO location_files SET location_id = $location_id, file_id = $file_id"); } if ($vendor_id) { mysqli_query($mysqli, "INSERT IGNORE INTO vendor_files SET vendor_id = $vendor_id, file_id = $file_id"); } 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 - 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; } $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) . ($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'); } redirect(); } /* * A folder uploaded in parts from the upload window (upload_json above) - when the last part is * in, it says how it went, here, so the message is on the page it reloads. */ if (isset($_POST['upload_folder_done'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $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); // 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, 'go' => count($markdown['documents']) === 1 && $uploaded <= 0 && !$notes ? "document.php?client_id=$client_id&document_id={$markdown['documents'][0][0]}" : '']); exit; } /* * A folder and everything under it as one zip (the folder's menu on the files list), or the files * and documents ticked (Bulk Action) - functions/files.php filesZipSend(). Documents go in as * .html pages; archived ones are left out. */ if (isset($_GET['download_folder_zip']) || isset($_POST['bulk_download_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 1); $client_id = intval($_GET['client_id'] ?? $_POST['client_id'] ?? 0); enforceClientAccess(); if (isset($_GET['download_folder_zip'])) { $folder_id = folderOwnedId($_GET['download_folder_zip'], $client_id); $zip_items = filesZipFolderItems($client_id, $folder_id); $zip_name = $folder_id ? folderDisplayName($folder_id) : getFieldById('clients', $client_id, 'client_name') . ' files'; $what = $folder_id ? 'folder ' . escapeSql(folderDisplayName($folder_id)) : 'all files'; } else { $zip_items = []; foreach (['file', 'document'] as $kind) { foreach ((array) ($_POST[$kind . '_ids'] ?? []) as $id) { $zip_items[] = ['kind' => $kind, 'id' => intval($id), 'path' => '']; } } $zip_name = getFieldById('clients', $client_id, 'client_name') . ' files'; $what = count($zip_items) . ' ticked'; } $sent = filesZipSend($client_id, $zip_items, $zip_name); if ($sent === false) { flashAlert(class_exists('ZipArchive') ? ($zip_items ? 'Too big for one zip - over 2 GB. Download it a folder at a time.' : 'Nothing to download - there are no files or documents here.') : 'Zips can\'t be made on this server - PHP\'s zip extension isn\'t installed.', 'error'); redirect(); } logAudit("File", "Download", "$session_name downloaded $what as a zip - $sent files and documents", $client_id); exit; } /* * 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(); enforceUserPermission('module_support', 2); $file_id = intval($_POST['file_id']); $file_name = escapeSql(trim($_POST['file_name'] ?? '')); $file_description = escapeSql($_POST['file_description'] ?? ''); $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(); } $old_file_name = escapeSql($row['file_name']); $client_id = intval($row['file_client_id']); enforceClientAccess(); if ($file_name === '') { flashAlert('A file needs a name.', 'error'); redirect(); } mysqli_query($mysqli, "UPDATE files SET file_name = '$file_name', file_description = '$file_description' WHERE file_id = $file_id"); logAudit("File", "Rename", "$session_name renamed file $old_file_name to $file_name", $client_id, $file_id); flashAlert("File " . trim($_POST['file_name']) . " saved"); redirect(); } if (isset($_POST['move_file'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $file_id = intval($_POST['file_id']); $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(); } $file_name = escapeSql($row['file_name']); $client_id = intval($row['file_client_id']); enforceClientAccess(); // Only into one of this client's folders $folder_id = folderOwnedId($_POST['folder_id'] ?? 0, $client_id); $folder_name = folderDisplayName($folder_id); $undo = undoSnapshot('files', 'file_id', [$file_id], ['file_folder_id'], 'file_client_id'); // for Undo on the message mysqli_query($mysqli, "UPDATE files SET file_folder_id = $folder_id WHERE file_id = $file_id"); logAudit("File", "Move", "$session_name moved file $file_name to " . escapeSql($folder_name), $client_id, $file_id); flashAlert("File {$row['file_name']} moved to $folder_name"); undoOfferChanges($undo, "" . escapeHtml($row['file_name']) . " moved back", 'module_support'); redirect(); } if (isset($_GET['archive_file'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $file_id = intval($_GET['archive_file']); $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(); $undo = undoArchiveBefore('file', $file_id); // for Undo on the message mysqli_query($mysqli, "UPDATE files SET file_archived_at = NOW() WHERE file_id = $file_id"); logAudit("File", "Archive", "$session_name archived file " . escapeSql($row['file_name']), $client_id, $file_id); flashAlert("File {$row['file_name']} archived", 'error'); undoOfferArchive($undo); redirect(); } if (isset($_GET['restore_file'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $file_id = intval($_GET['restore_file']); $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(); mysqli_query($mysqli, "UPDATE files SET file_archived_at = NULL WHERE file_id = $file_id"); logAudit("File", "Restore", "$session_name restored file " . escapeSql($row['file_name']), $client_id, $file_id); flashAlert("File {$row['file_name']} restored"); redirect(); } if (isset($_POST['delete_file'])) { validateCSRFToken(); enforceUserPermission('module_support', 3); $file_name = fileDeleteForGood(intval($_POST['file_id'])); if ($file_name === null) { flashAlert('That file no longer exists.', 'error'); } else { flashAlert("File $file_name deleted", 'error'); } redirect(); } /* * The bulk actions take files and documents together - the files list ticks * both - and each item is checked against the agent's client access on its * own, since nothing ties the ticked ids to one client. */ if (isset($_POST['bulk_archive_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $file_count = 0; $document_count = 0; $undo = undoArchiveBefore('file', $_POST['file_ids'] ?? []); // for Undo on the message $undo_documents = undoArchiveBefore('document', $_POST['document_ids'] ?? []); foreach (array_map('intval', (array) ($_POST['file_ids'] ?? [])) as $file_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_client_id, file_name FROM files WHERE file_id = $file_id AND file_archived_at IS NULL")); if (!$row) { continue; } $client_id = intval($row['file_client_id']); enforceClientAccess(); mysqli_query($mysqli, "UPDATE files SET file_archived_at = NOW() WHERE file_id = $file_id"); logAudit("File", "Archive", "$session_name archived file " . escapeSql($row['file_name']), $client_id, $file_id); $file_count++; } foreach (array_map('intval', (array) ($_POST['document_ids'] ?? [])) as $document_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_client_id FROM documents WHERE document_id = $document_id AND document_archived_at IS NULL")); if (!$row) { continue; } $client_id = intval($row['document_client_id']); enforceClientAccess(); mysqli_query($mysqli, "UPDATE documents SET document_archived_at = NOW(), document_updated_at = document_updated_at WHERE document_id = $document_id"); logAudit("Document", "Archive", "$session_name archived document " . escapeSql($row['document_name']), $client_id, $document_id); $document_count++; } flashAlert("Archived " . filesCountPhrase($document_count, $file_count), 'error'); undoOfferArchive($undo, $undo_documents); redirect(); } if (isset($_POST['bulk_restore_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $file_count = 0; $document_count = 0; foreach (array_map('intval', (array) ($_POST['file_ids'] ?? [])) as $file_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_client_id, file_name FROM files WHERE file_id = $file_id AND file_archived_at IS NOT NULL")); if (!$row) { continue; } $client_id = intval($row['file_client_id']); enforceClientAccess(); mysqli_query($mysqli, "UPDATE files SET file_archived_at = NULL WHERE file_id = $file_id"); logAudit("File", "Restore", "$session_name restored file " . escapeSql($row['file_name']), $client_id, $file_id); $file_count++; } foreach (array_map('intval', (array) ($_POST['document_ids'] ?? [])) as $document_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_client_id FROM documents WHERE document_id = $document_id AND document_archived_at IS NOT NULL")); if (!$row) { continue; } $client_id = intval($row['document_client_id']); enforceClientAccess(); mysqli_query($mysqli, "UPDATE documents SET document_archived_at = NULL, document_updated_at = document_updated_at WHERE document_id = $document_id"); logAudit("Document", "Restore", "$session_name restored document " . escapeSql($row['document_name']), $client_id, $document_id); $document_count++; } flashAlert("Restored " . filesCountPhrase($document_count, $file_count)); redirect(); } if (isset($_POST['bulk_delete_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 3); $file_count = 0; $document_count = 0; foreach (array_map('intval', (array) ($_POST['file_ids'] ?? [])) as $file_id) { if (fileDeleteForGood($file_id) !== null) { $file_count++; } } foreach (array_map('intval', (array) ($_POST['document_ids'] ?? [])) as $document_id) { if (documentDeleteForGood($document_id) !== null) { $document_count++; } } flashAlert("Deleted " . filesCountPhrase($document_count, $file_count), 'error'); redirect(); } if (isset($_POST['bulk_move_files'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); $target_folder = intval($_POST['bulk_folder_id'] ?? 0); // A folder of a client this agent can reach - another's name isn't said back $folder_client_id = $target_folder ? intval(getFieldById('folders', $target_folder, 'folder_client_id')) : 0; if ($target_folder && (!$folder_client_id || !hasClientAccess($folder_client_id))) { flashAlert('That folder no longer exists.', 'error'); redirect(); } $folder_name = folderDisplayName($target_folder); $file_count = 0; $document_count = 0; // For Undo on the message - each back to the folder it came from $undo = undoSnapshot('files', 'file_id', $_POST['file_ids'] ?? [], ['file_folder_id'], 'file_client_id'); $undo_documents = undoSnapshot('documents', 'document_id', $_POST['document_ids'] ?? [], ['document_folder_id'], 'document_client_id'); // Each item only moves into a folder of its own client - one of another // client's folders would take it out of sight of both. One already there is left alone. foreach (array_map('intval', (array) ($_POST['file_ids'] ?? [])) as $file_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT file_client_id, file_name, file_folder_id FROM files WHERE file_id = $file_id")); if (!$row) { continue; } $client_id = intval($row['file_client_id']); enforceClientAccess(); if (($target_folder && folderOwnedId($target_folder, $client_id) !== $target_folder) || intval($row['file_folder_id']) === $target_folder) { continue; } mysqli_query($mysqli, "UPDATE files SET file_folder_id = $target_folder WHERE file_id = $file_id"); logAudit("File", "Move", "$session_name moved file " . escapeSql($row['file_name']) . " to " . escapeSql($folder_name), $client_id, $file_id); $file_count++; } foreach (array_map('intval', (array) ($_POST['document_ids'] ?? [])) as $document_id) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_client_id, document_name, document_folder_id FROM documents WHERE document_id = $document_id")); if (!$row) { continue; } $client_id = intval($row['document_client_id']); enforceClientAccess(); if (($target_folder && folderOwnedId($target_folder, $client_id) !== $target_folder) || intval($row['document_folder_id']) === $target_folder) { continue; } mysqli_query($mysqli, "UPDATE documents SET document_folder_id = $target_folder, document_updated_at = document_updated_at WHERE document_id = $document_id"); logAudit("Document", "Move", "$session_name moved document " . escapeSql($row['document_name']) . " to " . escapeSql($folder_name), $client_id, $document_id); $document_count++; } flashAlert("Moved " . filesCountPhrase($document_count, $file_count) . " to $folder_name"); undoOffer('{n} item{s} moved back', array_merge(undoChangedSteps($undo), undoChangedSteps($undo_documents)), 'module_support'); redirect(); }