';
}
/** Label / value pairs as a two-column table - for a client's or a location's details. */
function clientExportPdfFacts(array $facts, $label_width = 26) {
$html = '
';
foreach ($facts as $label => $value) {
if (trim(strip_tags((string) $value)) === '') {
continue;
}
$html .= '
' . escapeHtml($label) . '
' . $value . '
';
}
return $html . '
';
}
/**
* A document's HTML made fit for TCPDF: purified, and every image either
* one of the document's own (uploads/documents//), inlined, or dropped -
* TCPDF would otherwise go and fetch any URL a document points at, and a
* format it cannot draw ends the whole PDF. Wide images are scaled to the
* page.
*/
function clientExportPdfDocumentHtml($html, $document_id) {
return clientExportPdfImages(documentHtmlPurify($html), $document_id);
}
/**
* The images of purified HTML made fit for TCPDF, as above - its own from
* uploads/<$folder>// (documents, or kb for an article) inlined, a WebP
* one as a PNG, any other dropped. Also for a document's or an article's own
* PDF (functions/document_pdf.php).
*/
function clientExportPdfImages($html, $id, $folder = 'documents') {
if (stripos($html, ']*>/i', function ($match) use ($base, $folder) {
$tag = $match[0];
$src = preg_match('/\bsrc\s*=\s*"([^"]*)"/i', $tag, $m) ? html_entity_decode($m[1], ENT_QUOTES, 'UTF-8') : '';
$alt = preg_match('/\balt\s*=\s*"([^"]*)"/i', $tag, $m) ? $m[1] : '';
$data = null;
if (preg_match('#^data:image/(png|jpe?g|gif);base64,(.+)$#is', $src, $m)) {
$data = base64_decode($m[2], true) ?: null;
} elseif ($base && preg_match('#^/?uploads/' . $folder . '/\d+/([^/?\#]+)$#', $src, $m)) {
$path = realpath($base . '/' . rawurldecode($m[1]));
if ($path && strpos($path, $base . DIRECTORY_SEPARATOR) === 0 && is_file($path)) {
$data = file_get_contents($path);
}
}
$info = $data ? @getimagesizefromstring($data) : false;
// A WebP one as a PNG, which TCPDF can draw
if ($info && $info[2] === IMAGETYPE_WEBP && function_exists('imagewebp') && ($image = @imagecreatefromstring($data))) {
ob_start();
imagepng($image);
$data = ob_get_clean();
$info = @getimagesizefromstring($data);
}
if (!$info || !in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) {
return $alt !== '' ? '[' . $alt . ']' : '[image]';
}
$width = min(intval($info[0]), 640);
return '';
}, $html);
}
/**
* The documentation PDF for one client, as a string. $options from
* clientExportOptions(): the sections to include, and with 'secrets' the
* passwords and 2FA secrets - the PDF is then locked with 'password'.
*/
function clientExportPdf($client_id, $options) {
global $session_name, $config_whitelabel_enabled;
require_once __DIR__ . '/../libs/TCPDF/tcpdf.php';
require_once __DIR__ . '/client_export_pdf.php';
$client_id = intval($client_id);
$pdf_options = ['archived' => false] + $options;
$data = function ($dataset) use ($client_id, $pdf_options) {
static $cache = [];
return $cache[$dataset] ?? ($cache[$dataset] = clientExportRows($dataset, $client_id, $pdf_options));
};
$client = $data('client')[0] ?? ['name' => ''];
$company = clientExportCompany();
$sections = clientExportSections();
$has = function ($section) use ($options) {
return clientExportHas($options, $section);
};
$e = function ($value) {
return clientExportPdfText($value);
};
// Letter for North America, A4 everywhere else
$format = in_array($company['company_country'], ['United States', 'Canada'], true) ? 'LETTER' : 'A4';
$pdf = new ClientExportPdf('P', 'mm', $format, true, 'UTF-8', false);
$pdf->SetCreator('ITFlow');
$pdf->SetAuthor($company['company_name']);
$pdf->SetTitle($client['name'] . ' - IT Documentation');
$pdf->SetSubject('IT Documentation');
$pdf->SetMargins(16, 20, 16);
$pdf->SetHeaderMargin(8);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(true, 18);
$pdf->setImageScale(1.6);
$pdf->setFontSubsetting(true);
$pdf->running_title = $client['name'];
$pdf->running_footer = trim($company['company_name'] . ' · Confidential · ' . date('M j, Y'), ' ·');
if ($options['secrets']) {
// Readable and printable with the password, not editable
$pdf->SetProtection(['modify', 'annot-forms', 'fill-forms', 'assemble'], $options['password'], bin2hex(random_bytes(16)), 3);
}
$margins = $pdf->getMargins();
$width = $pdf->getPageWidth() - $margins['left'] - $margins['right'];
// By reference: a rolled-back document swaps the object out from under them
$write = function ($html) use (&$pdf) {
$pdf->SetFont('dejavusans', '', 8.5);
$pdf->SetTextColor(33, 37, 41);
$pdf->writeHTML($html, true, false, true, false, '');
};
$chapter = function ($title, $subtitle = '', $level = 0, $new_page = false, $size = null) use (&$pdf, $width) {
// A heading near the foot of a page goes over to the next with what follows it
if ($new_page || $pdf->GetY() > $pdf->getPageHeight() - 70) {
$pdf->AddPage();
} elseif ($pdf->GetY() > 30) {
$pdf->Ln($level ? 3 : 6);
}
$pdf->Bookmark($title, $level, 0, '', $level ? '' : 'B', [33, 37, 41]);
$size = $size ?? ($level ? 11 : 15);
$pdf->SetFont('dejavusans', 'B', $size);
$pdf->SetTextColor(33, 37, 41);
$pdf->MultiCell($width, $size > 12 ? 8 : 6, $title, 0, 'L', false, 1);
if (!$level) {
$pdf->SetDrawColor(13, 110, 253);
$pdf->SetLineWidth(0.6);
$pdf->Line($pdf->GetX(), $pdf->GetY(), $pdf->GetX() + 18, $pdf->GetY());
$pdf->Ln(1.5);
}
if ($subtitle !== '') {
$pdf->SetFont('dejavusans', '', 8);
$pdf->SetTextColor(108, 117, 125);
$pdf->MultiCell($width, 4, $subtitle, 0, 'L', false, 1);
}
$pdf->Ln(1.5);
};
$count = function ($n, $one, $many = null) {
return $n . ' ' . ($n === 1 ? $one : ($many ?? $one . 's'));
};
/*
* The cover
*/
$pdf->AddPage();
$logo = $company['company_logo'] ? realpath(__DIR__ . '/../uploads/settings/' . basename($company['company_logo'])) : false;
if ($logo && is_file($logo) && @getimagesize($logo)) {
try {
$pdf->Image($logo, $margins['left'], 22, 0, 16, '', '', '', true, 300, '', false, false, 0, 'L');
} catch (Exception $exception) {
// A logo TCPDF cannot read leaves the cover without one
}
}
$pdf->SetFillColor(13, 110, 253);
$pdf->Rect($margins['left'], 78, 22, 1.6, 'F');
$pdf->SetY(86);
$pdf->SetFont('dejavusans', '', 12);
$pdf->SetTextColor(108, 117, 125);
$pdf->Cell($width, 7, 'IT Documentation', 0, 1, 'L');
$pdf->SetFont('dejavusans', 'B', 26);
$pdf->SetTextColor(33, 37, 41);
$pdf->MultiCell($width, 12, $client['name'], 0, 'L', false, 1);
$pdf->Ln(2);
$pdf->SetFont('dejavusans', '', 10);
$pdf->SetTextColor(73, 80, 87);
$pdf->MultiCell($width, 5, 'Prepared ' . date('M j, Y') . ' by ' . stripslashes((string) $session_name) . ($company['company_name'] ? ', ' . $company['company_name'] : ''), 0, 'L', false, 1);
$included = array_map(function ($key) use ($sections) { return lcfirst($sections[$key]['label']); }, $options['sections']);
$about = 'This document records ' . $client['name'] . "'s IT environment as documented on " . date('M j, Y') . ': the client details'
. ($included ? ', ' . implode(', ', array_slice($included, 0, -1)) . (count($included) > 1 ? ' and ' : '') . end($included) : '') . '.';
$pdf->SetY(150);
$pdf->SetFont('dejavusans', '', 9);
$pdf->SetTextColor(73, 80, 87);
$pdf->MultiCell($width, 5, $about, 0, 'L', false, 1);
$pdf->Ln(3);
$pdf->SetFont('dejavusans', 'B', 9);
$pdf->SetTextColor($options['secrets'] ? 176 : 73, $options['secrets'] ? 42 : 80, $options['secrets'] ? 55 : 87);
$pdf->MultiCell($width, 5, $options['secrets']
? 'Confidential - this copy includes passwords. Keep it somewhere secure and destroy printed copies when they are no longer needed.'
: 'Confidential - store it securely and share it only with people who look after these systems.', 0, 'L', false, 1);
$contact_lines = array_filter([$company['company_name'], clientExportPhone($company['company_phone'], $company['company_phone_country_code']), $company['company_email'], $company['company_website']]);
$pdf->SetY($pdf->getPageHeight() - 46);
$pdf->SetDrawColor(222, 226, 230);
$pdf->SetLineWidth(0.2);
$pdf->Line($margins['left'], $pdf->GetY(), $pdf->getPageWidth() - $margins['right'], $pdf->GetY());
$pdf->Ln(3);
$pdf->SetFont('dejavusans', '', 8.5);
$pdf->SetTextColor(73, 80, 87);
$pdf->MultiCell($width, 4.5, implode("\n", $contact_lines), 0, 'L', false, 1);
if (!$config_whitelabel_enabled) {
$pdf->SetFont('dejavusans', '', 7);
$pdf->SetTextColor(173, 181, 189);
$pdf->Cell($width, 4, 'Powered by ITFlow', 0, 1, 'R');
}
/*
* Overview
*/
$pdf->AddPage();
$contacts = $has('contacts') ? $data('contacts') : [];
$locations = $has('locations') ? $data('locations') : [];
$primary_location = $locations[0] ?? null;
$chapter('Overview');
$write(clientExportPdfFacts([
'Client' => '' . $e($client['name']) . '',
'Industry' => $e($client['industry'] ?? ''),
'Website' => $e($client['website'] ?? ''),
'Main address' => $primary_location ? $e(formatAddress($primary_location['address'], $primary_location['city'], $primary_location['state'], $primary_location['zip'], $primary_location['country'])) : '',
'Main phone' => $primary_location ? $e($primary_location['phone']) : '',
'Client since' => $e(clientExportShowDate($client['created'] ?? '')),
]));
$key_contacts = array_values(array_filter($contacts, function ($c) {
return $c['primary'] === 'Yes' || $c['billing'] === 'Yes' || $c['technical'] === 'Yes' || $c['important'] === 'Yes';
}));
if ($key_contacts) {
$chapter('Key contacts', '', 1);
$write(clientExportPdfTable(['Name' => 24, 'Role' => 16, 'Email' => 30, 'Phone' => 15, 'Mobile' => 15], array_map(function ($c) use ($e) {
$roles = array_keys(array_filter(['Primary' => $c['primary'] === 'Yes', 'Billing' => $c['billing'] === 'Yes', 'Technical' => $c['technical'] === 'Yes', 'Important' => $c['important'] === 'Yes']));
return ['' . $e($c['name']) . '' . clientExportPdfSub($c['title']), $e(implode(', ', $roles)), $e($c['email']), $e($c['phone']), $e($c['mobile'])];
}, $key_contacts)));
}
// What the document holds, at a glance
$glance = [];
$tally = ['contacts' => ['contacts', 'contact'], 'locations' => ['locations', 'location'], 'vendors' => ['vendors', 'vendor'], 'networks' => ['networks', 'network'],
'assets' => ['assets', 'asset'], 'racks' => ['racks', 'rack'], 'software' => ['licenses', 'license'], 'domains' => ['domains', 'domain'],
'certificates' => ['certificates', 'certificate'], 'services' => ['services', 'service'], 'credentials' => ['credentials', 'credential'],
'documents' => ['documents', 'document'], 'files' => ['files', 'file']];
foreach ($tally as $section => [$dataset, $noun]) {
if ($has($section)) {
$glance[] = [$e($sections[$section]['label']), $e($count(count($data($dataset)), $noun))];
}
}
if ($glance) {
$chapter('In this document', '', 1);
$write(clientExportPdfTable(['Section' => 50, 'Records' => 50], $glance));
}
$slas = $data('slas');
if ($slas) {
$chapter('Service levels', 'Targets run in business hours.', 1);
$minutes = function ($m) {
$m = intval($m);
return $m >= 60 ? round($m / 60, 1) . ' h' : $m . 'm';
};
$write(clientExportPdfTable(['Priority' => 20, 'SLA' => 40, 'First reply within' => 20, 'Resolved within' => 20], array_map(function ($s) use ($e, $minutes) {
return [$e($s['priority']), $e($s['sla']), $e($minutes($s['response_minutes'])), $e($minutes($s['resolution_minutes']))];
}, $slas)));
}
$support = array_filter(['Company' => $e($company['company_name']), 'Phone' => $e(clientExportPhone($company['company_phone'], $company['company_phone_country_code'])),
'Email' => $e($company['company_email']), 'Website' => $e($company['company_website'])]);
if ($support) {
$chapter('Getting support', '', 1);
$write(clientExportPdfFacts($support));
}
/*
* Contacts
*/
if ($has('contacts') && $contacts) {
$chapter('Contacts', $count(count($contacts), 'contact'), 0, true);
$write(clientExportPdfTable(['Name' => 24, 'Email' => 25, 'Phone' => 17, 'Mobile' => 15, 'Location' => 19], array_map(function ($c) use ($e) {
$roles = implode(', ', array_keys(array_filter(['Primary' => $c['primary'] === 'Yes', 'Billing' => $c['billing'] === 'Yes', 'Technical' => $c['technical'] === 'Yes'])));
return ['' . $e($c['name']) . '' . clientExportPdfSub(trim($c['title'] . ($c['department'] ? ' · ' . $c['department'] : ''), ' ·')) . clientExportPdfSub($roles),
$e($c['email']), $e($c['phone']), $e($c['mobile']), $e($c['location'])];
}, $contacts)));
}
/*
* Locations
*/
if ($has('locations') && $locations) {
$chapter('Locations', $count(count($locations), 'location'), 0, true);
foreach ($locations as $location) {
$chapter($location['name'] . ($location['primary'] === 'Yes' ? ' (primary)' : ''), $location['description'], 1);
$write(clientExportPdfFacts([
'Address' => $e(formatAddress($location['address'], $location['city'], $location['state'], $location['zip'], $location['country'])),
'Phone' => $e($location['phone']), 'Fax' => $e($location['fax']), 'Hours' => $e($location['hours']), 'Contact' => $e($location['contact']), 'Notes' => $e($location['notes']),
]));
}
}
/*
* Networks
*/
$networks = $has('networks') ? $data('networks') : [];
if ($networks) {
$chapter('Networks', $count(count($networks), 'network'), 0, true);
$write(clientExportPdfTable(['Network' => 22, 'Address' => 20, 'Gateway' => 14, 'DNS' => 16, 'DHCP range' => 16, 'Location' => 12], array_map(function ($n) use ($e) {
return ['' . $e($n['name']) . '' . clientExportPdfSub(trim($n['type'] . ($n['vlan'] !== '' ? ' · VLAN ' . $n['vlan'] : '') . ($n['provider'] ? ' · ' . $n['provider'] : ''), ' ·')),
$e($n['network']) . clientExportPdfSub($n['subnet']), $e($n['gateway']), $e(trim($n['primary_dns'] . "\n" . $n['secondary_dns'])), $e($n['dhcp_range']), $e($n['location'])];
}, $networks)));
$addresses = [];
foreach ($data('ip_addresses') as $ip) {
$addresses[$ip['network']][] = $ip;
}
foreach ($networks as $network) {
if (!empty($addresses[$network['name']])) {
$chapter($network['name'] . ' - addresses', '', 1);
$write(clientExportPdfTable(['Address' => 16, 'Type' => 13, 'Hostname' => 20, 'MAC address' => 19, 'Description' => 32], array_map(function ($ip) use ($e) {
return [$e($ip['address']), $e(ucfirst((string) $ip['type'])), $e($ip['hostname']), $e($ip['mac']), $e($ip['description'])];
}, $addresses[$network['name']])));
}
}
}
/*
* Assets, by what they are
*/
$assets = $has('assets') ? $data('assets') : [];
if ($assets) {
$chapter('Assets', $count(count($assets), 'asset') . ' in use', 0, true);
// By the type's group (assetTypes() - your own types too, functions/asset_type.php)
$families = [
'Servers and storage' => assetTypesInGroup('server', 'virtual'),
'Network equipment' => assetTypesInGroup('network'),
'Power' => assetTypesInGroup('power'),
'Workstations' => assetTypesInGroup('workstation'),
'Phones and mobile devices' => assetTypesInGroup('mobile'),
];
$placed = [];
foreach ($families as $family => $types) {
$placed[$family] = array_values(array_filter($assets, function ($a) use ($types) { return in_array($a['type'], $types, true); }));
}
$placed['Printers and other devices'] = array_values(array_filter($assets, function ($a) use ($families) {
return !in_array($a['type'], array_merge(...array_values($families)), true);
}));
$warranty = function ($date) {
if ($date === '') {
return '';
}
$expired = $date < date('Y-m-d');
return '' . ($expired ? 'Ended ' : '') . clientExportShowDate($date) . '';
};
foreach ($placed as $family => $list) {
if (!$list) {
continue;
}
$chapter($family, $count(count($list), 'device'), 1);
$user_facing = in_array($family, ['Workstations', 'Phones and mobile devices', 'Printers and other devices'], true);
$write(clientExportPdfTable(
['Name' => 19, 'Make and model' => 19, 'Serial' => 14, ($family === 'Network equipment' ? 'Firmware' : 'OS') => 14, ($user_facing ? 'Used by' : 'IP address') => 13, 'Location' => 11, 'Warranty' => 10],
array_map(function ($a) use ($e, $warranty, $user_facing) {
return ['' . $e($a['name']) . '' . clientExportPdfSub($a['type'] . ($a['status'] && $a['status'] !== 'Deployed' ? ' · ' . $a['status'] : '')),
$e(trim($a['make'] . ' ' . $a['model'])), $e($a['serial']), $e($a['os']), $e($user_facing ? $a['used_by'] : $a['ip']),
$e($a['location']) . clientExportPdfSub($a['physical_location']), $warranty($a['warranty_expire'])];
}, $list)
));
}
}
/*
* Racks
*/
$racks = $has('racks') ? $data('racks') : [];
if ($racks) {
$chapter('Racks', $count(count($racks), 'rack'), 0, true);
$units = [];
foreach ($data('rack_units') as $unit) {
$units[$unit['rack']][] = $unit;
}
foreach ($racks as $rack) {
$chapter($rack['name'], trim(implode(' · ', array_filter([$rack['units'] ? $rack['units'] . 'U' : '', $rack['model'], $rack['location'], $rack['physical_location']]))), 1);
$list = $units[$rack['name']] ?? [];
usort($list, function ($a, $b) { return intval($b['from_unit']) <=> intval($a['from_unit']); });
$write($list ? clientExportPdfTable(['Units' => 12, 'Face' => 10, 'Device' => 38, 'Type' => 16, 'Power' => 10, 'Notes' => 14], array_map(function ($u) use ($e) {
$span = (intval($u['from_unit']) === intval($u['to_unit']) ? 'U' . $u['from_unit'] : 'U' . $u['from_unit'] . '-' . $u['to_unit']) . ($u['holder'] !== '' ? ', slot ' . $u['slot'] : '');
return [$e($span), $e($u['face']), '' . $e($u['device']) . '', $e($u['type']), $e($u['power_watts'] ? $u['power_watts'] . ' W' : ''), $e($u['notes'])];
}, $list)) : 'Nothing documented in this rack.');
}
}
/*
* Licenses
*/
$licenses = $has('software') ? $data('licenses') : [];
if ($licenses) {
$chapter('Licenses', $count(count($licenses), 'license'), 0, true);
$keys = [];
foreach ($data('license_keys') as $key) {
$keys[$key['license']][] = $key['key'] . ($key['assigned_to'] !== '' ? ' (' . $key['assigned_to'] . ')' : '');
}
$write(clientExportPdfTable(['License' => 26, 'Type' => 15, 'Keys' => 24, 'Seats' => 9, 'Renews' => 12, 'Vendor' => 14], array_map(function ($l) use ($e, $keys) {
$seats = $l['seats'] !== '' ? $l['seats_used'] . ' of ' . $l['seats'] : ($l['seats_used'] ? $l['seats_used'] . ' in use' : '');
$license_keys = array_filter(array_merge([$l['key']], $keys[$l['name']] ?? []), 'strlen');
return ['' . $e(trim($l['name'] . ' ' . $l['version'])) . '' . clientExportPdfSub($l['description']), $e($l['type']) . clientExportPdfSub($l['license_type']),
$license_keys ? '' . $e(implode("\n", $license_keys)) . '' : '', $e($seats),
$e(clientExportShowDate($l['expires'])), $e($l['vendor'])];
}, $licenses)));
$holders = [];
foreach ($data('license_seats') as $seat) {
$holders[$seat['license']][$seat['seat']][] = $seat['name'];
}
if ($holders) {
$chapter('Who has each license', '', 1);
$write(clientExportPdfTable(['License' => 26, 'Devices' => 37, 'Users' => 37], array_map(function ($license, $seats) use ($e) {
return ['' . $e($license) . '', $e(implode(', ', $seats['Device'] ?? [])), $e(implode(', ', $seats['User'] ?? []))];
}, array_keys($holders), $holders)));
}
}
/*
* Domains and certificates
*/
$domains = $has('domains') ? $data('domains') : [];
if ($domains) {
$chapter('Domains', $count(count($domains), 'domain'), 0, true);
$write(clientExportPdfTable(['Domain' => 22, 'Expires' => 14, 'Registrar' => 16, 'DNS host' => 16, 'Web host' => 16, 'Mail host' => 16], array_map(function ($d) use ($e) {
return ['' . $e($d['name']) . '' . clientExportPdfSub($d['description']), $e(clientExportShowDate($d['expires'])) . clientExportPdfSub($d['auto_renew'] === 'Yes' ? 'Auto-renews' : ''),
$e($d['registrar']), $e($d['dns_host']), $e($d['web_host']), $e($d['mail_host'])];
}, $domains)));
$chapter('DNS', 'As last looked up.', 1);
$write(clientExportPdfTable(['Domain' => 22, 'Name servers' => 30, 'Mail servers' => 30, 'A record' => 18], array_map(function ($d) use ($e) {
return ['' . $e($d['name']) . '', $e($d['name_servers']), $e($d['mail_servers']), $e($d['ip'])];
}, $domains)));
}
$certificates = $has('certificates') ? $data('certificates') : [];
if ($certificates) {
$chapter('Certificates', $count(count($certificates), 'certificate'), 0, !$domains);
$write(clientExportPdfTable(['Certificate' => 26, 'Host' => 22, 'Issued by' => 20, 'Expires' => 14, 'Last check' => 18], array_map(function ($c) use ($e) {
return ['' . $e($c['name']) . '', $e($c['host']), $e($c['issued_by']), $e(clientExportShowDate($c['expires'])), $e($c['check']) . clientExportPdfSub(clientExportShowDate($c['checked']))];
}, $certificates)));
}
/*
* Services - what each one is, what it runs on and needs, who supports it
*/
$services = $has('services') ? $data('services') : [];
if ($services) {
$chapter('Services', $count(count($services), 'service') . ', most important first', 0, true);
$depends = [];
foreach ($data('links') as $link) {
if ($link['type'] === 'Service') {
$depends[$link['name']][$link['linked_type']][] = $link['linked_name'];
}
}
foreach ($services as $service) {
$chapter($service['name'], trim(implode(' · ', array_filter([$service['importance'] ? $service['importance'] . ' importance' : '', $service['category']]))), 1);
$on = $depends[$service['name']] ?? [];
$write(clientExportPdfFacts([
'What it is' => $e($service['description']),
'Runs on' => $e(implode(', ', $on['Asset'] ?? [])),
'Domains' => $e(implode(', ', $on['Domain'] ?? [])),
'Certificates' => $e(implode(', ', $on['Certificate'] ?? [])),
'Logins' => $e(implode(', ', $on['Credential'] ?? [])),
'Supported by' => $e(implode(', ', array_merge($on['Vendor'] ?? [], $on['Contact'] ?? []))),
'Documents' => $e(implode(', ', $on['Document'] ?? [])),
'Backup' => $e($service['backup']),
'Notes' => $e($service['notes']),
'Next review' => $e(clientExportShowDate($service['review_due'])),
]));
}
}
/*
* Vendors
*/
$vendors = $has('vendors') ? $data('vendors') : [];
if ($vendors) {
$chapter('Vendors', $count(count($vendors), 'vendor'), 0, true);
$write(clientExportPdfTable(['Vendor' => 22, 'Account' => 15, 'Support' => 22, 'Hours and SLA' => 18, 'Account manager' => 23], array_map(function ($v) use ($e) {
return ['' . $e($v['name']) . '' . clientExportPdfSub($v['description']), $e($v['account_number']) . clientExportPdfSub($v['code'] !== '' ? 'PIN ' . $v['code'] : ''),
$e(trim($v['phone'] . "\n" . $v['email'] . "\n" . $v['website'])), $e(trim($v['hours'] . "\n" . $v['sla'])),
$e(trim($v['contact_name'] . "\n" . $v['contact_phone'] . "\n" . $v['contact_email']))];
}, $vendors)));
}
/*
* Credentials - passwords only when asked for, and then the PDF is locked
*/
$credentials = $has('credentials') ? $data('credentials') : [];
if ($credentials) {
$chapter('Credentials', $count(count($credentials), 'credential') . ($options['secrets'] ? ' - with passwords' : ' - passwords are not included'), 0, true);
$mono = function ($value) use ($e) {
return $value === '' ? '' : '' . $e($value) . '';
};
if ($options['secrets']) {
$write(clientExportPdfTable(['Name' => 24, 'Username' => 20, 'Password' => 20, '2FA secret' => 14, 'Link' => 22], array_map(function ($c) use ($e, $mono) {
return ['' . $e($c['name']) . '' . clientExportPdfSub($c['description']), $mono($c['username']), $mono($c['password']),
$c['otp_secret'] !== '' ? $mono($c['otp_secret']) : $e($c['has_2fa'] === 'Yes' ? 'Yes' : ''), $e($c['uri'])];
}, $credentials)));
} else {
$write(clientExportPdfTable(['Name' => 30, 'Username' => 26, '2FA' => 8, 'Link' => 36], array_map(function ($c) use ($e, $mono) {
return ['' . $e($c['name']) . '' . clientExportPdfSub($c['description']), $mono($c['username']), $e($c['has_2fa'] === 'Yes' ? 'Yes' : ''), $e($c['uri'])];
}, $credentials)));
}
}
/*
* Files - listed; the files themselves are in the full export
*/
$files = $has('files') ? $data('files') : [];
if ($files) {
$chapter('Files', $count(count($files), 'file') . ' on record. The files themselves are in the full export.', 0, true);
$write(clientExportPdfTable(['Name' => 36, 'Folder' => 26, 'Type' => 10, 'Size' => 12, 'Uploaded' => 16], array_map(function ($f) use ($e) {
return ['' . $e($f['name']) . '' . clientExportPdfSub($f['description']), $e($f['folder']), $e($f['type']), $e(formatBytes($f['size'], 1)), $e(clientExportShowDate($f['created']))];
}, $files)));
}
/*
* Documents - each one in full, on its own pages
*/
$documents = $has('documents') ? $data('documents') : [];
if ($documents) {
$chapter('Documents', $count(count($documents), 'document') . ', each on the pages that follow', 0, true);
$write(clientExportPdfTable(['Document' => 46, 'Folder' => 30, 'Updated' => 24], array_map(function ($d) use ($e) {
return ['' . $e($d['name']) . '' . clientExportPdfSub($d['description']), $e($d['folder']), $e(clientExportShowDate($d['updated'] ?: $d['created']))];
}, $documents)));
foreach ($documents as $document) {
$content = clientExportDocumentContent($document['id'], $client_id);
$chapter($document['name'], trim(implode(' · ', array_filter([$document['folder'], 'Updated ' . clientExportShowDate($document['updated'] ?: $document['created'])])), ' ·'), 1, true, 15);
if ($document['description'] !== '') {
$write('
' . $e($document['description']) . '
');
}
// One document TCPDF cannot draw goes in as plain text rather than ending the PDF
$pdf->startTransaction();
try {
$write(clientExportPdfDocumentHtml($content, $document['id']));
$pdf->commitTransaction();
} catch (Exception $exception) {
$pdf = $pdf->rollbackTransaction();
$write('
This document has formatting the PDF cannot show, so here is its text.
data/csv - every record as a spreadsheet (opens in Excel, Numbers or LibreOffice)
'
. '
data/json - the same records for importing into another system, described in data/export.json
'
. ($document_pages ? '
documents - ' . count($document_pages) . ' documents as web pages, in their folders
' : '')
. (isset($rows['files']) ? '
files - ' . count(array_filter(array_column($rows['files'], 'path'))) . ' files, in their folders
' : '')
. ($ticket_pages ? '
tickets - ' . count($ticket_pages) . ' ticket conversations with their attachments
' : '')
. ($photos ? '
photos - ' . $photos . ' photos of contacts, assets, locations and racks
' : '')
. '
Included: client details, ' . escapeHtml(implode(', ', array_map(function ($key) use ($sections) { return lcfirst($sections[$key]['label']); }, $options['sections'])))
. '. ' . ($options['archived'] ? 'Archived records are included and dated in their Archived column.' : 'Archived records are left out.')
. ($options['secrets'] ? '' : (in_array('credentials', $options['sections'], true) ? ' Passwords and 2FA secrets are not included.' : '')) . '
';
$readme .= '
Records
Table
Rows
Download
';
foreach ($manifest_sets as $set) {
$readme .= '
';
}
$add_string('README.html', clientExportHtmlPage($client['name'] . ' - Client data export', $readme, null));
$add_string('data/export.json', json_encode([
'exported_at' => date('c'),
'exported_by' => stripslashes((string) $session_name),
'itflow_version' => APP_VERSION,
'client' => clientExportJsonRows('client', [$client])[0],
'sections' => array_merge(['client'], $options['sections']),
'includes_archived' => $options['archived'],
'includes_secrets' => $options['secrets'],
'includes_internal_notes' => $options['internal'],
'datasets' => $manifest_sets,
'not_included' => $missing,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
$zip_open = false;
if ($failed) {
$zip->close();
@unlink($zip_path);
$error = "This server's zip library cannot encrypt archives (libzip 1.2 or newer is needed), so the export was not made. Export it without passwords instead.";
return false;
}
if (!$zip->close()) {
@unlink($zip_path);
$error = 'The export could not be finished - the server may be out of disk space.';
return false;
}
return $zip_path;
}
/*
* ---------- the export window and the download ----------
*/
/** How many records each section holds now (archived left out) - shown beside its box. */
function clientExportCounts($client_id) {
global $mysqli;
$c = intval($client_id);
$queries = [
'contacts' => "SELECT COUNT(*) FROM contacts WHERE contact_client_id = $c AND contact_archived_at IS NULL",
'locations' => "SELECT COUNT(*) FROM locations WHERE location_client_id = $c AND location_archived_at IS NULL",
'vendors' => "SELECT COUNT(*) FROM vendors WHERE vendor_client_id = $c AND vendor_archived_at IS NULL",
'networks' => "SELECT COUNT(*) FROM networks WHERE network_client_id = $c AND network_archived_at IS NULL",
'assets' => "SELECT COUNT(*) FROM assets WHERE asset_client_id = $c AND asset_archived_at IS NULL",
'racks' => "SELECT COUNT(*) FROM racks WHERE rack_client_id = $c AND rack_archived_at IS NULL",
'software' => "SELECT COUNT(*) FROM software WHERE software_client_id = $c AND software_archived_at IS NULL",
'domains' => "SELECT COUNT(*) FROM domains WHERE domain_client_id = $c AND domain_archived_at IS NULL",
'certificates' => "SELECT COUNT(*) FROM certificates WHERE certificate_client_id = $c AND certificate_archived_at IS NULL",
'services' => "SELECT COUNT(*) FROM services WHERE service_client_id = $c AND service_archived_at IS NULL",
'credentials' => "SELECT COUNT(*) FROM credentials WHERE credential_client_id = $c AND credential_archived_at IS NULL",
'documents' => "SELECT COUNT(*) FROM documents WHERE document_client_id = $c AND document_archived_at IS NULL",
'files' => "SELECT COUNT(*) FROM files WHERE file_client_id = $c AND file_archived_at IS NULL",
'tickets' => "SELECT COUNT(*) FROM tickets WHERE ticket_client_id = $c AND ticket_archived_at IS NULL",
'billing' => "SELECT COUNT(*) FROM invoices WHERE invoice_client_id = $c AND invoice_archived_at IS NULL",
];
$counts = [];
foreach ($queries as $section => $query) {
$counts[$section] = intval(mysqli_fetch_row(mysqli_query($mysqli, $query))[0] ?? 0);
}
return $counts;
}
/**
* The section boxes for the export window, two columns, each with how many
* records it holds. $kind 'pdf' offers only the sections the PDF has a
* chapter for. $id_prefix keeps the boxes' ids apart in another window;
* $picked, the sections to start ticked (otherwise the defaults).
*/
function clientExportSectionPicker($client_id, $kind, $id_prefix = 'clientExport', ?array $picked = null) {
$counts = clientExportCounts($client_id);
$nouns = ['billing' => 'invoice', 'software' => 'license'];
$html = '