/, so it needs its id first - written in Markdown, the HTML is made from it
[$processed_html, $markdown] = documentPostedContent($document_id);
$processed_content = mysqli_real_escape_string($mysqli, $processed_html);
mysqli_query($mysqli, "UPDATE documents SET document_content = '$processed_content', document_content_raw = '" . escapeSql(documentContentRaw($_POST['name'] ?? '', $processed_html)) . "'
" . documentMarkdownSet($markdown) . " WHERE document_id = $document_id");
if ($contact_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO contact_documents SET contact_id = $contact_id, document_id = $document_id");
}
if ($asset_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO asset_documents SET asset_id = $asset_id, document_id = $document_id");
}
if ($software_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO software_documents SET software_id = $software_id, document_id = $document_id");
}
if ($location_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO location_documents SET location_id = $location_id, document_id = $document_id");
}
if ($vendor_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO vendor_documents SET vendor_id = $vendor_id, document_id = $document_id");
}
if ($service_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO service_documents SET service_id = $service_id, document_id = $document_id");
logAudit("Service", "Link", "$session_name linked new document $name to service " . escapeSql($service['name']), $client_id, $service_id);
}
tagSetForRecord('document', $document_id, (array) ($_POST['tags'] ?? []));
logAudit("Document", "Create", "$session_name created document $name", $client_id, $document_id);
// Written up from a ticket (Write up as a document) - its history says so, and it opens on the document
$from_ticket = ticketRow($_POST['from_ticket_id'] ?? 0);
if ($from_ticket && (intval($from_ticket['ticket_client_id']) ?: intval($config_internal_client_id ?? 0)) === $client_id) {
logTicketHistory(intval($from_ticket['ticket_id']), "$session_name wrote this ticket up as document $name");
} else {
$from_ticket = null;
}
flashAlert("Document " . trim($_POST['name']) . " created");
// From an asset, a contact, a license, a location, a vendor or a service, back to it; otherwise to the new document
redirect(!$from_ticket && ($contact_id || $asset_id || $software_id || $location_id || $vendor_id || $service_id) ? null : "document.php?client_id=$client_id&document_id=$document_id");
}
if (isset($_POST['add_document_from_template'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$client_id = intval($_POST['client_id'] ?? 0);
$document_template_id = intval($_POST['document_template_id'] ?? 0);
enforceClientAccess();
if (!mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id"))) {
flashAlert('Pick the client it is for.', 'error');
redirect();
}
$folder = folderOwnedId($_POST['folder'] ?? 0, $client_id);
$template = documentTemplateRow($document_template_id);
if (!$template || $template['document_template_archived_at']) {
flashAlert('That template is gone or archived.', 'error');
redirect();
}
// What it asks for, answered - a required one left blank, or an answer that isn't one, says so
$answers = ticketFillInAnswers(documentTemplateFillInsFor($document_template_id), $_POST['fill_ins'] ?? [], $fill_in_error);
if ($answers === null) {
flashAlert($fill_in_error, 'error');
redirect();
}
// A copy of what it says and its images, filled in for the client and remembering the template (functions/document_template.php)
$document_id = documentTemplateMakeDocument($document_template_id, $client_id, $_POST['name'] ?? '', $_POST['description'] ?? '', $folder,
intval($_POST['location_id'] ?? 0), intval($_POST['contact_id'] ?? 0), $answers);
$document_name = (string) getFieldById('documents', $document_id, 'document_name');
logAudit("Document", "Create", "$session_name created document " . escapeSql($document_name) . " from template " . escapeSql($template['document_template_name']), $client_id, $document_id);
flashAlert("Document " . escapeHtml($document_name) . " created from template " . escapeHtml($template['document_template_name']) . "");
redirect("/agent/document.php?client_id=$client_id&document_id=$document_id");
}
if (isset($_POST['edit_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
require_once 'document_model.php';
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
if ($name === '') {
flashAlert('A document needs a name.', 'error');
redirect();
}
// What it said before, kept as a version
$document_version_id = documentKeepVersion($row);
// Written in the rich text editor or in Markdown - the HTML every page shows, and what was written
[$processed_html, $markdown] = documentPostedContent($document_id);
$content = mysqli_real_escape_string($mysqli, $processed_html);
$content_raw = escapeSql(documentContentRaw($_POST['name'], $processed_html));
// The portal switch is only on the form when the portal is on - left alone otherwise
$visible_sql = isset($_POST['client_visible']) ? ', document_client_visible = ' . (intval($_POST['client_visible']) ? 1 : 0) : '';
mysqli_query($mysqli, "UPDATE documents SET
document_name = '$name',
document_description = '$description',
document_content = '$content',
document_content_raw = '$content_raw',
document_updated_by = $session_user_id
$visible_sql
" . documentMarkdownSet($markdown) . "
WHERE document_id = $document_id");
// Only a form that showed the tags changes them
if (isset($_POST['tags_form'])) {
tagSetForRecord('document', $document_id, (array) ($_POST['tags'] ?? []));
}
logAudit("Document", "Edit", "$session_name edited document $name, previous version kept", $client_id, $document_id);
flashAlert("Document " . trim($_POST['name']) . " saved - the previous version is kept");
redirect("document.php?client_id=$client_id&document_id=$document_id");
}
if (isset($_POST['move_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
// Only into one of this client's folders
$folder_id = folderOwnedId($_POST['folder'] ?? 0, $client_id);
$folder_name = folderDisplayName($folder_id);
$undo = undoSnapshot('documents', 'document_id', [$document_id], ['document_folder_id'], 'document_client_id'); // for Undo on the message
mysqli_query($mysqli, "UPDATE documents SET document_folder_id = $folder_id, document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Move", "$session_name moved document " . escapeSql($row['document_name']) . " to folder " . escapeSql($folder_name), $client_id, $document_id);
flashAlert("Document {$row['document_name']} moved to $folder_name");
undoOfferChanges($undo, "" . escapeHtml($row['document_name']) . " moved back", 'module_support');
redirect();
}
if (isset($_GET['mark_document_reviewed'])) {
// Looked over and still right - due again a review period from now
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_GET['mark_document_reviewed']);
$document_id = intval($row['document_id']);
if ($row['document_archived_at']) {
flashAlert('That document is archived.', 'error');
redirect();
}
mysqli_query($mysqli, "UPDATE documents SET document_reviewed_at = NOW(), document_reviewed_by = " . intval($session_user_id) . ", document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Edit", "$session_name marked document " . escapeSql($row['document_name']) . " as reviewed", $client_id, $document_id);
$review = documentReviewState(mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_created_at, document_updated_at, document_reviewed_at, document_template_review_months, document_template_archived_at,
" . (documentReviewOwnReady() ? 'document_review_months' : 'NULL AS document_review_months') . "
FROM documents LEFT JOIN document_templates USING (document_template_id) WHERE document_id = $document_id")));
flashAlert("Document " . escapeHtml($row['document_name']) . " marked as reviewed" . ($review ? " - next due " . date('M j, Y', strtotime($review['next'])) : ''));
redirect();
}
/*
* How often a document is reviewed, set on it - every so many months, never,
* or as its template says ('template'). When it was last looked at stays as
* it is.
*/
if (isset($_GET['set_document_review'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_GET['set_document_review']);
$document_id = intval($row['document_id']);
$months = (string) ($_GET['months'] ?? '');
if (!documentReviewOwnReady() || ($months !== 'template' && (!ctype_digit($months) || !isset(DOCUMENT_TEMPLATE_REVIEW_MONTHS[intval($months)])))) {
flashAlert('Pick how often it is reviewed.', 'error');
redirect();
}
mysqli_query($mysqli, "UPDATE documents SET document_review_months = " . ($months === 'template' ? 'NULL' : intval($months)) . ", document_updated_at = document_updated_at WHERE document_id = $document_id");
$how = $months === 'template' ? 'as its template says' : lcfirst(DOCUMENT_TEMPLATE_REVIEW_MONTHS[intval($months)]);
logAudit("Document", "Edit", "$session_name set document " . escapeSql($row['document_name']) . ($months === '0' ? ' not to be reviewed on a schedule' : " to be reviewed $how"), $client_id, $document_id);
flashAlert("Document " . escapeHtml($row['document_name']) . " " . ($months === '0' ? "isn't reviewed on a schedule" : "is reviewed $how"));
redirect();
}
if (isset($_POST['set_document_template'])) {
// The template it counts as made from - what it says stays as it is
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
$current_id = intval(getFieldById('documents', $document_id, 'document_template_id'));
// A current template, or the one it is from already - or none
$template_id = intval($_POST['document_template_id'] ?? 0);
$template = $template_id ? documentTemplateRow($template_id) : null;
if ($template_id && (!$template || ($template['document_template_archived_at'] && $template_id !== $current_id))) {
flashAlert('That template is gone or archived.', 'error');
redirect();
}
mysqli_query($mysqli, "UPDATE documents SET document_template_id = $template_id, document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Edit", "$session_name " . ($template ? "set document " . escapeSql($row['document_name']) . " as made from template " . escapeSql($template['document_template_name']) : "set document " . escapeSql($row['document_name']) . " as not from a template"), $client_id, $document_id);
flashAlert("Document " . escapeHtml($row['document_name']) . " " . ($template ? "counts as made from " . escapeHtml($template['document_template_name']) . "" : "no longer counts as made from a template"));
redirect();
}
if (isset($_POST['rename_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
$name = escapeSql(trim($_POST['name'] ?? ''));
$description_sql = isset($_POST['description']) ? ", document_description = '" . escapeSql($_POST['description']) . "'" : '';
if ($name === '') {
flashAlert('A document needs a name.', 'error');
redirect();
}
mysqli_query($mysqli, "UPDATE documents SET document_name = '$name' $description_sql, document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Edit", "$session_name renamed document " . escapeSql($row['document_name']) . " to $name", $client_id, $document_id);
flashAlert("Document " . trim($_POST['name']) . " saved");
redirect();
}
/*
* Copy a document (agent/modals/document/document_copy.php) - in the same client's files, or into
* another client's that the agent can reach (functions/files.php documentCopy()).
*/
if (isset($_POST['copy_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
$from_client_id = $client_id;
$client_id = intval($_POST['client_id'] ?? $from_client_id);
enforceClientAccess();
if (!mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL"))) {
flashAlert('Pick a client to copy it to.', 'error');
redirect();
}
// A folder of that client's, or their top level
$folder_id = folderOwnedId($_POST['folder_id'] ?? 0, $client_id);
$copy_name = trim((string) ($_POST['name'] ?? ''));
if ($copy_name === '') {
flashAlert('A document needs a name.', 'error');
redirect();
}
$new_id = documentCopy($document_id, $client_id, $folder_id, mb_substr($copy_name, 0, 200));
$copy_name_sql = escapeSql($copy_name);
$to = $client_id === $from_client_id ? '' : ' for ' . escapeSql((string) getFieldById('clients', $client_id, 'client_name'));
logAudit("Document", "Create", "$session_name copied document " . escapeSql($row['document_name']) . " as $copy_name_sql$to", $client_id, $new_id);
flashAlert("Copied to " . escapeHtml($copy_name) . "" . ($to ? ' for ' . escapeHtml((string) getFieldById('clients', $client_id, 'client_name')) . '' : '') . " - it isn't in the client portal or linked to anything yet");
redirect("document.php?client_id=$client_id&document_id=$new_id");
}
/* A favorite or not - favorites show on the client's overview, with their favorite assets, licenses and logins. */
if (isset($_GET['toggle_document_favorite'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_GET['toggle_document_favorite']);
$document_id = intval($row['document_id']);
$favorite = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT document_favorite FROM documents WHERE document_id = $document_id"))[0]) ? 0 : 1;
mysqli_query($mysqli, "UPDATE documents SET document_favorite = $favorite, document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Edit", "$session_name " . ($favorite ? 'made' : 'took') . " document " . escapeSql($row['document_name']) . ($favorite ? ' a favorite' : ' out of the favorites'), $client_id, $document_id);
flashAlert("" . escapeHtml($row['document_name']) . " " . ($favorite ? "is a favorite - it's on the client's overview" : 'is no longer a favorite'));
redirect();
}
if (isset($_POST['toggle_document_visibility'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_POST['document_id']);
$document_id = intval($row['document_id']);
$document_visible = intval($_POST['document_visible'] ?? 0) ? 1 : 0;
$wording = $document_visible ? 'visible' : 'hidden';
mysqli_query($mysqli, "UPDATE documents SET document_client_visible = $document_visible, document_updated_at = document_updated_at WHERE document_id = $document_id");
logAudit("Document", "Edit", "$session_name made document " . escapeSql($row['document_name']) . " $wording in the client portal", $client_id, $document_id);
flashAlert("Document {$row['document_name']} is now $wording in the client portal");
redirect();
}
if (isset($_GET['export_document'])) {
validateCSRFToken();
// Reading, not changing - anyone who can open the document can take a PDF of it
enforceUserPermission('module_client');
$row = documentForHandler($_GET['export_document']);
$document_id = intval($row['document_id']);
logAudit("Document", "Export", "$session_name exported document " . escapeSql($row['document_name']), $client_id, $document_id);
// With the company's letterhead, page numbers and its headings as bookmarks (functions/document_pdf.php)
require_once '../libs/TCPDF/tcpdf.php';
require_once '../functions/document_pdf.php';
billingPdfSend(documentPdfRender(documentPdfDocument($row)));
}
/*
* A document as a Markdown file (functions/markdown.php documentMarkdownFile()) - what a Markdown
* document says as it was written, a rich text one made Markdown - with its name on top.
*/
if (isset($_GET['export_document_markdown'])) {
validateCSRFToken();
// Reading, not changing - as for its PDF
enforceUserPermission('module_client');
$row = documentForHandler($_GET['export_document_markdown']);
$document_id = intval($row['document_id']);
logAudit("Document", "Export", "$session_name downloaded document " . escapeSql($row['document_name']) . " as Markdown", $client_id, $document_id);
$file_name = trim(preg_replace('/[^A-Za-z0-9 ._-]/', '', $row['document_name'])) ?: 'Document';
header('Content-Type: text/markdown; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $file_name . '.md"; filename*=UTF-8\'\'' . rawurlencode(trim($row['document_name']) . '.md'));
header('X-Content-Type-Options: nosniff');
echo documentMarkdownFile($row['document_name'], $row['document_content'], $row['document_markdown']);
exit;
}
/*
* Markdown files made into documents (agent/modals/document/document_import_markdown.php) - one
* each, written in Markdown, in the folder picked. Each is named by the title in its front
* matter or the heading it starts with, else its file name (markdownImportSplit()).
*/
if (isset($_POST['import_markdown_documents'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$client_id = intval($_POST['client_id'] ?? 0);
enforceClientAccess();
if (!documentMarkdownReady() || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id"))) {
flashAlert('Markdown files can\'t be imported here yet.', 'error');
redirect();
}
$folder_id = folderOwnedId($_POST['folder'] ?? 0, $client_id);
$client_visible = !empty($config_client_portal_enable) && intval($_POST['client_visible'] ?? 0) ? 1 : 0;
$files = $_FILES['files'] ?? null;
$count = is_array($files['name'] ?? null) ? count($files['name']) : 0;
$imported = [];
$skipped = [];
for ($i = 0; $i < $count && count($imported) < 50; $i++) {
$original = basename((string) $files['name'][$i]);
if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) {
continue;
}
if ($files['error'][$i] !== UPLOAD_ERR_OK || !is_uploaded_file($files['tmp_name'][$i])) {
$skipped[] = "$original (it didn't upload)";
continue;
}
if (!preg_match('/\.(md|markdown|mdown|mkd)$/i', $original)) {
$skipped[] = "$original (not a .md file)";
continue;
}
if ($files['size'][$i] > 5 * 1024 * 1024) {
$skipped[] = "$original (over 5 MB)";
continue;
}
$text = (string) file_get_contents($files['tmp_name'][$i]);
if (!mb_check_encoding($text, 'UTF-8')) {
$skipped[] = "$original (not UTF-8 text)";
continue;
}
[$name, $markdown] = markdownImportSplit($text, preg_replace('/\.(md|markdown|mdown|mkd)$/i', '', $original));
$name_sql = escapeSql($name);
mysqli_query($mysqli, "INSERT INTO documents SET document_name = '$name_sql', document_description = '', document_content = '', document_content_raw = '',
document_client_visible = $client_visible, document_folder_id = $folder_id, document_created_by = $session_user_id, document_client_id = $client_id");
$document_id = mysqli_insert_id($mysqli);
$markdown = markdownSaveImages($markdown, $document_id);
$html = markdownToHtml($markdown);
mysqli_query($mysqli, "UPDATE documents SET document_content = '" . mysqli_real_escape_string($mysqli, $html) . "',
document_content_raw = '" . escapeSql(documentContentRaw($name, $html)) . "'" . documentMarkdownSet($markdown) . " WHERE document_id = $document_id");
logAudit("Document", "Create", "$session_name imported document $name_sql from " . escapeSql($original), $client_id, $document_id);
$imported[] = [$document_id, $name];
}
if (!$imported) {
flashAlert('Nothing was imported' . ($skipped ? ': ' . escapeHtml(implode(', ', $skipped)) : ' - pick the .md files to import.'), 'error');
redirect();
}
$what = count($imported) === 1 ? 'Document ' . escapeHtml($imported[0][1]) . ' imported' : count($imported) . ' documents imported';
flashAlert($what . ($skipped ? ' - left out ' . escapeHtml(implode(', ', $skipped)) : ''), $skipped ? 'warning' : 'success');
// One goes straight to it; several, to the folder they are in
redirect(count($imported) === 1 ? "document.php?client_id=$client_id&document_id={$imported[0][0]}" : "files.php?client_id=$client_id&folder_id=$folder_id&type=document");
}
if (isset($_GET['archive_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_GET['archive_document']);
$document_id = intval($row['document_id']);
$undo = undoArchiveBefore('document', $document_id); // for Undo on the message
mysqli_query($mysqli, "UPDATE documents SET document_archived_at = NOW(), document_updated_at = document_updated_at WHERE document_id = $document_id");
// An archived document drops its links, as it always has
linkRemoveAll('document', $document_id);
logAudit("Document", "Archive", "$session_name archived document " . escapeSql($row['document_name']), $client_id, $document_id);
flashAlert("Document {$row['document_name']} archived", 'error');
undoOfferArchive($undo);
redirect();
}
if (isset($_GET['restore_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$row = documentForHandler($_GET['restore_document']);
$document_id = intval($row['document_id']);
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);
flashAlert("Document {$row['document_name']} restored");
redirect();
}
/*
* Put an older version back. What the document says now is kept as a version
* first, so a restore can itself be undone.
*/
if (isset($_POST['restore_document_version'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$document_version_id = intval($_POST['document_version_id']);
$version = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_version_document_id, document_version_name, document_version_description,
document_version_content, " . documentMarkdownSql('document_version_markdown') . ", document_version_created_at
FROM document_versions WHERE document_version_id = $document_version_id"));
if (!$version) {
flashAlert('That version no longer exists.', 'error');
redirect();
}
$row = documentForHandler($version['document_version_document_id']);
$document_id = intval($row['document_id']);
documentKeepVersion($row);
$name = escapeSql($version['document_version_name']);
$content = mysqli_real_escape_string($mysqli, (string) $version['document_version_content']);
$content_raw = escapeSql(documentContentRaw($version['document_version_name'], $version['document_version_content']));
mysqli_query($mysqli, "UPDATE documents SET
document_name = '$name',
document_description = '" . escapeSql($version['document_version_description']) . "',
document_content = '$content',
document_content_raw = '$content_raw',
document_updated_by = $session_user_id
" . documentMarkdownSet($version['document_version_markdown']) . "
WHERE document_id = $document_id");
$version_date = date('M j, Y g:i A', strtotime($version['document_version_created_at']));
logAudit("Document", "Edit", "$session_name restored document $name to its version of " . escapeSql($version_date) . ", the current one kept", $client_id, $document_id);
flashAlert("Document {$version['document_version_name']} restored to the version of $version_date - what it said before is kept as a version");
redirect("document.php?client_id=$client_id&document_id=$document_id");
}
if (isset($_GET['delete_document_version'])) {
validateCSRFToken();
enforceUserPermission('module_support', 3);
$document_version_id = intval($_GET['delete_document_version']);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_version_name, document_client_id FROM documents, document_versions
WHERE document_version_document_id = document_id AND document_version_id = $document_version_id"));
if (!$row) {
flashAlert('That version no longer exists.', 'error');
redirect();
}
$client_id = intval($row['document_client_id']);
enforceClientAccess();
mysqli_query($mysqli, "DELETE FROM document_versions WHERE document_version_id = $document_version_id");
logAudit("Document Version", "Delete", "$session_name deleted document version " . escapeSql($row['document_version_name']), $client_id);
flashAlert("A version of {$row['document_version_name']} deleted", 'error');
redirect();
}
if (isset($_GET['delete_document'])) {
validateCSRFToken();
enforceUserPermission('module_support', 3);
$document_name = documentDeleteForGood(intval($_GET['delete_document']));
if ($document_name === null) {
flashAlert('That document no longer exists.', 'error');
redirect();
}
flashAlert("Document $document_name and all its versions deleted", 'error');
// From the document's own page there is nothing to go back to
if (($_GET['from'] ?? '') === 'document_details') {
redirect("files.php?client_id=$client_id");
}
redirect();
}