Racks makeover: rack page with to-scale front/rear elevation (click an empty U to add), front/rear mounting and full/half depth, non-asset items (patch panel, cable management, shelf, PDU, UPS, KVM, blanking panel), item edit/move, U and power capacity with largest free gap, front/rear photos, U1 top/bottom numbering, print view, Not racked yet list, rack cards with mini elevation and usage, Racks under All Client Docs, rack position on asset views. Fixes model wiped on every rack save, archive denied for non-admins, item edits taking the rack from the form instead of the item, no bounds check on positions, orphaned rack items on asset delete/transfer and orphaned racks on client delete. DB 2.8.0

This commit is contained in:
johnnyq
2026-10-14 15:14:11 -04:00
parent cce7b15a03
commit 2d6e40bcf6
24 changed files with 2506 additions and 796 deletions

View File

@@ -0,0 +1,55 @@
<?php
/*
* ITFlow - Database update to version 2.8.0 (from 2.7.9)
* Included by admin/database_updates.php - do not access directly
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
// Racks: unit numbering direction, a power budget and a photo of the back
mysqli_query($mysqli, "ALTER TABLE `racks`
ADD COLUMN `rack_units_descending` tinyint(1) NOT NULL DEFAULT 0 AFTER `rack_units`,
ADD COLUMN `rack_power_capacity` int(11) DEFAULT NULL AFTER `rack_units_descending`,
ADD COLUMN `rack_photo_rear` varchar(200) DEFAULT NULL AFTER `rack_photo`
");
// Rack units: which face an item is mounted on and whether it takes the full depth
// (existing items default to front + full depth, which is exactly how the old
// single-face overlap check treated them), what kind of item an unlinked one is,
// its power draw and a short note. The asset key backs the "racked in" lookup on
// the asset page and the clean-up when an asset is deleted or transferred.
mysqli_query($mysqli, "ALTER TABLE `rack_units`
ADD COLUMN `unit_face` varchar(10) NOT NULL DEFAULT 'front' AFTER `unit_device`,
ADD COLUMN `unit_full_depth` tinyint(1) NOT NULL DEFAULT 1 AFTER `unit_face`,
ADD COLUMN `unit_type` varchar(50) DEFAULT NULL AFTER `unit_full_depth`,
ADD COLUMN `unit_power_watts` int(11) DEFAULT NULL AFTER `unit_type`,
ADD COLUMN `unit_notes` varchar(255) DEFAULT NULL AFTER `unit_power_watts`,
ADD KEY `unit_asset_id` (`unit_asset_id`)
");
// Unlinked items were stored with an asset id of 0 rather than NULL - normalise,
// so "linked to an asset" is one test everywhere
mysqli_query($mysqli, "UPDATE `rack_units` SET `unit_asset_id` = NULL WHERE `unit_asset_id` = 0");
// Items whose asset was deleted were left behind pointing at nothing. Keep the
// slot (someone racked something there) but drop the dead link.
mysqli_query($mysqli, "UPDATE `rack_units` LEFT JOIN `assets` ON `asset_id` = `unit_asset_id`
SET `unit_asset_id` = NULL, `unit_device` = COALESCE(NULLIF(`unit_device`, ''), 'Removed asset')
WHERE `unit_asset_id` IS NOT NULL AND `asset_id` IS NULL
");
// Give the unlinked items already in racks a type where their name makes it
// obvious, so a patch panel draws as one instead of as a generic device
$rack_unit_type_guesses = [
'Patch Panel' => '%patch%panel%',
'Cable Management' => '%cable%manage%',
'Blanking Panel' => '%blank%',
'Shelf' => '%shelf%',
];
foreach ($rack_unit_type_guesses as $rack_unit_type => $rack_unit_pattern) {
mysqli_query($mysqli, "UPDATE `rack_units` SET `unit_type` = '$rack_unit_type'
WHERE `unit_type` IS NULL AND `unit_asset_id` IS NULL AND `unit_device` LIKE '$rack_unit_pattern'
");
}
mysqli_query($mysqli, "UPDATE `rack_units` SET `unit_type` = 'Device' WHERE `unit_type` IS NULL AND `unit_asset_id` IS NULL");

View File

@@ -1678,46 +1678,59 @@ function demoBuildRack($mysqli, $profile, $client_id, $location_id, $assets, $mo
$rack_id = starterInsert($mysqli, 'racks', [
'rack_name' => $profile['abbreviation'] . '-RACK-01',
'rack_description' => 'Main comms rack',
'rack_model' => 'StarTech 12U Wall Mount',
'rack_depth' => 'Full',
'rack_type' => 'Wall Mount',
'rack_model' => 'StarTech 12U Wall Mount Enclosure',
'rack_depth' => '18 in',
'rack_type' => 'Wall-Mount Enclosed',
'rack_units' => 12,
'rack_power_capacity' => 1000,
'rack_physical_location' => 'Server room',
'rack_notes' => 'Keyed alike with the comms cupboard. Spare key is held by the onsite point of contact.',
'rack_notes' => 'Keyed alike with the comms cupboard. Spare key is held by the onsite point of contact. Fed from the 1500VA UPS at the bottom of the rack.',
'rack_location_id' => $location_id,
'rack_client_id' => $client_id,
'rack_created_at' => demoMonthDateTime($months, 6, 15, 0),
]);
$counts['documentation']++;
// Patch panel at the top, then the kit under it
$unit = 12;
starterInsert($mysqli, 'rack_units', [
'unit_start_number' => $unit,
'unit_end_number' => $unit,
'unit_device' => 'Patch panel - 24 port',
'unit_rack_id' => $rack_id,
'unit_created_at' => demoMonthDateTime($months, 6, 15, 5),
]);
$racked_at = demoMonthDateTime($months, 6, 15, 5);
$rack_item = function ($start, $end, $fields) use ($mysqli, $rack_id, $racked_at) {
starterInsert($mysqli, 'rack_units', $fields + [
'unit_start_number' => $start,
'unit_end_number' => $end,
'unit_face' => 'front',
'unit_full_depth' => 1,
'unit_rack_id' => $rack_id,
'unit_created_at' => $racked_at,
]);
};
// Patching at the top, front only - the PDU shares those units at the back
$rack_item(12, 12, ['unit_device' => 'Patch panel - 24 port Cat6', 'unit_type' => 'Patch Panel', 'unit_full_depth' => 0]);
$rack_item(11, 11, ['unit_device' => 'Horizontal cable manager', 'unit_type' => 'Cable Management', 'unit_full_depth' => 0]);
$rack_item(11, 12, ['unit_device' => 'Switched PDU - 8 outlet', 'unit_type' => 'PDU', 'unit_face' => 'rear', 'unit_full_depth' => 0]);
// Then the kit, top down. Firewalls and switches are short-depth; servers are not.
$unit = 11;
foreach ($rackable as $asset) {
$unit--;
if ($unit < 1) {
$height = $asset['type'] === 'Server' ? 2 : 1;
$end = $unit - 1;
$start = $end - ($height - 1);
if ($start < 3) {
break;
}
$height = $asset['type'] === 'Server' ? 2 : 1;
$start = max(1, $unit - ($height - 1));
starterInsert($mysqli, 'rack_units', [
'unit_start_number' => $start,
'unit_end_number' => $unit,
'unit_device' => $asset['name'] . ' - ' . $asset['make'] . ' ' . $asset['model'],
$is_server = $asset['type'] === 'Server';
$is_poe = stripos($asset['model'], 'poe') !== false;
$rack_item($start, $end, [
'unit_device' => '',
'unit_asset_id' => $asset['id'],
'unit_rack_id' => $rack_id,
'unit_created_at' => demoMonthDateTime($months, 6, 15, 5),
'unit_full_depth' => $is_server ? 1 : 0,
'unit_power_watts' => $is_server ? 220 : ($is_poe ? 150 : 35),
]);
$unit = $start;
}
// The UPS everything runs on, at the bottom where the weight belongs
$rack_item(1, 2, ['unit_device' => 'APC Smart-UPS 1500VA 2U', 'unit_type' => 'UPS', 'unit_notes' => 'Battery replaced at install']);
}
// ------------------------------

View File

@@ -101,6 +101,14 @@ if (isset($_GET['asset_id'])) {
$location_name_display = $location_name;
}
// The rack it sits in, if any
$asset_rack = rackPositionForAsset($asset_id);
if ($asset_rack) {
$asset_rack_id = intval($asset_rack['rack_id']);
$asset_rack_name = escapeHtml($asset_rack['rack_name']);
$asset_rack_position = rackPositionLabel($asset_rack['unit_start_number'], $asset_rack['unit_end_number']) . ', ' . ($asset_rack['unit_face'] === 'rear' ? 'rear' : 'front');
}
// Override Tab Title // No Sanitizing needed as this var will opnly be used in the tab title
$page_title = $row['asset_name'];
@@ -365,6 +373,9 @@ if (isset($_GET['asset_id'])) {
<?php if ($location_name) { ?>
<div><i class="fa fa-fw fa-map-marker-alt text-secondary me-2"></i><?= $location_name_display; ?></div>
<?php }
if ($asset_rack) { ?>
<div class="mt-2"><i class="fa fa-fw fa-server text-secondary me-2"></i><a href="rack.php?client_id=<?= $client_id ?>&rack_id=<?= $asset_rack_id ?>"><?= $asset_rack_name ?></a> <span class="text-secondary">&middot; <?= $asset_rack_position ?></span></div>
<?php }
if ($contact_name) { ?>
<div class="mt-2"><i class="fa fa-fw fa-user text-secondary me-2"></i><?= $contact_name_display; ?></div>
<?php }

View File

@@ -19,6 +19,9 @@ $num_credentials = $row['num'];
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('network_id') AS num FROM networks LEFT JOIN clients ON network_client_id = client_id WHERE network_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('network_client_id') . ""));
$num_networks = $row['num'];
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('rack_id') AS num FROM racks LEFT JOIN clients ON rack_client_id = client_id WHERE rack_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('rack_client_id') . ""));
$num_racks = $row['num'];
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('domain_id') AS num FROM domains LEFT JOIN clients ON domain_client_id = client_id WHERE domain_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('domain_client_id') . ""));
$num_domains = $row['num'];
@@ -102,6 +105,19 @@ $num_software = $row['num'];
</a>
</li>
<li class="nav-item">
<a href="racks.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "racks.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-server"></i>
<p>
Racks
<?php
if ($num_racks > 0) { ?>
<span class="right badge text-light"><?= $num_racks ?></span>
<?php } ?>
</p>
</a>
</li>
<li class="nav-header mt-3">WEB & SECURITY</li>
<li class="nav-item">

View File

@@ -27,6 +27,7 @@
'network.php' => 'networks.php',
'project.php' => 'projects.php',
'quote.php' => 'quotes.php',
'rack.php' => 'racks.php',
'recurring_invoice.php' => 'recurring_invoices.php',
'ticket.php' => 'tickets.php',
];
@@ -198,7 +199,7 @@
</li>
<li class="nav-item">
<a href="/agent/racks.php?client_id=<?= $client_id ?>" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "racks.php") { echo "active"; } ?>">
<a href="/agent/racks.php?client_id=<?= $client_id ?>" class="nav-link <?php if (in_array(basename($_SERVER["PHP_SELF"]), ["racks.php", "rack.php"])) { echo "active"; } ?>">
<i class="nav-icon fas fa-server"></i>
<p>
Racks

View File

@@ -0,0 +1,136 @@
<?php
/*
* One face of a rack, drawn to scale - included by agent/rack.php once for the
* front and once for the rear. Expects:
*
* $elevation_face 'front' | 'rear'
* $elevation_items rackUnitView() items for the whole rack
* $elevation_rack_units rack height in U
* $elevation_descending 1 when U1 is at the top
* $elevation_can_edit whether empty U and items open the add/edit modals
* $rack_id, $client_id
*
* A CSS grid with one row per U. Items on this face are placed by grid-row;
* a full-depth item mounted on the OTHER face shows here as a hatched ghost,
* because it fills this face too. Every U nothing fills is an "add here" slot.
*
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
$elevation_taken = [];
$elevation_blocks = [];
foreach ($elevation_items as $elevation_item) {
if (!rackUnitOnFace($elevation_item['face'], $elevation_item['full_depth'], $elevation_face)) {
continue;
}
$elevation_blocks[] = $elevation_item + ['ghost' => $elevation_item['face'] !== $elevation_face];
for ($u = $elevation_item['start']; $u <= $elevation_item['end']; $u++) {
$elevation_taken[$u] = true;
}
}
$elevation_other_face = $elevation_face === 'front' ? 'rear' : 'front';
// Rail numbers top to bottom, in the order the rack is drawn
$elevation_rail = $elevation_descending ? range(1, $elevation_rack_units) : range($elevation_rack_units, 1);
?>
<div class="itflow-rack" style="--rack-rows: <?= $elevation_rack_units ?>" data-rack-face="<?= $elevation_face ?>">
<div class="itflow-rack-cap"><?= ucfirst($elevation_face) ?></div>
<div class="itflow-rack-frame">
<div class="itflow-rack-rail" aria-hidden="true">
<?php foreach ($elevation_rail as $u) { ?>
<span><?= $u ?></span>
<?php } ?>
</div>
<div class="itflow-rack-bay">
<?php
// Empty U first so the items paint over the grid lines
foreach ($elevation_rail as $u) {
if (isset($elevation_taken[$u])) {
continue;
}
$slot_row = rackGridRow($u, $u, $elevation_rack_units, $elevation_descending);
if ($elevation_can_edit) { ?>
<button type="button" class="itflow-rack-slot ajax-modal" style="grid-row: <?= $slot_row ?>"
data-modal-url="modals/rack/rack_device_add.php?id=<?= $rack_id ?>&u=<?= $u ?>&face=<?= $elevation_face ?>"
title="Add something at U<?= $u ?> (<?= $elevation_face ?>)">
<span><i class="fas fa-plus me-1"></i>U<?= $u ?></span>
</button>
<?php } else { ?>
<span class="itflow-rack-slot" style="grid-row: <?= $slot_row ?>"></span>
<?php }
}
foreach ($elevation_blocks as $block) {
$block_row = rackGridRow($block['start'], $block['end'], $elevation_rack_units, $elevation_descending);
$block_classes = "itflow-rack-item itflow-rack-tone-{$block['tone']} itflow-rack-h" . min(3, $block['height']);
if ($block['ghost']) {
$block_classes .= ' is-ghost';
}
if ($block['asset_archived']) {
$block_classes .= ' is-archived';
}
$block_title = $block['name'] . ' - ' . html_entity_decode($block['position']) . ($block['meta'] ? " - {$block['meta']}" : '');
?>
<div class="<?= $block_classes ?>" style="grid-row: <?= $block_row ?> / span <?= $block['height'] ?>">
<?php if ($block['ghost']) { ?>
<div class="itflow-rack-item-body" title="<?= $block_title ?> - mounted on the <?= $elevation_other_face ?>, full depth">
<span class="itflow-rack-item-text">
<span class="itflow-rack-item-name"><?= $block['name'] ?></span>
<span class="itflow-rack-item-meta">Full depth from the <?= $elevation_other_face ?></span>
</span>
</div>
<?php } else {
// An asset opens its asset page; anything else opens its editor
if ($block['asset_id']) {
$block_open = '<a class="itflow-rack-item-body" href="asset.php?client_id=' . $client_id . '&asset_id=' . $block['asset_id'] . '" title="' . $block_title . '">';
$block_close = '</a>';
} elseif ($elevation_can_edit) {
$block_open = '<button type="button" class="itflow-rack-item-body ajax-modal" data-modal-url="modals/rack/rack_device_edit.php?id=' . $block['id'] . '" title="' . $block_title . '">';
$block_close = '</button>';
} else {
$block_open = '<div class="itflow-rack-item-body" title="' . $block_title . '">';
$block_close = '</div>';
}
?>
<?= $block_open ?>
<span class="itflow-rack-item-icon"><i class="fas fa-fw <?= $block['icon'] ?>"></i></span>
<span class="itflow-rack-item-text">
<span class="itflow-rack-item-name"><?= $block['name'] ?></span>
<?php if ($block['meta'] || $block['ip']) { ?>
<span class="itflow-rack-item-meta">
<?= $block['meta'] ?>
<?php if ($block['ip'] && $block['height'] > 1) { ?>
<span class="font-monospace"><?= $block['meta'] ? '&middot; ' : '' ?><?= $block['ip'] ?></span>
<?php } ?>
</span>
<?php } ?>
</span>
<span class="itflow-rack-item-pos"><?= $block['position'] ?></span>
<?= $block_close ?>
<?php if ($elevation_can_edit && $block['asset_id']) { ?>
<button type="button" class="itflow-rack-item-edit ajax-modal" title="Move or edit"
data-modal-url="modals/rack/rack_device_edit.php?id=<?= $block['id'] ?>">
<i class="fas fa-pen"></i>
</button>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
</div>
<div class="itflow-rack-rail" aria-hidden="true">
<?php foreach ($elevation_rail as $u) { ?>
<span><?= $u ?></span>
<?php } ?>
</div>
</div>
</div>

View File

@@ -87,6 +87,14 @@ if ($location_archived_at) {
$location_name_display = $location_name;
}
// The rack it sits in, if any
$asset_rack = rackPositionForAsset($asset_id);
if ($asset_rack) {
$asset_rack_id = intval($asset_rack['rack_id']);
$asset_rack_name = escapeHtml($asset_rack['rack_name']);
$asset_rack_position = rackPositionLabel($asset_rack['unit_start_number'], $asset_rack['unit_end_number']) . ', ' . ($asset_rack['unit_face'] === 'rear' ? 'rear' : 'front');
}
// Tags - many to many relationship
// Tags - functions/tags.php
$asset_tags_display = tagPills('asset', $asset_id, tagsForRecord('asset', $asset_id), "assets.php?client_id=$client_id&");
@@ -393,6 +401,9 @@ ob_start();
<?php if ($location_name) { ?>
<div><i class="fa fa-fw fa-map-marker-alt text-secondary me-2"></i><?= $location_name_display ?></div>
<?php }
if ($asset_rack) { ?>
<div class="mt-2"><i class="fa fa-fw fa-server text-secondary me-2"></i><a href="rack.php?client_id=<?= $client_id ?>&rack_id=<?= $asset_rack_id ?>"><?= $asset_rack_name ?></a> <span class="text-secondary">&middot; <?= $asset_rack_position ?></span></div>
<?php }
if ($contact_name) { ?>
<div class="mt-2"><i class="fa fa-fw fa-user text-secondary me-2"></i><?= $contact_name_display ?></div>
<?php }

View File

@@ -2,8 +2,28 @@
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$client_id = intval($_GET['client_id'] ?? 0);
enforceClientAccess();
// A new rack - the shared form reads these
$rack_name = '';
$rack_type = '';
$rack_units = 0;
$rack_units_descending = 0;
$rack_highest_used_unit = 0;
$rack_model = '';
$rack_depth = '';
$rack_location_id = 0;
$rack_physical_location = '';
$rack_power_capacity = 0;
$rack_description = '';
$rack_photo = '';
$rack_photo_rear = '';
$rack_notes = '';
ob_start();
?>
@@ -17,128 +37,7 @@ ob_start();
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-details">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-notes">Notes</a>
</li>
</ul>
<hr>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-details">
<div class="mb-3">
<label>Type <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<select class="form-select select2" name="type" required>
<option value="">- Type -</option>
<?php
$sql_rack_types_select = mysqli_query($mysqli, "
SELECT category_name, category_color, category_icon FROM categories
WHERE category_type = 'rack_type'
AND category_archived_at IS NULL
ORDER BY category_order ASC, category_name ASC
");
while ($row = mysqli_fetch_assoc($sql_rack_types_select)) {
$rack_type_select = escapeHtml($row['category_name']);
?>
<option<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $rack_type_select ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<input type="text" class="form-control" name="name" placeholder="Rack name" maxlength="200" required autofocus>
</div>
</div>
<div class="mb-3">
<label>Number of Units <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sort-numeric-up-alt"></i></span>
<input type="number" class="form-control" name="units" placeholder="Number of Units" min="1" max="70" required>
</div>
</div>
<div class="mb-3">
<label>Model</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<input type="text" class="form-control" name="make" placeholder="ex StarTech 12U Open Frame" maxlength="200">
</div>
</div>
<div class="mb-3">
<label>Depth</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-ruler"></i></span>
<input type="text" class="form-control" name="depth" placeholder="Rack Depth eg 800 mm or 31.5 Inches" maxlength="50">
</div>
</div>
<div class="mb-3">
<label>Location</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-map-marker-alt"></i></span>
<select class="form-select select2" name="location">
<option value="">- Location -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations WHERE location_archived_at IS NULL AND location_client_id = $client_id ORDER BY location_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$location_id = intval($row['location_id']);
$location_name = escapeHtml($row['location_name']);
?>
<option value="<?= $location_id ?>"><?= $location_name ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Physical Location</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-map-marker-alt"></i></span>
<input type="text" class="form-control" name="physical_location" placeholder="Physical location eg. Floor 2, Closet B" maxlength="200">
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="Description of the rack">
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-notes">
<div class="mb-3">
<label>Upload Photo</label>
<input type="file" class="form-control" name="file" accept="image/*">
</div>
<div class="mb-3">
<textarea class="form-control" rows="8" placeholder="Enter some notes" name="notes"></textarea>
</div>
</div>
</div>
<?php require 'rack_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_rack" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Create</button>

View File

@@ -2,77 +2,58 @@
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$rack_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT rack_client_id, rack_name FROM racks WHERE rack_id = $rack_id LIMIT 1");
$sql = mysqli_query($mysqli, "SELECT rack_client_id, rack_name, rack_units FROM racks WHERE rack_id = $rack_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
echo json_encode(['error' => 'That rack no longer exists.']);
exit;
}
$rack_name = escapeHtml($row['rack_name']);
$rack_units = intval($row['rack_units']);
$client_id = intval($row['rack_client_id']);
enforceClientAccess();
// A new item. Clicking an empty U on the rack page passes where it was.
$unit_id = 0;
$unit_asset_id = 0;
$unit_device = '';
$unit_type = 'Device';
$unit_start = min($rack_units, max(0, intval($_GET['u'] ?? 0)));
$unit_height = 1;
$unit_face = ($_GET['face'] ?? '') === 'rear' ? 'rear' : 'front';
$unit_full_depth = 1;
$unit_power_watts = 0;
$unit_notes = '';
// "Rack it" on the rack page passes the asset - start from what that kind of kit usually is
$unit_asset_id = intval($_GET['asset_id'] ?? 0);
if ($unit_asset_id) {
$preset_asset_type = getFieldById('assets', $unit_asset_id, 'asset_type');
$unit_height = $preset_asset_type === 'Server' ? 2 : 1;
$unit_full_depth = in_array($preset_asset_type, ['Access Point', 'Firewall/Router'], true) ? 0 : 1;
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-server me-2"></i>Adding Device to Rack <strong><?= $rack_name ?></strong></h5>
<h5 class="modal-title"><i class="fa fa-fw fa-plus me-2"></i>Add to <strong><?= $rack_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" enctype="multipart/form-data" autocomplete="off">
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="rack_id" value="<?= $rack_id ?>">
<div class="modal-body">
<div class="mb-3">
<label>Custom Device</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<input type="text" class="form-control" name="name" placeholder="Device Name" maxlength="200">
</div>
</div>
<div class="mb-3">
<label>Or Select a Device</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-desktop"></i></span>
<select class="form-select select2" name="asset">
<option value="">- Select Asset -</option>
<?php
// Fetch IDs of all assets already assigned to any rack
$assigned_assets = [];
$assigned_sql = mysqli_query($mysqli, "SELECT unit_asset_id FROM rack_units");
while ($assigned_row = mysqli_fetch_assoc($assigned_sql)) {
$assigned_assets[] = intval($assigned_row['unit_asset_id']);
}
$assigned_assets_list = implode(',', $assigned_assets);
$assigned_assets_list = empty($assigned_assets_list) ? '0' : $assigned_assets_list;
// Fetch assets not assigned to any rack
$sql_assets = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model FROM assets WHERE asset_archived_at IS NULL AND asset_client_id = $client_id AND asset_id NOT IN ($assigned_assets_list) ORDER BY asset_name ASC");
while ($row = mysqli_fetch_assoc($sql_assets)) {
$asset_id = intval($row['asset_id']);
$asset_name = escapeHtml($row['asset_name']);
?>
<option value="<?= $asset_id ?>"<?= selectOptionAsset($row['asset_type'], trim($row['asset_make'] . ' ' . $row['asset_model'])) ?>><?= $asset_name ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Unit Number Start - End <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sort-numeric-up-alt"></i></span>
<input type="number" class="form-control" name="unit_start" placeholder="Unit Start" min="1" max="<?= $rack_units ?>" required>
<input type="number" class="form-control" name="unit_end" placeholder="Unit End" min="1" max="<?= $rack_units ?>" required>
</div>
</div>
<?php require 'rack_device_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_rack_unit" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Add to Rack</button>

View File

@@ -0,0 +1,65 @@
<?php
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
$unit_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT unit_asset_id, unit_device, unit_end_number, unit_face, unit_full_depth, unit_notes,
unit_power_watts, unit_rack_id, unit_start_number, unit_type, rack_client_id, rack_name, rack_units, asset_name
FROM rack_units
LEFT JOIN racks ON rack_id = unit_rack_id
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_id = $unit_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
echo json_encode(['error' => 'That item is no longer in the rack.']);
exit;
}
$rack_id = intval($row['unit_rack_id']);
$rack_name = escapeHtml($row['rack_name']);
$rack_units = intval($row['rack_units']);
$client_id = intval($row['rack_client_id']);
$unit_asset_id = intval($row['unit_asset_id']);
$unit_device = escapeHtml($row['unit_device']);
$unit_type = $row['unit_type'] ?: 'Device';
$unit_start = intval($row['unit_start_number']);
$unit_height = max(1, intval($row['unit_end_number']) - $unit_start + 1);
$unit_face = $row['unit_face'] === 'rear' ? 'rear' : 'front';
$unit_full_depth = intval($row['unit_full_depth']);
$unit_power_watts = intval($row['unit_power_watts']);
$unit_notes = escapeHtml($row['unit_notes']);
$unit_name = escapeHtml(rackUnitName($row['asset_name'], $row['unit_device'], $row['unit_type']));
enforceClientAccess();
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-edit me-2"></i><?= $unit_name ?> <span class="fw-normal text-white-50">in <?= $rack_name ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="unit_id" value="<?= $unit_id ?>">
<div class="modal-body">
<?php require 'rack_device_form.php'; ?>
</div>
<div class="modal-footer">
<a class="btn btn-link text-danger me-auto confirm-link" href="post.php?remove_rack_unit=<?= $unit_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-minus-circle me-1"></i>Remove from rack
</a>
<button type="submit" name="edit_rack_unit" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,256 @@
<?php
/*
* Rack item form - shared by rack_device_add.php and rack_device_edit.php,
* which load the rack ($rack_id, $rack_units, $client_id) and the item's
* current values ($unit_*, empty for a new one) before including this.
* Should not be accessed directly.
*
* The live position check below is advisory - agent/post/rack.php runs the
* same bounds, overlap and asset checks again on submit.
*/
isset($mysqli) || die("Direct file access is not allowed");
// Everything else in the rack, for the live position check
$rack_other_units = [];
$sql = mysqli_query($mysqli, "SELECT unit_id, unit_device, unit_type, unit_start_number, unit_end_number, unit_face, unit_full_depth, asset_name
FROM rack_units
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_rack_id = $rack_id AND unit_id != $unit_id
ORDER BY unit_start_number");
while ($row = mysqli_fetch_assoc($sql)) {
$rack_other_units[] = [
'start' => intval($row['unit_start_number']),
'end' => intval($row['unit_end_number']),
'face' => $row['unit_face'] === 'rear' ? 'rear' : 'front',
'full' => intval($row['unit_full_depth']) === 1,
'name' => rackUnitName($row['asset_name'], $row['unit_device'], $row['unit_type']),
];
}
// This client's assets that aren't racked anywhere yet (plus the one already
// on this item). An archived asset only stays listed if it's this item's.
$asset_options = [];
$sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model
FROM assets
WHERE asset_client_id = $client_id
AND (asset_id = $unit_asset_id OR (
asset_archived_at IS NULL
AND NOT EXISTS (SELECT 1 FROM rack_units WHERE unit_asset_id = asset_id)
))
ORDER BY FIELD(asset_type, 'Server', 'Switch', 'Firewall/Router', 'Access Point') = 0, asset_type, asset_name");
while ($row = mysqli_fetch_assoc($sql)) {
$asset_options[] = $row;
}
$unit_is_asset = $unit_asset_id > 0 || ($unit_id === 0 && $unit_device === '');
$item_types = rackItemTypes();
?>
<div class="mb-3">
<div class="btn-group w-100" role="group" aria-label="What is going in the rack">
<input type="radio" class="btn-check" name="item_kind" id="rackItemKindAsset" value="asset" <?= $unit_is_asset ? 'checked' : '' ?>>
<label class="btn btn-outline-secondary" for="rackItemKindAsset"><i class="fas fa-fw fa-desktop me-2"></i>An asset</label>
<input type="radio" class="btn-check" name="item_kind" id="rackItemKindOther" value="other" <?= $unit_is_asset ? '' : 'checked' ?>>
<label class="btn btn-outline-secondary" for="rackItemKindOther"><i class="fas fa-fw fa-ethernet me-2"></i>Something else</label>
</div>
</div>
<div class="mb-3" data-rack-kind="asset">
<label class="form-label">Asset <strong class="text-danger">*</strong></label>
<select class="form-select select2" name="asset" id="rackItemAsset">
<option value="">- Select an asset -</option>
<?php foreach ($asset_options as $asset_option) {
$asset_option_id = intval($asset_option['asset_id']);
?>
<option value="<?= $asset_option_id ?>" data-asset-type="<?= escapeHtml($asset_option['asset_type']) ?>" <?php if ($asset_option_id === $unit_asset_id) { echo "selected"; } ?><?= selectOptionAsset($asset_option['asset_type'], trim($asset_option['asset_make'] . ' ' . $asset_option['asset_model'])) ?>><?= escapeHtml($asset_option['asset_name']) ?></option>
<?php } ?>
</select>
<?php if (empty($asset_options)) { ?>
<div class="form-text">Every asset this client has is already racked.</div>
<?php } ?>
</div>
<div class="mb-3" data-rack-kind="other">
<label class="form-label">What is it</label>
<select class="form-select select2" name="type" id="rackItemType">
<?php foreach ($item_types as $item_type => $item_type_style) { ?>
<option value="<?= escapeHtml($item_type) ?>" <?php if ($unit_type === $item_type) { echo "selected"; } ?><?= selectOptionData(['icon' => 'fas ' . $item_type_style['icon']]) ?>><?= escapeHtml($item_type) ?></option>
<?php } ?>
</select>
</div>
<div class="mb-3">
<label class="form-label" for="rackItemName">
<span data-rack-kind="asset">Label <span class="text-secondary fw-normal">(optional, shown under the asset name)</span></span>
<span data-rack-kind="other">Name <strong class="text-danger">*</strong></span>
</label>
<input type="text" class="form-control" name="name" id="rackItemName" maxlength="200" value="<?= $unit_device ?>" placeholder="24-port Cat6 patch panel">
</div>
<div class="row g-3 mb-1">
<div class="col-sm-4">
<label class="form-label" for="rackItemStart">Lowest U <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text">U</span>
<input type="number" class="form-control" name="unit_start" id="rackItemStart" min="1" max="<?= $rack_units ?>" value="<?= $unit_start ?: '' ?>" required>
</div>
</div>
<div class="col-sm-4">
<label class="form-label" for="rackItemHeight">Height <strong class="text-danger">*</strong></label>
<div class="input-group">
<input type="number" class="form-control" name="unit_height" id="rackItemHeight" min="1" max="<?= $rack_units ?>" value="<?= $unit_height ?>" required>
<span class="input-group-text">U</span>
</div>
</div>
<div class="col-sm-4">
<label class="form-label">Mounted on</label>
<div class="btn-group w-100" role="group">
<input type="radio" class="btn-check" name="face" id="rackItemFaceFront" value="front" <?= $unit_face === 'rear' ? '' : 'checked' ?>>
<label class="btn btn-outline-secondary" for="rackItemFaceFront">Front</label>
<input type="radio" class="btn-check" name="face" id="rackItemFaceRear" value="rear" <?= $unit_face === 'rear' ? 'checked' : '' ?>>
<label class="btn btn-outline-secondary" for="rackItemFaceRear">Rear</label>
</div>
</div>
</div>
<div class="form-check form-switch mt-2">
<input class="form-check-input" type="checkbox" name="full_depth" value="1" id="rackItemFullDepth" <?= $unit_full_depth ? 'checked' : '' ?>>
<label class="form-check-label" for="rackItemFullDepth">Full depth <span class="text-secondary">- fills the front and the rear</span></label>
</div>
<div class="itflow-rack-fit small mt-2 mb-3" id="rackItemFit" aria-live="polite"></div>
<div class="row g-3">
<div class="col-sm-5">
<label class="form-label">Power draw</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bolt"></i></span>
<input type="number" class="form-control" name="power_watts" min="0" max="100000" placeholder="350" value="<?= $unit_power_watts ?: '' ?>">
<span class="input-group-text">W</span>
</div>
</div>
<div class="col-sm-7">
<label class="form-label">Notes</label>
<input type="text" class="form-control" name="notes" maxlength="255" placeholder="Rails in the box, PSU A on PDU-A port 3" value="<?= $unit_notes ?>">
</div>
</div>
<script>
(function () {
var others = <?= json_encode($rack_other_units, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
var rackUnits = <?= intval($rack_units) ?>;
var form = document.getElementById('rackItemFit').closest('form');
var start = form.querySelector('#rackItemStart');
var height = form.querySelector('#rackItemHeight');
var fullDepth = form.querySelector('#rackItemFullDepth');
var fit = form.querySelector('#rackItemFit');
var nameInput = form.querySelector('#rackItemName');
var assetSelect = form.querySelector('#rackItemAsset');
var typeSelect = form.querySelector('#rackItemType');
// Things that sit at the front and leave the back free, as a starting point
var halfDepthTypes = ['Patch Panel', 'Cable Management', 'Blanking Panel'];
var halfDepthAssetTypes = ['Access Point', 'Firewall/Router'];
function kind() {
return form.querySelector('input[name="item_kind"]:checked').value;
}
function face() {
return form.querySelector('input[name="face"]:checked').value;
}
function position(s, e) {
return s === e ? 'U' + s : 'U' + s + '–U' + e;
}
function setText(el, icon, cls, text) {
el.className = 'itflow-rack-fit small mt-2 mb-3 ' + cls;
el.textContent = '';
var i = document.createElement('i');
i.className = 'fas fa-fw me-1 ' + icon;
el.appendChild(i);
el.appendChild(document.createTextNode(text));
}
function check() {
var s = parseInt(start.value, 10);
var h = parseInt(height.value, 10);
if (!s || !h) {
fit.textContent = '';
fit.className = 'itflow-rack-fit small mt-2 mb-3';
return;
}
var e = s + h - 1;
if (s < 1 || e > rackUnits) {
setText(fit, 'fa-times-circle', 'text-danger', position(s, e) + " doesn't fit - this rack runs from U1 to U" + rackUnits);
return;
}
var f = face();
var full = fullDepth.checked;
var clash = others.find(function (o) {
return o.start <= e && o.end >= s && (o.full || full || o.face === f);
});
if (clash) {
setText(fit, 'fa-times-circle', 'text-danger', position(s, e) + ' clashes with ' + clash.name + ' (' + position(clash.start, clash.end) + ', ' + (clash.full ? 'full depth' : clash.face) + ')');
} else {
setText(fit, 'fa-check-circle', 'text-success', position(s, e) + ' is free on the ' + (full ? 'front and rear' : f));
}
}
function applyKind() {
var k = kind();
form.querySelectorAll('[data-rack-kind]').forEach(function (el) {
el.classList.toggle('d-none', el.getAttribute('data-rack-kind') !== k);
});
assetSelect.required = k === 'asset';
nameInput.required = k === 'other';
nameInput.placeholder = k === 'asset' ? 'Optional' : '24-port Cat6 patch panel';
}
form.querySelectorAll('input[name="item_kind"]').forEach(function (r) {
r.addEventListener('change', applyKind);
});
[start, height, fullDepth].forEach(function (el) {
el.addEventListener('input', check);
el.addEventListener('change', check);
});
form.querySelectorAll('input[name="face"]').forEach(function (r) {
r.addEventListener('change', check);
});
<?php if ($unit_id === 0) { ?>
// A new item: suggest the depth from what it is. Editing keeps what was saved.
typeSelect.addEventListener('change', function () {
fullDepth.checked = halfDepthTypes.indexOf(typeSelect.value) === -1;
check();
});
assetSelect.addEventListener('change', function () {
var option = assetSelect.options[assetSelect.selectedIndex];
var assetType = option ? option.getAttribute('data-asset-type') : '';
if (assetType) {
fullDepth.checked = halfDepthAssetTypes.indexOf(assetType) === -1;
height.value = assetType === 'Server' && !height.dataset.touched ? 2 : height.value;
check();
}
});
height.addEventListener('input', function () {
height.dataset.touched = '1';
});
<?php } ?>
// On submit, the field for the kind not chosen must not count
form.addEventListener('submit', function () {
if (kind() === 'other') {
assetSelect.value = '';
}
});
applyKind();
check();
})();
</script>

View File

@@ -6,26 +6,35 @@ enforceUserPermission('module_support', 2);
$rack_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT rack_client_id, rack_created_at, rack_depth, rack_description, rack_location_id,
rack_model, rack_name, rack_notes, rack_photo, rack_physical_location, rack_type,
rack_units FROM racks WHERE rack_id = $rack_id LIMIT 1");
$sql = mysqli_query($mysqli, "SELECT rack_client_id, rack_depth, rack_description, rack_location_id,
rack_model, rack_name, rack_notes, rack_photo, rack_photo_rear, rack_physical_location, rack_power_capacity,
rack_type, rack_units, rack_units_descending FROM racks WHERE rack_id = $rack_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
echo json_encode(['error' => 'That rack no longer exists.']);
exit;
}
$rack_name = escapeHtml($row['rack_name']);
$rack_description = escapeHtml($row['rack_description']);
$rack_model = escapeHtml($row['rack_model']);
$rack_depth = escapeHtml($row['rack_depth']);
$rack_type = escapeHtml($row['rack_type']);
$rack_units = intval($row['rack_units']);
$rack_units_descending = intval($row['rack_units_descending']);
$rack_power_capacity = intval($row['rack_power_capacity']);
$rack_photo = escapeHtml($row['rack_photo']);
$rack_photo_rear = escapeHtml($row['rack_photo_rear']);
$rack_physical_location = escapeHtml($row['rack_physical_location']);
$rack_notes = escapeHtml($row['rack_notes']);
$rack_location_id = escapeHtml($row['rack_location_id']);
$rack_created_at = escapeHtml($row['rack_created_at']);
$rack_location_id = intval($row['rack_location_id']);
$client_id = intval($row['rack_client_id']);
enforceClientAccess();
// The rack can't shrink below what's mounted in it - the field's minimum says so
$rack_highest_used_unit = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT MAX(unit_end_number) FROM rack_units WHERE unit_rack_id = $rack_id"))[0]);
ob_start();
?>
@@ -40,134 +49,7 @@ ob_start();
<input type="hidden" name="rack_id" value="<?= $rack_id ?>">
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-rack-details<?= $rack_id ?>">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-rack-notes<?= $rack_id ?>">Notes</a>
</li>
</ul>
<hr>
<div class="tab-content" <?php if (lookupUserPermission('module_support') <= 1) { echo 'inert'; } ?>>
<div class="tab-pane fade show active" id="pills-rack-details<?= $rack_id ?>">
<div class="mb-3">
<label>Type <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<select class="form-select select2" name="type" required>
<option value="">- Type -</option>
<?php
$sql_rack_types_select = mysqli_query($mysqli, "
SELECT category_name, category_color, category_icon FROM categories
WHERE category_type = 'rack_type'
AND category_archived_at IS NULL
ORDER BY category_order ASC, category_name ASC
");
while ($row = mysqli_fetch_assoc($sql_rack_types_select)) {
$rack_type_select = escapeHtml($row['category_name']);
?>
<option <?php if ($rack_type == $rack_type_select) { echo "selected"; } ?><?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>>
<?= $rack_type_select ?>
</option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<input type="text" class="form-control" name="name" placeholder="Rack name" maxlength="200" value="<?= $rack_name ?>" required autofocus>
</div>
</div>
<div class="mb-3">
<label>Number of Units <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sort-numeric-up-alt"></i></span>
<input type="number" class="form-control" name="units" placeholder="Number of Units" min="1" max="70" value="<?= $rack_units ?>" required>
</div>
</div>
<div class="mb-3">
<label>Model</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<input type="text" class="form-control" name="make" placeholder="ex StarTech 12U Open Frame" maxlength="200" value="<?= $rack_model ?>">
</div>
</div>
<div class="mb-3">
<label>Depth</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-ruler"></i></span>
<input type="text" class="form-control" name="depth" placeholder="Rack Depth eg 800 mm or 31.5 Inches" maxlength="50" value="<?= $rack_depth ?>">
</div>
</div>
<div class="mb-3">
<label>Location</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-map-marker-alt"></i></span>
<select class="form-select select2" name="location">
<option value="">- Location -</option>
<?php
$sql_location_select = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations WHERE location_archived_at IS NULL AND location_client_id = $client_id ORDER BY location_name ASC");
while ($row = mysqli_fetch_assoc($sql_location_select)) {
$location_id_select = intval($row['location_id']);
$location_name_select = escapeHtml($row['location_name']);
?>
<option <?php if ($rack_location_id == $location_id_select) { echo "selected"; } ?> value="<?= $location_id_select ?>"><?= $location_name_select ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Physical Location</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-map-marker-alt"></i></span>
<input type="text" class="form-control" name="physical_location" placeholder="Physical location eg. Floor 2, Closet B" maxlength="200" value="<?= $rack_physical_location ?>">
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="Description of the rack" value="<?= $rack_description ?>">
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-rack-notes<?= $rack_id ?>">
<?php if ($rack_photo) { ?>
<img class="img-fluid p-3" alt="rack_photo" src="<?= "uploads/clients/$client_id/$rack_photo" ?>">
<?php } ?>
<div class="mb-3">
<label>Upload Photo</label>
<input type="file" class="form-control" name="file" accept="image/*">
</div>
<div class="mb-3">
<textarea class="form-control" rows="8" placeholder="Enter some notes" name="notes"><?= $rack_notes ?></textarea>
</div>
</div>
</div>
<?php require 'rack_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_rack" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>

View File

@@ -0,0 +1,166 @@
<?php
/*
* Rack form fields - shared by rack_add.php and rack_edit.php, which set the
* $rack_* values (empty for a new rack) and $client_id before including this.
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
// Rack types come from Admin > Categories. A rack saved with a type that has
// since been renamed or archived keeps it as an option, or the required select
// would force the type to change on every edit.
$rack_type_options = [];
$sql_rack_types_select = mysqli_query($mysqli, "SELECT category_name, category_color, category_icon FROM categories
WHERE category_type = 'rack_type' AND category_archived_at IS NULL
ORDER BY category_order ASC, category_name ASC");
while ($row = mysqli_fetch_assoc($sql_rack_types_select)) {
$rack_type_options[escapeHtml($row['category_name'])] = selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '');
}
if ($rack_type !== '' && !isset($rack_type_options[$rack_type])) {
$rack_type_options = [$rack_type => ''] + $rack_type_options;
}
?>
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#rackFormDetails">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#rackFormPhotos">Photos &amp; Notes</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="rackFormDetails">
<div class="row g-3">
<div class="col-md-7">
<label class="form-label">Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
<input type="text" class="form-control" name="name" placeholder="MDF-RACK-01" maxlength="200" value="<?= $rack_name ?>" required autofocus>
</div>
</div>
<div class="col-md-5">
<label class="form-label">Type <strong class="text-danger">*</strong></label>
<select class="form-select select2" name="type" required>
<option value="">- Type -</option>
<?php foreach ($rack_type_options as $rack_type_option => $rack_type_option_data) { ?>
<option <?php if ($rack_type === $rack_type_option) { echo "selected"; } ?><?= $rack_type_option_data ?>><?= $rack_type_option ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-4">
<label class="form-label">Height <strong class="text-danger">*</strong></label>
<div class="input-group">
<input type="number" class="form-control" name="units" placeholder="42" min="<?= max(1, $rack_highest_used_unit) ?>" max="70" value="<?= $rack_units ?: '' ?>" required>
<span class="input-group-text">U</span>
</div>
<?php if ($rack_highest_used_unit > 0) { ?>
<div class="form-text">In use up to U<?= $rack_highest_used_unit ?></div>
<?php } ?>
</div>
<div class="col-md-8">
<label class="form-label">Unit numbering</label>
<select class="form-select" name="units_descending">
<option value="0" <?php if (!$rack_units_descending) { echo "selected"; } ?>>U1 at the bottom (standard)</option>
<option value="1" <?php if ($rack_units_descending) { echo "selected"; } ?>>U1 at the top</option>
</select>
</div>
<div class="col-md-7">
<label class="form-label">Model</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<input type="text" class="form-control" name="model" placeholder="APC NetShelter SX 42U" maxlength="200" value="<?= $rack_model ?>">
</div>
</div>
<div class="col-md-5">
<label class="form-label">Depth</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-ruler"></i></span>
<input type="text" class="form-control" name="depth" placeholder="1070 mm" maxlength="50" value="<?= $rack_depth ?>">
</div>
</div>
<div class="col-md-6">
<label class="form-label">Location</label>
<select class="form-select select2" name="location">
<option value="">- Location -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations WHERE location_archived_at IS NULL AND location_client_id = $client_id ORDER BY location_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$location_id_select = intval($row['location_id']);
$location_name_select = escapeHtml($row['location_name']);
?>
<option value="<?= $location_id_select ?>" <?php if ($rack_location_id === $location_id_select) { echo "selected"; } ?>><?= $location_name_select ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Where in the building</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-door-closed"></i></span>
<input type="text" class="form-control" name="physical_location" placeholder="2nd floor, comms closet B" maxlength="200" value="<?= $rack_physical_location ?>">
</div>
</div>
<div class="col-md-6">
<label class="form-label">Power budget</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-bolt"></i></span>
<input type="number" class="form-control" name="power_capacity" placeholder="1440" min="0" max="1000000" value="<?= $rack_power_capacity ?: '' ?>">
<span class="input-group-text">W</span>
</div>
<div class="form-text">What the circuit or UPS feeding this rack can supply. Leave empty to skip power tracking.</div>
</div>
<div class="col-md-6">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="Main comms rack" maxlength="500" value="<?= $rack_description ?>">
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="rackFormPhotos">
<div class="row g-3 mb-3">
<?php foreach (['front' => ['file', 'remove_photo', $rack_photo], 'rear' => ['file_rear', 'remove_photo_rear', $rack_photo_rear]] as $photo_side => [$photo_field, $photo_remove_field, $photo_current]) { ?>
<div class="col-md-6">
<label class="form-label"><?= ucfirst($photo_side) ?> photo</label>
<?php if ($photo_current) { ?>
<div class="itflow-rack-form-photo mb-2">
<img src="<?= "../uploads/clients/$client_id/$photo_current" ?>" alt="<?= ucfirst($photo_side) ?> of the rack">
</div>
<?php } ?>
<input type="file" class="form-control" name="<?= $photo_field ?>" accept="image/jpeg,image/png,image/gif,image/webp">
<?php if ($photo_current) { ?>
<div class="form-check mt-2">
<input class="form-check-input" type="checkbox" name="<?= $photo_remove_field ?>" value="1" id="rackForm_<?= $photo_remove_field ?>">
<label class="form-check-label" for="rackForm_<?= $photo_remove_field ?>">Remove this photo</label>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<label class="form-label">Notes</label>
<textarea class="form-control" rows="6" placeholder="Keys, access, who to call at the site, power circuit numbers..." name="notes"><?= $rack_notes ?></textarea>
</div>
</div>

View File

@@ -236,6 +236,9 @@ if (isset($_GET['delete_asset'])) {
mysqli_query($mysqli,"DELETE FROM assets WHERE asset_id = $asset_id");
// Out of whatever rack it was in - an item pointing at a deleted asset draws as nothing
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
logAudit("Asset", "Delete", "$session_name deleted asset $asset_name", $client_id);
flashAlert("Asset <strong>$asset_name</strong> deleted");
@@ -508,6 +511,8 @@ if (isset($_POST['bulk_transfer_client_asset'])) {
// Archive/log the current asset
$notes = $asset_notes . "\r\n\r\n---\r\n* " . date('Y-m-d H:i:s') . ": Transferred asset $asset_name (old asset ID: $current_asset_id) from $current_client_name to $new_client_name (new asset ID: $new_asset_id)";
mysqli_query($mysqli,"UPDATE assets SET asset_archived_at = NOW() WHERE asset_id = $current_asset_id");
// It belongs to another client now, so it is no longer in this client's rack
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $current_asset_id");
mysqli_query($mysqli,"INSERT INTO asset_history SET asset_history_status = 'Transferred', asset_history_description = '$session_name transferred $asset_name to $new_client_name', asset_history_asset_id = $current_asset_id");
// Log Archive
@@ -805,6 +810,7 @@ if (isset($_POST['bulk_delete_assets'])) {
enforceClientAccess();
mysqli_query($mysqli,"DELETE FROM assets WHERE asset_id = $asset_id");
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
logAudit("Asset", "Delete", "$session_name deleted asset $asset_name", $client_id, $asset_id);
}

View File

@@ -285,6 +285,9 @@ if (isset($_GET['delete_client'])) {
// Delete Assets
mysqli_query($mysqli, "DELETE FROM assets WHERE asset_client_id = $client_id");
// Delete Racks (their items go with them)
mysqli_query($mysqli, "DELETE FROM racks WHERE rack_client_id = $client_id");
// Delete Domains and associated records
mysqli_query($mysqli, "DELETE FROM domains WHERE domain_client_id = $client_id");

View File

@@ -2,151 +2,144 @@
/*
* ITFlow - GET/POST request handler for client racks
*
* Racks and the items mounted in them (rack_units). Layout rules - faces,
* depth, which way the units are numbered - live in functions/rack.php, and
* every position check here goes through it so the add and edit paths cannot
* drift apart.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
if (isset($_POST['add_rack'])) {
if (isset($_POST['add_rack']) || isset($_POST['edit_rack'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$client_id = intval($_POST['client_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$type = escapeSql($_POST['type']);
$model = escapeSql($_POST['model']);
$depth = escapeSql($_POST['depth']);
$units = intval($_POST['units']);
$physical_location = escapeSql($_POST['physical_location']);
$location = intval($_POST['location']);
$notes = escapeSql($_POST['notes']);
$is_edit = isset($_POST['edit_rack']);
if ($is_edit) {
$rack_id = intval($_POST['rack_id']);
$sql = mysqli_query($mysqli, "SELECT rack_client_id, rack_photo, rack_photo_rear FROM racks WHERE rack_id = $rack_id");
$rack_row = mysqli_fetch_assoc($sql);
if (!$rack_row) {
flashAlert("That rack no longer exists", 'error');
redirect();
}
$client_id = intval($rack_row['rack_client_id']);
} else {
$rack_id = 0;
$rack_row = ['rack_photo' => '', 'rack_photo_rear' => ''];
$client_id = intval($_POST['client_id']);
}
enforceClientAccess();
mysqli_query($mysqli,"INSERT INTO racks SET rack_name = '$name', rack_description = '$description', rack_type = '$type', rack_model = '$model', rack_depth = '$depth', rack_units = $units, rack_location_id = $location, rack_physical_location = '$physical_location', rack_notes = '$notes', rack_client_id = $client_id");
$name = escapeSql($_POST['name'] ?? '');
$name_display = strip_tags(trim($_POST['name'] ?? ''));
$description = escapeSql($_POST['description'] ?? '');
$type = escapeSql($_POST['type'] ?? '');
$model = escapeSql($_POST['model'] ?? '');
$depth = escapeSql($_POST['depth'] ?? '');
$units = intval($_POST['units'] ?? 0);
$units_descending = intval($_POST['units_descending'] ?? 0) === 1 ? 1 : 0;
$power_capacity = intval($_POST['power_capacity'] ?? 0);
$power_capacity_sql = $power_capacity > 0 ? $power_capacity : "NULL";
$physical_location = escapeSql($_POST['physical_location'] ?? '');
$location = intval($_POST['location'] ?? 0);
$notes = escapeSql($_POST['notes'] ?? '');
$rack_id = mysqli_insert_id($mysqli);
if ($name === '') {
flashAlert("A rack needs a name", 'error');
redirect();
}
// Add Photo
if ($new_file_name = checkFileUpload($_FILES['file'], array('jpg', 'jpeg', 'gif', 'png', 'webp'))) {
if ($units < 1 || $units > 70) {
flashAlert("A rack is between 1 and 70 units tall", 'error');
redirect();
}
$file_tmp_path = $_FILES['file']['tmp_name'];
// A location from another client would show up on this client's rack
if ($location && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM locations WHERE location_id = $location AND location_client_id = $client_id"))) {
$location = 0;
}
// directory in which the uploaded file will be moved
if (!file_exists("../uploads/clients/$client_id")) {
mkdir("../uploads/clients/$client_id");
if ($is_edit) {
// Shrinking the rack under an item would leave it hanging off the top
$sql = mysqli_query($mysqli, "SELECT unit_device, unit_type, unit_end_number, asset_name FROM rack_units
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_rack_id = $rack_id AND unit_end_number > $units
ORDER BY unit_end_number DESC LIMIT 1");
if ($row = mysqli_fetch_assoc($sql)) {
$blocking_name = rackUnitName($row['asset_name'], $row['unit_device'], $row['unit_type']);
flashAlert("Can't shrink the rack to {$units}U - <strong>" . strip_tags($blocking_name) . "</strong> is mounted up to U" . intval($row['unit_end_number']) . ". Move or remove it first.", 'error');
redirect();
}
$upload_file_dir = "../uploads/clients/$client_id/";
$dest_path = $upload_file_dir . $new_file_name;
move_uploaded_file($file_tmp_path, $dest_path);
mysqli_query($mysqli,"UPDATE racks SET rack_photo = '$new_file_name' WHERE rack_id = $rack_id");
mysqli_query($mysqli, "UPDATE racks SET rack_name = '$name', rack_description = '$description', rack_type = '$type', rack_model = '$model', rack_depth = '$depth', rack_units = $units, rack_units_descending = $units_descending, rack_power_capacity = $power_capacity_sql, rack_location_id = $location, rack_physical_location = '$physical_location', rack_notes = '$notes' WHERE rack_id = $rack_id");
} else {
mysqli_query($mysqli, "INSERT INTO racks SET rack_name = '$name', rack_description = '$description', rack_type = '$type', rack_model = '$model', rack_depth = '$depth', rack_units = $units, rack_units_descending = $units_descending, rack_power_capacity = $power_capacity_sql, rack_location_id = $location, rack_physical_location = '$physical_location', rack_notes = '$notes', rack_client_id = $client_id");
$rack_id = mysqli_insert_id($mysqli);
}
// Photos of the front and the back. A new upload replaces the old file; the
// remove boxes only matter when nothing new came in for that side.
foreach (['rack_photo' => ['file', 'remove_photo'], 'rack_photo_rear' => ['file_rear', 'remove_photo_rear']] as $column => [$file_field, $remove_field]) {
$old_photo = (string) ($rack_row[$column] ?? '');
$new_photo = isset($_FILES[$file_field]) ? rackStorePhoto($_FILES[$file_field], $client_id, $old_photo) : '';
if ($new_photo !== '') {
$new_photo = escapeSql($new_photo);
mysqli_query($mysqli, "UPDATE racks SET $column = '$new_photo' WHERE rack_id = $rack_id");
} elseif ($is_edit && !empty($_POST[$remove_field]) && $old_photo !== '') {
rackDeletePhoto($client_id, $old_photo);
mysqli_query($mysqli, "UPDATE racks SET $column = NULL WHERE rack_id = $rack_id");
}
}
if ($is_edit) {
logAudit("Rack", "Edit", "$session_name edited rack $name", $client_id, $rack_id);
flashAlert("Rack <strong>$name_display</strong> saved");
redirect();
}
logAudit("Rack", "Create", "$session_name created rack $name", $client_id, $rack_id);
flashAlert("Rack <strong>$name</strong> created");
redirect();
flashAlert("Rack <strong>$name_display</strong> created - now add what's in it");
redirect("rack.php?client_id=$client_id&rack_id=$rack_id");
}
if (isset($_POST['edit_rack'])) {
if (isset($_GET['archive_rack']) || isset($_GET['restore_rack'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$rack_id = intval($_POST['rack_id']);
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$type = escapeSql($_POST['type']);
$model = escapeSql($_POST['model']);
$depth = escapeSql($_POST['depth']);
$units = intval($_POST['units']);
$physical_location = escapeSql($_POST['physical_location']);
$location = intval($_POST['location']);
$notes = escapeSql($_POST['notes']);
$is_archive = isset($_GET['archive_rack']);
$rack_id = intval($is_archive ? $_GET['archive_rack'] : $_GET['restore_rack']);
$client_id = intval(getFieldById('racks', $rack_id, 'rack_client_id'));
enforceClientAccess();
mysqli_query($mysqli,"UPDATE racks SET rack_name = '$name', rack_description = '$description', rack_type = '$type', rack_model = '$model', rack_depth = '$depth', rack_units = $units, rack_location_id = $location, rack_physical_location = '$physical_location', rack_notes = '$notes' WHERE rack_id = $rack_id");
// Add Photo
if ($new_file_name = checkFileUpload($_FILES['file'], array('jpg', 'jpeg', 'gif', 'png', 'webp'))) {
$file_tmp_path = $_FILES['file']['tmp_name'];
// directory in which the uploaded file will be moved
if (!file_exists("../uploads/clients/$client_id")) {
mkdir("../uploads/clients/$client_id");
}
$upload_file_dir = "../uploads/clients/$client_id/";
$dest_path = $upload_file_dir . $new_file_name;
move_uploaded_file($file_tmp_path, $dest_path);
mysqli_query($mysqli,"UPDATE racks SET rack_photo = '$new_file_name' WHERE rack_id = $rack_id");
$sql = mysqli_query($mysqli, "SELECT rack_name, rack_client_id FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
flashAlert("That rack no longer exists", 'error');
redirect();
}
logAudit("Rack", "Edit", "$session_name edited rack $name", $client_id, $rack_id);
flashAlert("Rack <strong>$name</strong> edited");
redirect();
}
if (isset($_GET['archive_rack'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$rack_id = intval($_GET['archive_rack']);
enforceClientAccess();
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_client_id FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
$rack_name = escapeSql($row['rack_name']);
$client_id = intval($row['rack_client_id']);
mysqli_query($mysqli,"UPDATE racks SET rack_archived_at = NOW() WHERE rack_id = $rack_id");
logAudit("Rack", "Archive", "$session_name archived rack $rack_name", $client_id, $rack_id);
flashAlert("Rack <strong>$rack_name</strong> archived", 'error');
redirect();
}
if (isset($_GET['restore_rack'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$rack_id = intval($_GET['restore_rack']);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_client_id FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
$rack_name = escapeSql($row['rack_name']);
$rack_name_display = strip_tags($row['rack_name']);
$client_id = intval($row['rack_client_id']);
// The client has to be known before access can be checked against it
enforceClientAccess();
mysqli_query($mysqli,"UPDATE racks SET rack_archived_at = NULL WHERE rack_id = $rack_id");
logAudit("Rack", "Restore", "$session_name restored rack $rack_name", $client_id, $rack_id);
flashAlert("Rack <strong>$rack_name</strong> Restored");
if ($is_archive) {
mysqli_query($mysqli, "UPDATE racks SET rack_archived_at = NOW() WHERE rack_id = $rack_id");
logAudit("Rack", "Archive", "$session_name archived rack $rack_name", $client_id, $rack_id);
flashAlert("Rack <strong>$rack_name_display</strong> archived", 'error');
} else {
mysqli_query($mysqli, "UPDATE racks SET rack_archived_at = NULL WHERE rack_id = $rack_id");
logAudit("Rack", "Restore", "$session_name restored rack $rack_name", $client_id, $rack_id);
flashAlert("Rack <strong>$rack_name_display</strong> restored");
}
redirect();
@@ -160,104 +153,138 @@ if (isset($_GET['delete_rack'])) {
$rack_id = intval($_GET['delete_rack']);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_client_id, rack_photo FROM racks WHERE rack_id = $rack_id");
$sql = mysqli_query($mysqli, "SELECT rack_name, rack_client_id, rack_photo, rack_photo_rear FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
flashAlert("That rack no longer exists", 'error');
redirect();
}
$rack_name = escapeSql($row['rack_name']);
$rack_photo = escapeSql($row['rack_photo']);
$rack_name_display = strip_tags($row['rack_name']);
$client_id = intval($row['rack_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"DELETE FROM racks WHERE rack_id = $rack_id");
// rack_units go with it (ON DELETE CASCADE)
mysqli_query($mysqli, "DELETE FROM racks WHERE rack_id = $rack_id");
// Delete Photo if exists
if ($rack_photo) {
unlink("../uploads/clients/$client_id/$rack_photo");
}
rackDeletePhoto($client_id, $row['rack_photo']);
rackDeletePhoto($client_id, $row['rack_photo_rear']);
logAudit("Rack", "Delete", "$session_name deleted rack $rack_name", $client_id);
flashAlert("Rack <strong>$rack_name</strong> deleted", 'error');
flashAlert("Rack <strong>$rack_name_display</strong> deleted", 'error');
redirect();
// The rack page this may have come from is gone - land on the list
redirect("racks.php?client_id=$client_id");
}
if (isset($_POST['add_rack_unit'])) {
if (isset($_POST['add_rack_unit']) || isset($_POST['edit_rack_unit'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$rack_id = intval($_POST['rack_id']);
$name = escapeSql($_POST['name']);
$unit_start = intval($_POST['unit_start']);
$unit_end = intval($_POST['unit_end']);
$asset = intval($_POST['asset']);
$is_edit = isset($_POST['edit_rack_unit']);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_client_id FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
$rack_name = escapeSql($row['rack_name']);
$client_id = intval($row['rack_client_id']);
// On an edit the rack comes from the item itself, never from the form - a
// posted rack_id would let an item be "edited" into another client's rack
if ($is_edit) {
$unit_id = intval($_POST['unit_id']);
$sql = mysqli_query($mysqli, "SELECT unit_rack_id FROM rack_units WHERE unit_id = $unit_id");
$unit_row = mysqli_fetch_assoc($sql);
if (!$unit_row) {
flashAlert("That item is no longer in the rack", 'error');
redirect();
}
$rack_id = intval($unit_row['unit_rack_id']);
} else {
$unit_id = 0;
$rack_id = intval($_POST['rack_id']);
}
$sql = mysqli_query($mysqli, "SELECT rack_name, rack_client_id, rack_units FROM racks WHERE rack_id = $rack_id");
$rack_row = mysqli_fetch_assoc($sql);
if (!$rack_row) {
flashAlert("That rack no longer exists", 'error');
redirect();
}
$rack_name = escapeSql($rack_row['rack_name']);
$rack_units = intval($rack_row['rack_units']);
$client_id = intval($rack_row['rack_client_id']);
enforceClientAccess();
// **New Validation Check**
if ($unit_start > $unit_end) {
flashAlert("Unit Start number cannot be higher than Unit End number.", 'error');
$asset_id = intval($_POST['asset'] ?? 0);
$label = escapeSql($_POST['name'] ?? '');
$unit_type = (string) ($_POST['type'] ?? 'Device');
$unit_type = array_key_exists($unit_type, rackItemTypes()) ? $unit_type : 'Device';
$start = intval($_POST['unit_start'] ?? 0);
$height = max(1, intval($_POST['unit_height'] ?? 1));
$end = $start + $height - 1;
$face = ($_POST['face'] ?? 'front') === 'rear' ? 'rear' : 'front';
$full_depth = intval($_POST['full_depth'] ?? 0) === 1 ? 1 : 0;
$power_watts = intval($_POST['power_watts'] ?? 0);
$power_watts_sql = $power_watts > 0 ? $power_watts : "NULL";
$notes = escapeSql($_POST['notes'] ?? '');
if ($start < 1 || $end > $rack_units) {
flashAlert("That doesn't fit - this rack runs from U1 to U$rack_units", 'error');
redirect();
}
// Check if the unit range is already occupied
$check_sql = mysqli_query($mysqli, "SELECT 1 FROM rack_units WHERE unit_rack_id = $rack_id AND unit_start_number <= $unit_end AND unit_end_number >= $unit_start");
// The asset has to be this client's, and in one place at a time
$asset_name = '';
if ($asset_id) {
$sql = mysqli_query($mysqli, "SELECT asset_name FROM assets WHERE asset_id = $asset_id AND asset_client_id = $client_id");
$asset_row = mysqli_fetch_assoc($sql);
if (!$asset_row) {
flashAlert("That asset doesn't belong to this client", 'error');
redirect();
}
$asset_name = $asset_row['asset_name'];
if (mysqli_num_rows($check_sql) > 0) {
// If there is an overlap, return an error message;
flashAlert("Units $unit_start to $unit_end are already in use by another device.", 'error');
$sql = mysqli_query($mysqli, "SELECT rack_name, unit_start_number, unit_end_number FROM rack_units
LEFT JOIN racks ON rack_id = unit_rack_id
WHERE unit_asset_id = $asset_id AND unit_id != $unit_id LIMIT 1");
if ($row = mysqli_fetch_assoc($sql)) {
flashAlert("<strong>" . strip_tags($asset_name) . "</strong> is already racked in " . strip_tags($row['rack_name']) . " at " . html_entity_decode(rackPositionLabel($row['unit_start_number'], $row['unit_end_number'])), 'error');
redirect();
}
} elseif ($label === '') {
flashAlert("Pick an asset or give the item a name", 'error');
redirect();
}
// If no overlap and validation passes, proceed with the insertion
mysqli_query($mysqli, "INSERT INTO rack_units SET unit_device = '$name', unit_asset_id = $asset, unit_start_number = $unit_start, unit_end_number = $unit_end, unit_rack_id = $rack_id");
$conflict = rackUnitConflict($rack_id, $start, $end, $face, $full_depth, $unit_id);
if ($conflict) {
flashAlert(html_entity_decode(rackPositionLabel($start, $end)) . " on the $face is taken by <strong>" . strip_tags($conflict['name']) . "</strong> (" . html_entity_decode(rackPositionLabel($conflict['start'], $conflict['end'])) . ")", 'error');
redirect();
}
$unit_id = mysqli_insert_id($mysqli);
$asset_sql = $asset_id ? $asset_id : "NULL";
// A linked asset is drawn by its own asset type, so only unlinked items keep one
$unit_type_sql = $asset_id ? "NULL" : "'" . escapeSql($unit_type) . "'";
logAudit("Rack", "Edit", "$session_name added device $name to units $unit_start - $unit_end in rack $rack_name", $client_id, $rack_id);
$set = "unit_device = '$label', unit_asset_id = $asset_sql, unit_type = $unit_type_sql,
unit_start_number = $start, unit_end_number = $end, unit_face = '$face', unit_full_depth = $full_depth,
unit_power_watts = $power_watts_sql, unit_notes = '$notes'";
flashAlert("Device <strong>$name</strong> added to units $unit_start - $unit_end in rack.");
$item_name = rackUnitName($asset_name, $_POST['name'] ?? '', $unit_type);
$item_name_sql = escapeSql($item_name);
$item_name_display = strip_tags($item_name);
$position = html_entity_decode(rackPositionLabel($start, $end));
redirect();
}
if (isset($_POST['edit_rack_unit'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
$unit_id = intval($_POST['unit_id']);
$rack_id = intval($_POST['rack_id']);
$name = escapeSql($_POST['name']);
$unit_start = intval($_POST['unit_start']);
$unit_end = intval($_POST['unit_end']);
$asset = intval($_POST['asset']);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_client_id FROM racks WHERE rack_id = $rack_id");
$row = mysqli_fetch_assoc($sql);
$rack_name = escapeSql($row['rack_name']);
$client_id = intval($row['rack_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE rack_units SET unit_device = '$name', unit_asset_id = $asset, unit_start_number = $unit_start, unit_end_number = $unit_end WHERE unit_id = $unit_id");
logAudit("Rack", "Edit", "$session_name edited device $name in rack $rack_name", $client_id, $rack_id);
flashAlert("Device $name edited on the rack");
if ($is_edit) {
mysqli_query($mysqli, "UPDATE rack_units SET $set WHERE unit_id = $unit_id");
logAudit("Rack", "Edit", "$session_name updated $item_name_sql at $position ($face) in rack $rack_name", $client_id, $rack_id);
flashAlert("<strong>$item_name_display</strong> saved at $position");
} else {
mysqli_query($mysqli, "INSERT INTO rack_units SET $set, unit_rack_id = $rack_id");
logAudit("Rack", "Edit", "$session_name added $item_name_sql at $position ($face) to rack $rack_name", $client_id, $rack_id);
flashAlert("<strong>$item_name_display</strong> added at $position");
}
redirect();
@@ -271,21 +298,27 @@ if (isset($_GET['remove_rack_unit'])) {
$unit_id = intval($_GET['remove_rack_unit']);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT rack_name, rack_id, rack_client_id, unit_device FROM racks LEFT JOIN rack_units ON unit_rack_id = rack_id WHERE unit_id = $unit_id");
$sql = mysqli_query($mysqli, "SELECT rack_name, rack_id, rack_client_id, unit_device, unit_type, asset_name FROM rack_units
LEFT JOIN racks ON rack_id = unit_rack_id
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_id = $unit_id");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
flashAlert("That item is no longer in the rack", 'error');
redirect();
}
$rack_name = escapeSql($row['rack_name']);
$unit_device = escapeSql($row['unit_device']);
$client_id = intval($row['rack_client_id']);
$rack_id = intval($row['rack_id']);
$item_name = rackUnitName($row['asset_name'], $row['unit_device'], $row['unit_type']);
enforceClientAccess();
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_id = $unit_id");
mysqli_query($mysqli, "DELETE FROM rack_units WHERE unit_id = $unit_id");
logAudit("Rack", "Edit", "$session_name removed device $unit_device from rack $rack_name", $client_id, $rack_id);
logAudit("Rack", "Edit", "$session_name removed " . escapeSql($item_name) . " from rack $rack_name", $client_id, $rack_id);
flashAlert("Device <strong>$unit_device</strong> removed from rack", 'error');
flashAlert("<strong>" . strip_tags($item_name) . "</strong> removed from the rack", 'error');
redirect();

451
agent/rack.php Normal file
View File

@@ -0,0 +1,451 @@
<?php
/*
* Rack - one rack, drawn to scale front and rear, with what is in it.
*
* The elevation (includes/rack_elevation.php) is the page: every item at its
* position on the face it is mounted on, every empty U a click away from
* adding something there. Around it, how full the rack is (units, the largest
* gap a full-depth item could still go in, power against the budget), the
* rack's details and photos, the item list for print and search, and the
* client's network gear that isn't racked anywhere yet.
*/
require_once "includes/inc_all_client.php";
// Perms
enforceUserPermission('module_support');
$rack_id = intval($_GET['rack_id'] ?? 0);
$sql = mysqli_query(
$mysqli,
"SELECT rack_archived_at, rack_client_id, rack_created_at, rack_depth, rack_description, rack_id, rack_model,
rack_name, rack_notes, rack_photo, rack_photo_rear, rack_physical_location, rack_power_capacity,
rack_type, rack_units, rack_units_descending, rack_updated_at, location_id, location_name
FROM racks
LEFT JOIN locations ON location_id = rack_location_id
WHERE rack_id = $rack_id
AND rack_client_id = $client_id
LIMIT 1"
);
if (mysqli_num_rows($sql) == 0) {
echo "<center><h1 class='text-secondary mt-5'>Nothing to see here</h1><a class='btn btn-lg btn-secondary mt-3' href='racks.php?client_id=$client_id'><i class='fa fa-fw fa-arrow-left'></i> Back to racks</a></center>";
} else {
$row = mysqli_fetch_assoc($sql);
$rack_name = escapeHtml($row['rack_name']);
$rack_description = escapeHtml($row['rack_description']);
$rack_model = escapeHtml($row['rack_model']);
$rack_depth = escapeHtml($row['rack_depth']);
$rack_type = escapeHtml($row['rack_type']);
$rack_units = max(1, intval($row['rack_units']));
$rack_units_descending = intval($row['rack_units_descending']);
$rack_power_capacity = intval($row['rack_power_capacity']);
$rack_photo = escapeHtml($row['rack_photo']);
$rack_photo_rear = escapeHtml($row['rack_photo_rear']);
$rack_physical_location = escapeHtml($row['rack_physical_location']);
$rack_notes = escapeHtml($row['rack_notes']);
$rack_archived_at = escapeHtml($row['rack_archived_at']);
$rack_updated_at = escapeHtml($row['rack_updated_at'] ?: $row['rack_created_at']);
$location_id = intval($row['location_id']);
$location_name = escapeHtml($row['location_name']);
$can_edit = lookupUserPermission('module_support') >= 2;
$can_delete = lookupUserPermission('module_support') >= 3;
$rack_rows = rackLoadUnits([$rack_id])[$rack_id];
$rack_items = array_map('rackUnitView', $rack_rows);
$occupancy = rackOccupancy($rack_rows, $rack_units);
$used_percent = (int) round($occupancy['any'] / $rack_units * 100);
$power_used = array_sum(array_column($rack_items, 'power'));
$power_percent = $rack_power_capacity ? (int) round($power_used / $rack_power_capacity * 100) : 0;
$item_count = count($rack_items);
$gap = $occupancy['largest_gap'];
// The client's network kit that isn't in any rack - one click to put it here
$unracked_assets = [];
if ($can_edit && !$rack_archived_at) {
$sql_unracked = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model FROM assets
WHERE asset_client_id = $client_id
AND asset_archived_at IS NULL
AND asset_type IN ('Server', 'Switch', 'Firewall/Router')
AND NOT EXISTS (SELECT 1 FROM rack_units WHERE unit_asset_id = asset_id)
ORDER BY FIELD(asset_type, 'Firewall/Router', 'Switch', 'Server'), asset_name
LIMIT 25");
while ($unracked_row = mysqli_fetch_assoc($sql_unracked)) {
$unracked_assets[] = $unracked_row;
}
}
$usage_tone = $used_percent >= 90 ? 'danger' : ($used_percent >= 75 ? 'warning' : 'primary');
$power_tone = $power_percent >= 90 ? 'danger' : ($power_percent >= 75 ? 'warning' : 'success');
?>
<ol class="breadcrumb d-print-none">
<li class="breadcrumb-item">
<a href="client_overview.php?client_id=<?= $client_id ?>"><?= $client_name ?></a>
</li>
<li class="breadcrumb-item">
<a href="racks.php?client_id=<?= $client_id ?>">Racks</a>
</li>
<li class="breadcrumb-item active"><?= $rack_name ?></li>
</ol>
<!-- Rack header -->
<div class="card mb-3 itflow-rack-head">
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<span class="itflow-rack-head-icon" aria-hidden="true"><i class="fas fa-server"></i></span>
<div class="flex-grow-1 min-w-0">
<h1 class="h4 mb-1 fw-semibold">
<?= $rack_name ?>
<?php if ($rack_archived_at) { ?>
<span class="badge rounded-pill text-bg-secondary fw-normal align-middle fs-6 ms-1">Archived</span>
<?php } ?>
</h1>
<div class="text-body-secondary small d-flex flex-wrap column-gap-3 row-gap-1">
<span><i class="fas fa-fw fa-arrows-alt-v me-1"></i><?= $rack_units ?>U</span>
<?php if ($rack_type) { ?>
<span><i class="fas fa-fw fa-th-large me-1"></i><?= $rack_type ?></span>
<?php } ?>
<?php if ($location_name || $rack_physical_location) { ?>
<span>
<i class="fas fa-fw fa-map-marker-alt me-1"></i><?= $location_name ?><?= $location_name && $rack_physical_location ? ' &rsaquo; ' : '' ?><?= $rack_physical_location ?>
</span>
<?php } ?>
<?php if ($rack_description) { ?>
<span><?= $rack_description ?></span>
<?php } ?>
</div>
</div>
<div class="d-flex flex-wrap gap-2 d-print-none">
<?php if ($can_edit && !$rack_archived_at) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/rack/rack_device_add.php?id=<?= $rack_id ?>">
<i class="fas fa-plus me-2"></i>Add Item
</button>
<?php } ?>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-size="lg" data-modal-url="modals/rack/rack_edit.php?id=<?= $rack_id ?>">
<i class="fas fa-edit me-2"></i>Edit
</button>
<?php } ?>
<button type="button" class="btn btn-outline-secondary" onclick="window.print()" title="Print the elevation and item list">
<i class="fas fa-print"></i><span class="visually-hidden">Print</span>
</button>
<?php if ($can_edit) { ?>
<div class="dropdown dropstart">
<button class="btn btn-outline-secondary" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<?php if ($rack_archived_at) { ?>
<a class="dropdown-item confirm-link" href="post.php?restore_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-redo me-2"></i>Restore
</a>
<?php } else { ?>
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="row g-3">
<!-- Elevation and items -->
<div class="col-xl-8 col-xxl-9 order-xl-2">
<div class="card mb-3">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-columns me-2 text-secondary"></i>Elevation</h3>
<span class="small text-body-secondary d-print-none">
<?php if ($can_edit && !$rack_archived_at) { ?>
Click an empty U to add something there
<?php } ?>
</span>
</div>
<div class="card-body">
<div class="itflow-rack-pair">
<?php
$elevation_items = $rack_items;
$elevation_rack_units = $rack_units;
$elevation_descending = $rack_units_descending;
$elevation_can_edit = $can_edit && !$rack_archived_at;
foreach (['front', 'rear'] as $elevation_face) {
require "includes/rack_elevation.php";
}
?>
</div>
<div class="itflow-rack-legend small text-body-secondary mt-3">
<span><i class="itflow-rack-swatch itflow-rack-tone-server"></i>Servers</span>
<span><i class="itflow-rack-swatch itflow-rack-tone-network"></i>Network</span>
<span><i class="itflow-rack-swatch itflow-rack-tone-firewall"></i>Firewalls</span>
<span><i class="itflow-rack-swatch itflow-rack-tone-power"></i>Power</span>
<span><i class="itflow-rack-swatch itflow-rack-tone-patch"></i>Patching</span>
<span><i class="itflow-rack-swatch itflow-rack-tone-device"></i>Other</span>
<span><i class="itflow-rack-swatch itflow-rack-swatch-ghost"></i>Full depth from the other side</span>
</div>
</div>
</div>
<div class="card mb-3 itflow-rack-items">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-list me-2 text-secondary"></i>In this rack <span class="text-body-secondary fw-normal">(<?= $item_count ?>)</span></h3>
</div>
<?php if ($item_count) { ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="text-nowrap">
<tr>
<th class="ps-3">Position</th>
<th style="min-width: 15rem">Item</th>
<th>Make / Model</th>
<th>Serial</th>
<th>IP</th>
<th>Mounted</th>
<th class="text-end">Power</th>
<?php if ($can_edit) { ?>
<th class="d-print-none"></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php
// Top of the rack first, the way you read it standing in front of it
$table_items = $rack_items;
usort($table_items, function ($a, $b) use ($rack_units_descending) {
return $rack_units_descending ? $a['start'] <=> $b['start'] : $b['end'] <=> $a['end'];
});
foreach ($table_items as $item) { ?>
<tr>
<td class="ps-3 text-nowrap font-monospace small"><?= $item['position'] ?></td>
<td>
<div class="d-flex align-items-center gap-2">
<span class="itflow-rack-chip itflow-rack-tone-<?= $item['tone'] ?>"><i class="fas fa-fw <?= $item['icon'] ?>"></i></span>
<div class="min-w-0">
<?php if ($item['asset_id']) { ?>
<a class="fw-semibold<?= $item['asset_archived'] ? ' text-decoration-line-through' : '' ?>" href="asset.php?client_id=<?= $client_id ?>&asset_id=<?= $item['asset_id'] ?>"><?= $item['name'] ?></a>
<?php } else { ?>
<span class="fw-semibold"><?= $item['name'] ?></span>
<?php } ?>
<div class="small text-body-secondary">
<?= $item['type_label'] ?>
<?php if ($item['asset_id'] && $item['label']) { ?>&middot; <?= $item['label'] ?><?php } ?>
<?php if ($item['notes']) { ?>&middot; <?= $item['notes'] ?><?php } ?>
</div>
</div>
</div>
</td>
<td class="small"><?= $item['make_model'] ?: '<span class="text-body-secondary">-</span>' ?></td>
<td class="small font-monospace"><?= $item['serial'] ?: '<span class="text-body-secondary">-</span>' ?></td>
<td class="small font-monospace"><?= $item['ip'] ?: '<span class="text-body-secondary">-</span>' ?></td>
<td class="small text-nowrap">
<?= ucfirst($item['face']) ?>
<?php if ($item['full_depth']) { ?>
<span class="badge rounded-pill text-bg-light border fw-normal ms-1">Full depth</span>
<?php } ?>
</td>
<td class="small text-end text-nowrap"><?= $item['power'] ? number_format($item['power']) . ' W' : '<span class="text-body-secondary">-</span>' ?></td>
<?php if ($can_edit) { ?>
<td class="text-end pe-3 d-print-none">
<button type="button" class="btn btn-sm btn-light ajax-modal" title="Move or edit"
data-modal-url="modals/rack/rack_device_edit.php?id=<?= $item['id'] ?>">
<i class="fas fa-fw fa-pen"></i>
</button>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
<?php if ($power_used) { ?>
<tfoot>
<tr>
<td colspan="6" class="ps-3 text-end small text-body-secondary">Total draw</td>
<td class="text-end small fw-semibold text-nowrap"><?= number_format($power_used) ?> W</td>
<?php if ($can_edit) { ?><td class="d-print-none"></td><?php } ?>
</tr>
</tfoot>
<?php } ?>
</table>
</div>
<?php } else { ?>
<div class="card-body text-center text-body-secondary py-5">
<i class="fas fa-server fa-2x mb-3 opacity-50"></i>
<div>Nothing racked yet.</div>
<?php if ($can_edit && !$rack_archived_at) { ?>
<div class="small">Click an empty U on the elevation, or use <strong>Add Item</strong>.</div>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
<!-- Capacity, details, photos, notes -->
<div class="col-xl-4 col-xxl-3 order-xl-1">
<div class="card mb-3">
<div class="card-body">
<div class="d-flex align-items-baseline justify-content-between mb-2">
<div>
<span class="fs-3 fw-semibold"><?= $occupancy['any'] ?></span>
<span class="text-body-secondary">of <?= $rack_units ?>U used</span>
</div>
<span class="fw-semibold text-<?= $usage_tone ?>-emphasis"><?= $used_percent ?>%</span>
</div>
<div class="progress mb-3" role="progressbar" aria-label="Units used" aria-valuenow="<?= $used_percent ?>" aria-valuemin="0" aria-valuemax="100" style="height: .5rem">
<div class="progress-bar bg-<?= $usage_tone ?>" style="width: <?= $used_percent ?>%"></div>
</div>
<div class="row g-2 text-center itflow-rack-stats">
<div class="col-4">
<div class="fw-semibold"><?= $occupancy['free_any'] ?>U</div>
<div class="small text-body-secondary">Free</div>
</div>
<div class="col-4">
<div class="fw-semibold"><?= $gap['size'] ?>U</div>
<div class="small text-body-secondary" title="The tallest full-depth item that still fits">Largest gap</div>
</div>
<div class="col-4">
<div class="fw-semibold"><?= $item_count ?></div>
<div class="small text-body-secondary">Items</div>
</div>
</div>
<?php if ($gap['size']) { ?>
<div class="small text-body-secondary mt-2 text-center">
Room for up to <?= $gap['size'] ?>U at <?= rackPositionLabel($gap['start'], $gap['end']) ?>
</div>
<?php } ?>
<?php if ($rack_power_capacity || $power_used) { ?>
<hr>
<div class="d-flex align-items-baseline justify-content-between mb-2">
<div>
<i class="fas fa-fw fa-bolt text-warning me-1"></i>
<span class="fw-semibold"><?= number_format($power_used) ?> W</span>
<?php if ($rack_power_capacity) { ?>
<span class="text-body-secondary">of <?= number_format($rack_power_capacity) ?> W</span>
<?php } ?>
</div>
<?php if ($rack_power_capacity) { ?>
<span class="fw-semibold text-<?= $power_tone ?>-emphasis"><?= $power_percent ?>%</span>
<?php } ?>
</div>
<?php if ($rack_power_capacity) { ?>
<div class="progress" role="progressbar" aria-label="Power used" aria-valuenow="<?= min(100, $power_percent) ?>" aria-valuemin="0" aria-valuemax="100" style="height: .5rem">
<div class="progress-bar bg-<?= $power_tone ?>" style="width: <?= min(100, $power_percent) ?>%"></div>
</div>
<?php if ($power_used > $rack_power_capacity) { ?>
<div class="small text-danger mt-2"><i class="fas fa-exclamation-triangle me-1"></i>Over budget by <?= number_format($power_used - $rack_power_capacity) ?> W</div>
<?php } ?>
<?php } else { ?>
<div class="small text-body-secondary">Set a power budget on the rack to track headroom.</div>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-info-circle me-2 text-secondary"></i>Details</h3>
</div>
<div class="card-body">
<dl class="itflow-rack-dl mb-0">
<?php if ($rack_model) { ?>
<dt>Model</dt><dd><?= $rack_model ?></dd>
<?php } ?>
<?php if ($rack_depth) { ?>
<dt>Depth</dt><dd><?= $rack_depth ?></dd>
<?php } ?>
<dt>Numbering</dt><dd>U1 at the <?= $rack_units_descending ? 'top' : 'bottom' ?></dd>
<?php if ($location_name) { ?>
<dt>Location</dt><dd><a href="locations.php?client_id=<?= $client_id ?>&q=<?= urlencode(html_entity_decode($location_name)) ?>"><?= $location_name ?></a></dd>
<?php } ?>
<?php if ($rack_physical_location) { ?>
<dt>In the building</dt><dd><?= $rack_physical_location ?></dd>
<?php } ?>
<dt>Front / rear</dt><dd><?= $occupancy['front'] ?>U / <?= $occupancy['rear'] ?>U in use</dd>
<dt>Updated</dt><dd title="<?= $rack_updated_at ?>"><?= timeAgo($rack_updated_at) ?></dd>
</dl>
</div>
</div>
<?php if ($rack_photo || $rack_photo_rear) { ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-camera me-2 text-secondary"></i>Photos</h3>
</div>
<div class="card-body">
<div class="row g-2">
<?php foreach (['Front' => $rack_photo, 'Rear' => $rack_photo_rear] as $photo_side => $photo_file) {
if (!$photo_file) {
continue;
} ?>
<div class="col-6">
<a class="itflow-rack-photo" href="<?= "../uploads/clients/$client_id/$photo_file" ?>" target="_blank" rel="noopener" title="Open full size">
<img src="<?= "../uploads/clients/$client_id/$photo_file" ?>" alt="<?= $photo_side ?> of <?= $rack_name ?>" loading="lazy">
<span><?= $photo_side ?></span>
</a>
</div>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php if ($rack_notes) { ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-sticky-note me-2 text-secondary"></i>Notes</h3>
</div>
<div class="card-body small" style="white-space: pre-line"><?= $rack_notes ?></div>
</div>
<?php } ?>
<?php if ($unracked_assets) { ?>
<div class="card mb-3 d-print-none">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-dolly me-2 text-secondary"></i>Not racked yet</h3>
</div>
<div class="list-group list-group-flush">
<?php foreach ($unracked_assets as $unracked) {
$unracked_id = intval($unracked['asset_id']);
$unracked_style = rackItemStyle($unracked['asset_type'], '', true);
?>
<div class="list-group-item d-flex align-items-center gap-2">
<span class="itflow-rack-chip itflow-rack-tone-<?= $unracked_style['tone'] ?>"><i class="fas fa-fw <?= $unracked_style['icon'] ?>"></i></span>
<div class="min-w-0 flex-grow-1">
<div class="text-truncate fw-semibold small"><?= escapeHtml($unracked['asset_name']) ?></div>
<div class="text-truncate small text-body-secondary"><?= escapeHtml(trim($unracked['asset_make'] . ' ' . $unracked['asset_model'])) ?: escapeHtml($unracked['asset_type']) ?></div>
</div>
<button type="button" class="btn btn-sm btn-outline-primary ajax-modal flex-shrink-0"
data-modal-url="modals/rack/rack_device_add.php?id=<?= $rack_id ?>&asset_id=<?= $unracked_id ?>">
Rack it
</button>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
<?php
}
require_once "../includes/footer.php";

View File

@@ -1,344 +1,328 @@
<?php
/*
* Racks - every rack a client has (or, from All Client Docs, every rack the
* agent can see), each as a card with a scale drawing of its front, how full it
* is and what it draws. A card opens the rack (rack.php).
*/
// Default Column Sortby Filter
$sort = "rack_name";
$order = "ASC";
require_once "includes/inc_all_client.php";
// If client_id is in URI then show client Side Bar and client header
if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$client_query = "AND rack_client_id = $client_id";
$client_url = "client_id=$client_id&";
} else {
require_once "includes/inc_client_overview_all.php";
$client_query = '';
$client_url = '';
}
// Perms
enforceUserPermission('module_support');
$can_edit = lookupUserPermission('module_support') >= 2;
$can_delete = lookupUserPermission('module_support') >= 3;
// Archived - from All Client Docs, an archived client's racks count as archived too
$archived = (isset($_GET['archived']) && $_GET['archived'] == 1) ? 1 : 0;
if ($client_url) {
$archive_query = $archived ? "rack_archived_at IS NOT NULL" : "rack_archived_at IS NULL";
} else {
$archive_query = $archived
? "(rack_archived_at IS NOT NULL OR client_archived_at IS NOT NULL)"
: "(rack_archived_at IS NULL AND client_archived_at IS NULL)";
}
// Client filter (All Client Docs only)
$client_filter = 0;
if (!$client_url && !empty($_GET['client'])) {
$client_filter = intval($_GET['client']);
$client_query = "AND rack_client_id = $client_filter";
}
// Location filter (one client only)
$location_filter = 0;
$location_query = '';
if ($client_url && !empty($_GET['location'])) {
$location_filter = intval($_GET['location']);
$location_query = "AND rack_location_id = $location_filter";
}
// Only these sort - filter_header.php will hand through any lowercase word
if (!in_array($sort, ['rack_name', 'rack_units', 'client_name', 'location_name', 'rack_created_at'], true)) {
$sort = 'rack_name';
}
$sql = mysqli_query(
$mysqli,
"SELECT SQL_CALC_FOUND_ROWS location_name, rack_created_at, rack_depth, rack_description, rack_id, rack_location_id,
rack_model, rack_name, rack_notes, rack_photo, rack_physical_location, rack_type,
rack_units FROM racks
"SELECT SQL_CALC_FOUND_ROWS client_id, client_name, location_name, rack_id, rack_client_id, rack_name, rack_type,
rack_model, rack_units, rack_units_descending, rack_power_capacity, rack_physical_location, rack_archived_at
FROM racks
LEFT JOIN clients ON client_id = rack_client_id
LEFT JOIN locations ON location_id = rack_location_id
WHERE rack_client_id = $client_id
AND rack_$archive_query
AND (rack_name LIKE '%$q%' OR rack_type LIKE '%$q%' OR rack_units LIKE '%$q%')
WHERE $archive_query
AND (rack_name LIKE '%$q%' OR rack_type LIKE '%$q%' OR rack_model LIKE '%$q%' OR rack_description LIKE '%$q%'
OR rack_physical_location LIKE '%$q%' OR location_name LIKE '%$q%' OR client_name LIKE '%$q%'
OR EXISTS (SELECT 1 FROM rack_units LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_rack_id = rack_id AND (unit_device LIKE '%$q%' OR asset_name LIKE '%$q%' OR asset_serial LIKE '%$q%')))
" . clientScopeSql('rack_client_id') . "
$client_query
$location_query
ORDER BY $sort $order LIMIT $record_from, $record_to"
);
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$racks = [];
while ($row = mysqli_fetch_assoc($sql)) {
$racks[intval($row['rack_id'])] = $row;
}
// Every item on the page in one query, not one per rack
$racks_units = rackLoadUnits(array_keys($racks));
// Totals across what's listed, for the summary line
$total_units = 0;
$total_used = 0;
$total_items = 0;
foreach ($racks as $rack_id => $row) {
$racks[$rack_id]['occupancy'] = rackOccupancy($racks_units[$rack_id], max(1, intval($row['rack_units'])));
$total_units += max(1, intval($row['rack_units']));
$total_used += $racks[$rack_id]['occupancy']['any'];
$total_items += count($racks_units[$rack_id]);
}
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-server me-2"></i>Network Racks</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/rack/rack_add.php?client_id=<?= $client_id ?>">
<i class="fas fa-plus me-2"></i>New Rack
</button>
</div>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-server me-2"></i>Racks</h3>
<?php if ($client_url && $can_edit) { ?>
<div class="card-tools">
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/rack/rack_add.php?client_id=<?= $client_id ?>">
<i class="fas fa-plus me-2"></i>New Rack
</button>
</div>
<?php } ?>
</div>
<div class="card-body">
<div class="card-header py-3">
<form autocomplete="off">
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<input type="hidden" name="archived" value="<?= $archived ?>">
<div class="row">
<div class="row g-2 align-items-center">
<div class="col-md-4">
<div class="input-group mb-3 mb-md-0">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search Racks">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search racks and what's in them">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-md-8">
<div class="float-end">
<a href="?client_id=<?= $client_id ?>&archived=<?php if($archived == 1){ echo 0; } else { echo 1; } ?>"
class="btn btn-<?php if($archived == 1){ echo "primary"; } else { echo "default"; } ?>">
<i class="fa fa-fw fa-archive me-2"></i>Archived
</a>
<?php if ($client_url) { ?>
<div class="col-md-3">
<select class="form-select select2" name="location" onchange="this.form.submit()">
<option value="">- All Locations -</option>
<?php
$sql_locations_filter = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations
WHERE location_client_id = $client_id
AND (EXISTS (SELECT 1 FROM racks WHERE rack_location_id = location_id) OR location_id = $location_filter)
ORDER BY location_name ASC");
while ($row = mysqli_fetch_assoc($sql_locations_filter)) {
$location_id_filter = intval($row['location_id']);
?>
<option value="<?= $location_id_filter ?>" <?php if ($location_filter === $location_id_filter) { echo "selected"; } ?>><?= escapeHtml($row['location_name']) ?></option>
<?php } ?>
</select>
</div>
<?php } else { ?>
<div class="col-md-3">
<select class="form-select select2" name="client" onchange="this.form.submit()">
<option value="">- All Clients -</option>
<?php
$sql_clients_filter = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name, client_abbreviation FROM clients
JOIN racks ON rack_client_id = client_id
WHERE 1 = 1
" . clientScopeSql('clients.client_id') . "
ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
$client_id_filter = intval($row['client_id']);
?>
<option value="<?= $client_id_filter ?>" <?php if ($client_filter === $client_id_filter) { echo "selected"; } ?><?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
<div class="col-md-5 d-flex align-items-center justify-content-md-end gap-3">
<?php if ($racks) { ?>
<span class="small text-body-secondary d-none d-lg-inline">
<?= number_format($total_used) ?> of <?= number_format($total_units) ?>U in use &middot; <?= number_format($total_items) ?> items<?= intval($num_rows[0]) > count($racks) ? ' on this page' : '' ?>
</span>
<?php } ?>
<a href="?<?= $client_url ?>archived=<?= $archived ? 0 : 1 ?>" class="btn btn-<?= $archived ? 'primary' : 'default' ?>">
<i class="fa fa-fw fa-archive me-2"></i>Archived
</a>
</div>
</div>
</form>
<hr>
</div>
<div class="row">
<div class="card-body">
<?php
while ($row = mysqli_fetch_assoc($sql)) {
$rack_id = intval($row['rack_id']);
$rack_name = escapeHtml($row['rack_name']);
$rack_description = escapeHtml($row['rack_description']);
$rack_model = escapeHtml($row['rack_model']);
$rack_depth = escapeHtml($row['rack_depth']);
$rack_type = escapeHtml($row['rack_type']);
$rack_units = intval($row['rack_units']);
$rack_photo = escapeHtml($row['rack_photo']);
$rack_physical_location = escapeHtml($row['rack_physical_location']);
$rack_notes = escapeHtml($row['rack_notes']);
$rack_location_id = escapeHtml($row['rack_location_id']);
$rack_location_name = escapeHtml($row['location_name']);
$rack_created_at = escapeHtml($row['rack_created_at']);
<?php if (!$racks) { ?>
// Fetch rack units
$unit_sql = mysqli_query($mysqli, "SELECT * FROM rack_units LEFT JOIN assets ON unit_asset_id = asset_id WHERE unit_rack_id = $rack_id ORDER BY unit_start_number ASC");
$rack_units_data = [];
while ($unit_row = mysqli_fetch_assoc($unit_sql)) {
$rack_units_data[] = $unit_row;
}
<div class="text-center text-body-secondary py-5">
<i class="fas fa-server fa-3x mb-3 opacity-25"></i>
<?php if ($q || $location_filter || $client_filter) { ?>
<div class="fs-5">No racks match that</div>
<?php } elseif ($archived) { ?>
<div class="fs-5">No archived racks</div>
<?php } else { ?>
<div class="fs-5 mb-1">No racks yet</div>
<div class="mb-3">Document the comms closet: what's racked where, front and rear, and how much room and power is left.</div>
<?php if ($client_url && $can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/rack/rack_add.php?client_id=<?= $client_id ?>">
<i class="fas fa-plus me-2"></i>New Rack
</button>
<?php } ?>
<?php } ?>
</div>
?>
<div class="col-md-6">
<?php } else { ?>
<div class="card card-dark">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-server me-2"></i><?= "$rack_name - $rack_units" ?>U</h3>
<div class="row g-3">
<?php foreach ($racks as $rack_id => $row) {
$rack_client_id = intval($row['rack_client_id']);
$rack_name = escapeHtml($row['rack_name']);
$rack_type = escapeHtml($row['rack_type']);
$rack_units = max(1, intval($row['rack_units']));
$rack_units_descending = intval($row['rack_units_descending']);
$rack_power_capacity = intval($row['rack_power_capacity']);
$rack_physical_location = escapeHtml($row['rack_physical_location']);
$rack_location_name = escapeHtml($row['location_name']);
$rack_client_name = escapeHtml($row['client_name']);
$rack_archived_at = $row['rack_archived_at'];
$occupancy = $row['occupancy'];
$used_percent = (int) round($occupancy['any'] / $rack_units * 100);
$usage_tone = $used_percent >= 90 ? 'danger' : ($used_percent >= 75 ? 'warning' : 'primary');
$rack_items = array_map('rackUnitView', $racks_units[$rack_id]);
$power_used = array_sum(array_column($rack_items, 'power'));
$rack_url = "rack.php?client_id=$rack_client_id&rack_id=$rack_id";
?>
<div class="col-md-6 col-xl-4 col-xxl-3">
<div class="card h-100 mb-0 itflow-rack-card">
<div class="card-body d-flex gap-3">
<div class="card-tools">
<div class="dropdown dropstart">
<button class="btn btn-tool" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="modals/rack/rack_device_add.php?id=<?= $rack_id ?>">
<i class="fas fa-fw fa-plus text-secondary me-2"></i>Add Device
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="modals/rack/rack_edit.php?id=<?= $rack_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<?php if ($session_user_role == 3) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
<?php /* The front, to scale: a full-depth item from the rear fills it too */ ?>
<div class="itflow-rack-mini" style="--rack-rows: <?= $rack_units ?>" aria-hidden="true">
<?php foreach ($rack_items as $item) {
if (!rackUnitOnFace($item['face'], $item['full_depth'], 'front')) {
continue;
} ?>
<span class="itflow-rack-tone-<?= $item['tone'] ?><?= $item['face'] !== 'front' ? ' is-ghost' : '' ?>" style="grid-row: <?= rackGridRow($item['start'], $item['end'], $rack_units, $rack_units_descending) ?> / span <?= $item['height'] ?>"></span>
<?php } ?>
</div>
<div class="flex-grow-1 min-w-0 d-flex flex-column">
<div class="d-flex align-items-start gap-2">
<div class="min-w-0 flex-grow-1">
<a class="stretched-link text-reset text-decoration-none" href="<?= $rack_url ?>">
<h3 class="h6 fw-semibold mb-0 text-truncate" title="<?= $rack_name ?>"><?= $rack_name ?></h3>
</a>
<?php if (!$client_url) { ?>
<div class="small text-truncate"><?= $rack_client_name ?></div>
<?php } ?>
<div class="small text-body-secondary text-truncate">
<?= $rack_units ?>U<?= $rack_type ? " &middot; $rack_type" : '' ?>
</div>
</div>
<?php if ($rack_archived_at) { ?>
<span class="badge rounded-pill text-bg-secondary fw-normal">Archived</span>
<?php } ?>
<?php if ($can_edit) { ?>
<div class="dropdown dropstart itflow-rack-card-menu">
<button class="btn btn-sm btn-link text-body-secondary px-1" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<?php if (!$rack_archived_at) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/rack/rack_device_add.php?id=<?= $rack_id ?>">
<i class="fas fa-fw fa-plus text-secondary me-2"></i>Add Item
</a>
<?php } ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/rack/rack_edit.php?id=<?= $rack_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<?php if ($rack_archived_at) { ?>
<a class="dropdown-item confirm-link" href="post.php?restore_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-redo text-secondary me-2"></i>Restore
</a>
<?php } else { ?>
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</a>
<?php } ?>
<?php if ($can_delete) { ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_rack=<?= $rack_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<?php if ($rack_photo) { ?>
<img class="img-thumbnail mb-3" alt="rack_photo" src="<?= "../uploads/clients/$client_id/$rack_photo" ?>">
<?php if ($rack_location_name || $rack_physical_location) { ?>
<div class="small text-body-secondary text-truncate mt-1">
<i class="fas fa-fw fa-map-marker-alt me-1"></i><?= $rack_location_name ?><?= $rack_location_name && $rack_physical_location ? ' &rsaquo; ' : '' ?><?= $rack_physical_location ?>
</div>
<?php } ?>
<table class="table table-sm table-borderless border">
<tbody>
<?php if ($rack_description) { ?>
<tr>
<th colspan="2">Description</th>
</tr>
<tr>
<td colspan="2"><?= $rack_description ?></td>
</tr>
<div class="mt-auto pt-3">
<div class="d-flex justify-content-between small mb-1">
<span><span class="fw-semibold"><?= $occupancy['any'] ?></span><span class="text-body-secondary"> / <?= $rack_units ?>U used</span></span>
<span class="text-<?= $usage_tone ?>-emphasis fw-semibold"><?= $used_percent ?>%</span>
</div>
<div class="progress" style="height: .375rem" role="progressbar" aria-label="Units used" aria-valuenow="<?= $used_percent ?>" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar bg-<?= $usage_tone ?>" style="width: <?= $used_percent ?>%"></div>
</div>
<div class="d-flex flex-wrap column-gap-3 small text-body-secondary mt-2">
<span><i class="fas fa-fw fa-cubes me-1"></i><?= count($rack_items) ?> item<?= count($rack_items) === 1 ? '' : 's' ?></span>
<?php if ($occupancy['largest_gap']['size']) { ?>
<span title="The tallest full-depth item that still fits"><i class="fas fa-fw fa-arrows-alt-v me-1"></i><?= $occupancy['largest_gap']['size'] ?>U gap</span>
<?php } ?>
<?php if ($rack_type) { ?>
<tr>
<th>Type</th>
<td><?= $rack_type ?></td>
</tr>
<?php if ($power_used || $rack_power_capacity) { ?>
<span class="<?= $rack_power_capacity && $power_used > $rack_power_capacity ? 'text-danger' : '' ?>">
<i class="fas fa-fw fa-bolt me-1"></i><?= number_format($power_used) ?><?= $rack_power_capacity ? ' / ' . number_format($rack_power_capacity) : '' ?> W
</span>
<?php } ?>
<?php if ($rack_model) { ?>
<tr>
<th>Model</th>
<td><?= $rack_model ?></td>
</tr>
<?php } ?>
<?php if ($rack_depth) { ?>
<tr>
<th>Depth</th>
<td><?= $rack_depth ?></td>
</tr>
<?php } ?>
<?php if ($rack_location_name) { ?>
<tr>
<th>Location</th>
<td><?= $rack_location_name ?></td>
</tr>
<?php } ?>
<?php if ($rack_physical_location) { ?>
<tr>
<th>Physical Location</th>
<td><?= $rack_physical_location ?></td>
</tr>
<?php } ?>
<?php if ($rack_notes) { ?>
<tr>
<th colspan="2">Notes</th>
</tr>
<tr>
<td><?= $rack_notes ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<table class="table table-sm border">
<thead class="table-dark">
<tr>
<th class="text-center px-0">U</th>
<th class="text-center">Device</th>
<th class=""></th>
</tr>
</thead>
<tbody>
<?php
// Keep track of which device_ids we've already printed
$printedDevices = [];
for ($i = $rack_units; $i >= 1; $i--) {
// Find all devices that occupy the current unit $i
$unit_devices = [];
foreach ($rack_units_data as $unit_data) {
$start = (int) $unit_data['unit_start_number'];
$end = (int) $unit_data['unit_end_number'];
// If $i is between start and end, device occupies this unit
if ($i >= $start && $i <= $end) {
$unit_devices[] = [
'unit_id' => (int) $unit_data['unit_id'],
'unit_device' => escapeHtml($unit_data['unit_device']),
'unit_start_number'=> $start,
'unit_end_number' => $end,
'asset_id' => (int) $unit_data['asset_id'],
'asset_name' => escapeHtml($unit_data['asset_name']),
'asset_type' => escapeHtml($unit_data['asset_type']),
'icon' => getAssetIcon($unit_data['asset_type'])
];
}
}
?>
<tr>
<!-- Always print the left-hand U #, for reference -->
<td class="px-0 text-center bg-light border">
<?= sprintf('%02d', $i) ?>
</td>
<?php
// If there's exactly one device in this row, attempt to rowSpan it.
// (If you can have multiple overlapping devices, you'll need more logic.)
if (count($unit_devices) === 1) {
$d = $unit_devices[0];
$deviceId = $d['unit_id'];
// If not already printed, this is the *first* row of the device
if (!in_array($deviceId, $printedDevices)) {
// Mark it printed so it won't appear in later rows
$printedDevices[] = $deviceId;
// Calculate how many rows (U's) it spans
$span = $d['unit_end_number'] - $d['unit_start_number'] + 1;
if ($span < 1) {
$span = 1; // safety check
}
// Print the device cell and action cell with rowSpan
?>
<td class="text-center align-middle" rowspan="<?= $span ?>">
<!-- DEVICE INFO HERE -->
<?php
echo $d['unit_device'];
if (!empty($d['asset_name'])) {
$icon = $d['icon']; // already from getAssetIcon
?>
<i class="fa fa-<?= $icon ?>"></i>
<a href="asset.php?client_id=<?= $client_id ?>&asset_id=<?= $d['asset_id'] ?>"
target="_blank">
<?= $d['asset_name'] ?>
<i class="fas fa-external-link-alt ms-1"></i>
</a>
<?php
}
?>
</td>
<td class="px-0 text-end align-middle" rowspan="<?= $span ?>">
<!-- ACTION ICON / DROPDOWN -->
<div class="dropdown dropstart">
<button class="btn btn-tool" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item text-danger text-bold confirm-link"
href="post.php?remove_rack_unit=<?= $d['unit_id'] ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-minus me-2"></i>Remove
</a>
</div>
</div>
</td>
<?php
} else {
// This device was already spanned from a higher row, so skip printing device cell
// but we still have the left column (U #).
}
} elseif (count($unit_devices) > 1) {
// If your data might have multiple devices in the same row,
// you have to decide how to handle them.
// For now, we can fallback to older logic or display them all in one cell, etc.
?>
<td class="text-center">
<?php foreach ($unit_devices as $d) { ?>
<?= $d['unit_device'] ?><br>
<?php // Could also show asset_name, etc. ?>
<?php } ?>
</td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-tool" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<?php foreach ($unit_devices as $d) { ?>
<a class="dropdown-item text-danger text-bold confirm-link"
href="post.php?remove_rack_unit=<?= $d['unit_id'] ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-minus me-2"></i>Remove
</a>
<?php } ?>
</div>
</div>
</td>
<?php
} else {
// No device in this row
?>
<td class="text-center text-secondary">--</td>
<td></td>
<?php
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<?php
// Paging only - the empty state above is this page's own
if (intval($num_rows[0]) > 0) {
require_once "../includes/filter_footer.php";
}
?>
</div>
<?php

View File

@@ -24,6 +24,9 @@ if (!empty($asset_id)) {
// Delete Interfaces
mysqli_query($mysqli,"DELETE FROM asset_interfaces WHERE interface_asset_id = $asset_id");
// And take it out of any rack
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
// Logging
logAudit("Asset", "Delete", "$asset_name via API ($api_key_name)", $client_id);
}

View File

@@ -17,6 +17,7 @@ if (!empty($client_id)) {
mysqli_query($mysqli, "DELETE FROM documents WHERE document_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM contacts WHERE contact_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM assets WHERE asset_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM racks WHERE rack_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM domains WHERE domain_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM calendar_events WHERE event_client_id = $client_id");
mysqli_query($mysqli, "DELETE FROM files WHERE file_client_id = $client_id");

View File

@@ -3150,3 +3150,395 @@ button.itflow-client-nav-identity:focus-visible {
--itflow-dash-tone: transparent;
flex-basis: 12rem;
}
/* Racks - agent/racks.php, agent/rack.php, agent/includes/rack_elevation.php
A rack is drawn as a cabinet: dark frame, numbered rails either side and a
bay with one CSS grid row per U. Items are placed by grid-row (PHP works out
the row from the U and which way the rack is numbered), empty U are buttons
that open "add here". The frame stays dark in both themes - it is a picture
of a rack, not page chrome - so its colours are fixed rather than taken from
the Bootstrap variables.
The row height shrinks for tall racks so a 42U rack still fits a screen. */
.min-w-0 {
min-width: 0;
}
.itflow-rack-pair {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 1.5rem;
}
.itflow-rack {
--rack-u: clamp(1.3rem, calc(60rem / var(--rack-rows)), 1.75rem);
flex: 1 1 19rem;
max-width: 30rem;
}
.itflow-rack-cap {
margin-bottom: .35rem;
font-size: .7rem;
font-weight: 600;
letter-spacing: .08em;
text-align: center;
text-transform: uppercase;
color: var(--bs-secondary-color);
}
.itflow-rack-frame {
display: flex;
padding: .5rem .3rem;
border-radius: .75rem;
background: linear-gradient(180deg, #2b3035, #212529);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .06), 0 .25rem .75rem rgba(0, 0, 0, .18);
}
.itflow-rack-rail {
display: grid;
flex: 0 0 1.75rem;
grid-template-rows: repeat(var(--rack-rows), var(--rack-u));
}
.itflow-rack-rail span {
display: flex;
align-items: center;
justify-content: center;
font-family: var(--bs-font-monospace);
font-size: .62rem;
color: rgba(255, 255, 255, .42);
}
.itflow-rack-bay {
position: relative;
display: grid;
flex: 1 1 auto;
min-width: 0;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: repeat(var(--rack-rows), var(--rack-u));
border-right: 2px solid #3a4148;
border-left: 2px solid #3a4148;
background-color: #15181b;
background-image: repeating-linear-gradient(to bottom, transparent 0, transparent calc(var(--rack-u) - 1px), rgba(255, 255, 255, .05) calc(var(--rack-u) - 1px), rgba(255, 255, 255, .05) var(--rack-u));
}
.itflow-rack-slot {
grid-column: 1;
display: flex;
align-items: center;
justify-content: center;
margin: 1px 2px;
padding: 0;
border: 1px dashed transparent;
border-radius: .3rem;
background: transparent;
font-size: .7rem;
color: rgba(255, 255, 255, .85);
}
.itflow-rack-slot span {
opacity: 0;
transition: opacity .12s ease-in-out;
}
button.itflow-rack-slot:hover,
button.itflow-rack-slot:focus-visible {
border-color: rgba(255, 255, 255, .35);
background-color: rgba(255, 255, 255, .07);
outline: 0;
}
button.itflow-rack-slot:hover span,
button.itflow-rack-slot:focus-visible span {
opacity: 1;
}
/* Items */
.itflow-rack-item {
position: relative;
grid-column: 1;
margin: 1px 2px;
overflow: hidden;
border-radius: .3rem;
color: #fff;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .14), inset 0 -1px 0 rgba(0, 0, 0, .25), 0 1px 2px rgba(0, 0, 0, .45);
}
.itflow-rack-item-body {
display: flex;
align-items: center;
gap: .5rem;
width: 100%;
height: 100%;
padding: 0 .5rem;
border: 0;
background: transparent;
font: inherit;
text-align: left;
color: inherit;
text-decoration: none;
}
a.itflow-rack-item-body:hover,
button.itflow-rack-item-body:hover {
color: inherit;
background-color: rgba(255, 255, 255, .08);
}
.itflow-rack-item-body:focus-visible {
outline: 2px solid #fff;
outline-offset: -2px;
}
.itflow-rack-item-icon {
flex: 0 0 auto;
font-size: .8rem;
opacity: .9;
}
.itflow-rack-item-text {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-width: 0;
line-height: 1.15;
}
.itflow-rack-item-name,
.itflow-rack-item-meta {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.itflow-rack-item-name {
font-size: .78rem;
font-weight: 600;
}
.itflow-rack-item-meta {
font-size: .68rem;
opacity: .78;
}
/* One U is one line: the name, then the quieter text beside it - which gives
way first when the line is short */
.itflow-rack-h1 .itflow-rack-item-text {
flex-direction: row;
align-items: baseline;
gap: .5rem;
}
.itflow-rack-h1 .itflow-rack-item-name {
flex: 0 1 auto;
max-width: 75%;
}
.itflow-rack-h1 .itflow-rack-item-meta {
flex: 1 1 0;
min-width: 0;
}
.itflow-rack-item-pos {
flex: 0 0 auto;
margin-left: auto;
font-family: var(--bs-font-monospace);
font-size: .62rem;
opacity: .6;
}
.itflow-rack-item-edit {
position: absolute;
top: 50%;
right: .3rem;
display: flex;
align-items: center;
justify-content: center;
width: 1.35rem;
height: 1.2rem;
margin-top: -.6rem;
padding: 0;
border: 0;
border-radius: .25rem;
background-color: rgba(0, 0, 0, .35);
font-size: .6rem;
color: #fff;
opacity: 0;
transition: opacity .12s ease-in-out;
}
.itflow-rack-item:hover .itflow-rack-item-edit,
.itflow-rack-item:focus-within .itflow-rack-item-edit {
opacity: 1;
}
.itflow-rack-item:has(.itflow-rack-item-edit):hover .itflow-rack-item-pos {
visibility: hidden;
}
.itflow-rack-item-edit:hover {
background-color: rgba(0, 0, 0, .55);
}
.itflow-rack-item.is-archived {
opacity: .55;
}
.itflow-rack-item.is-archived .itflow-rack-item-name {
text-decoration: line-through;
}
/* A full-depth item seen from its other side: it fills this face too */
.itflow-rack-item.is-ghost {
border: 1px dashed rgba(255, 255, 255, .16);
background: repeating-linear-gradient(45deg, rgba(255, 255, 255, .06) 0, rgba(255, 255, 255, .06) 5px, transparent 5px, transparent 10px), #1c2024;
color: rgba(255, 255, 255, .55);
box-shadow: none;
}
.itflow-rack-item.is-ghost .itflow-rack-item-body {
cursor: default;
}
/* Tones - the faceplate colour of each kind of kit, shared by the elevation,
the mini racks on the listing, the list chips and the legend */
.itflow-rack-tone-server { background: linear-gradient(180deg, #3d72bb, #2c5891); }
.itflow-rack-tone-network { background: linear-gradient(180deg, #27907f, #1b6c60); }
.itflow-rack-tone-firewall { background: linear-gradient(180deg, #c04e4e, #963838); }
.itflow-rack-tone-power { background: linear-gradient(180deg, #b8862f, #8e6420); }
.itflow-rack-tone-device { background: linear-gradient(180deg, #6d5fc4, #5447a1); }
.itflow-rack-tone-shelf { background: linear-gradient(180deg, #6b7682, #57616c); }
.itflow-rack-tone-patch {
background: radial-gradient(rgba(0, 0, 0, .38) 1.2px, transparent 1.7px) 0 0 / 7px 7px, linear-gradient(180deg, #4d5864, #3b444e);
}
.itflow-rack-tone-cable {
background: repeating-linear-gradient(90deg, rgba(255, 255, 255, .08) 0, rgba(255, 255, 255, .08) 2px, transparent 2px, transparent 9px), linear-gradient(180deg, #31373d, #262b30);
}
.itflow-rack-tone-blank {
background: repeating-linear-gradient(90deg, rgba(255, 255, 255, .05) 0, rgba(255, 255, 255, .05) 10px, transparent 10px, transparent 13px), #1f2327;
color: rgba(255, 255, 255, .7);
}
/* Small coloured tile with the item's icon - item list, "not racked yet" */
.itflow-rack-chip {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
width: 1.9rem;
height: 1.9rem;
border-radius: var(--bs-border-radius);
font-size: .8rem;
color: #fff;
}
.itflow-rack-legend {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: .35rem 1.1rem;
}
.itflow-rack-swatch {
display: inline-block;
width: .75rem;
height: .75rem;
margin-right: .35rem;
border-radius: .2rem;
vertical-align: -.1rem;
}
.itflow-rack-swatch-ghost {
border: 1px dashed var(--bs-secondary-color);
background: repeating-linear-gradient(45deg, var(--bs-secondary-bg) 0, var(--bs-secondary-bg) 2px, transparent 2px, transparent 4px);
}
/* Rack page header and side cards */
.itflow-rack-head-icon {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
width: 3rem;
height: 3rem;
border-radius: var(--bs-border-radius-lg);
background: linear-gradient(180deg, #2b3035, #1c1f23);
font-size: 1.2rem;
color: #fff;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .08);
}
.itflow-rack-dl {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: .4rem 1rem;
font-size: .875rem;
}
.itflow-rack-dl dt {
font-weight: 500;
color: var(--bs-secondary-color);
}
.itflow-rack-dl dd {
margin: 0;
overflow-wrap: anywhere;
}
.itflow-rack-stats .fw-semibold {
font-size: 1.1rem;
}
.itflow-rack-photo {
position: relative;
display: block;
overflow: hidden;
border-radius: var(--bs-border-radius);
}
.itflow-rack-photo img {
display: block;
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
transition: transform .2s ease-in-out;
}
.itflow-rack-photo:hover img {
transform: scale(1.04);
}
.itflow-rack-photo span {
position: absolute;
bottom: .35rem;
left: .35rem;
padding: .05rem .5rem;
border-radius: 50rem;
background-color: rgba(0, 0, 0, .6);
font-size: .7rem;
color: #fff;
}
.itflow-rack-form-photo img {
max-width: 100%;
max-height: 8rem;
border-radius: var(--bs-border-radius);
}
.itflow-rack-fit:empty {
display: none;
}
/* Listing cards: the whole card opens the rack, the menu sits above that link */
.itflow-rack-card {
transition: box-shadow .15s ease-in-out, border-color .15s ease-in-out;
}
.itflow-rack-card:hover {
border-color: var(--itflow-accent, var(--bs-primary));
box-shadow: 0 .25rem .9rem rgba(0, 0, 0, .1);
}
.itflow-rack-card-menu {
position: relative;
z-index: 2;
}
.itflow-rack-mini {
display: grid;
flex: 0 0 2.4rem;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: repeat(var(--rack-rows), minmax(0, 1fr));
align-self: flex-start;
height: clamp(5.5rem, calc(var(--rack-rows) * .32rem), 9rem);
padding: 2px;
border: 3px solid #2b3035;
border-radius: .4rem;
background-color: #15181b;
}
.itflow-rack-mini span {
grid-column: 1;
margin: .5px 0;
border-radius: 1px;
}
.itflow-rack-mini span.is-ghost {
opacity: .45;
}
@media print {
.itflow-rack-frame,
.itflow-rack-bay,
.itflow-rack-item,
.itflow-rack-chip,
.itflow-rack-swatch,
.itflow-rack-head-icon {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.itflow-rack-slot span,
.itflow-rack-item-edit {
display: none;
}
.itflow-rack {
--rack-u: clamp(1rem, calc(48rem / var(--rack-rows)), 1.5rem);
}
.itflow-rack-items,
.itflow-rack-pair {
break-inside: avoid;
}
}

9
db.sql
View File

@@ -1862,6 +1862,11 @@ CREATE TABLE `rack_units` (
`unit_start_number` int(11) NOT NULL,
`unit_end_number` int(11) NOT NULL,
`unit_device` varchar(200) DEFAULT NULL,
`unit_face` varchar(10) NOT NULL DEFAULT 'front',
`unit_full_depth` tinyint(1) NOT NULL DEFAULT 1,
`unit_type` varchar(50) DEFAULT NULL,
`unit_power_watts` int(11) DEFAULT NULL,
`unit_notes` varchar(255) DEFAULT NULL,
`unit_created_at` datetime NOT NULL DEFAULT current_timestamp(),
`unit_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
`unit_archived_at` datetime DEFAULT NULL,
@@ -1869,6 +1874,7 @@ CREATE TABLE `rack_units` (
`unit_rack_id` int(11) NOT NULL,
PRIMARY KEY (`unit_id`),
KEY `unit_rack_id` (`unit_rack_id`),
KEY `unit_asset_id` (`unit_asset_id`),
CONSTRAINT `rack_units_ibfk_1` FOREIGN KEY (`unit_rack_id`) REFERENCES `racks` (`rack_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -1888,7 +1894,10 @@ CREATE TABLE `racks` (
`rack_depth` varchar(50) DEFAULT NULL,
`rack_type` varchar(50) DEFAULT NULL,
`rack_units` int(11) NOT NULL,
`rack_units_descending` tinyint(1) NOT NULL DEFAULT 0,
`rack_power_capacity` int(11) DEFAULT NULL,
`rack_photo` varchar(200) DEFAULT NULL,
`rack_photo_rear` varchar(200) DEFAULT NULL,
`rack_physical_location` varchar(200) DEFAULT NULL,
`rack_notes` text DEFAULT NULL,
`rack_favorite` tinyint(1) NOT NULL DEFAULT 0,

View File

@@ -18,6 +18,7 @@ require_once __DIR__ . '/functions/request.php';
require_once __DIR__ . '/functions/files.php';
require_once __DIR__ . '/functions/domain.php';
require_once __DIR__ . '/functions/network.php';
require_once __DIR__ . '/functions/rack.php';
require_once __DIR__ . '/functions/auth.php';
require_once __DIR__ . '/functions/logging.php';
require_once __DIR__ . '/functions/app.php';

335
functions/rack.php Normal file
View File

@@ -0,0 +1,335 @@
<?php
/*
* Racks - rack elevation layout, occupancy and the checks shared by the rack
* handlers (agent/post/rack.php), the rack page (agent/rack.php) and the racks
* listing (agent/racks.php).
*
* Positions: an item occupies unit_start_number..unit_end_number, start being
* the LOWEST U number. That is storage only - whether U1 is drawn at the bottom
* (the usual) or at the top is the rack's rack_units_descending flag.
*
* Faces: an item is mounted on the front or the rear. A full-depth item (most
* servers, a UPS) fills both faces at its units; a half-depth one (a patch
* panel, a small switch) leaves the other face free for something else.
*/
/** Unlinked rack items - things worth documenting that are not assets. */
function rackItemTypes() {
return [
'Device' => ['icon' => 'fa-hdd', 'tone' => 'device'],
'Patch Panel' => ['icon' => 'fa-ethernet', 'tone' => 'patch'],
'Cable Management' => ['icon' => 'fa-grip-lines', 'tone' => 'cable'],
'Shelf' => ['icon' => 'fa-layer-group', 'tone' => 'shelf'],
'PDU' => ['icon' => 'fa-plug', 'tone' => 'power'],
'UPS' => ['icon' => 'fa-car-battery', 'tone' => 'power'],
'KVM / Console' => ['icon' => 'fa-keyboard', 'tone' => 'device'],
'Blanking Panel' => ['icon' => 'fa-minus', 'tone' => 'blank'],
];
}
/**
* How an item is drawn: its icon, colour tone and a type label. A linked asset
* goes by its asset type, an unlinked item by its rack item type.
*/
function rackItemStyle($asset_type, $unit_type, $has_asset) {
if ($has_asset) {
$tones = [
'Server' => 'server',
'Virtual Machine' => 'server',
'Switch' => 'network',
'Access Point' => 'network',
'Firewall/Router' => 'firewall',
];
$asset_type = (string) $asset_type;
return [
'icon' => 'fa-' . getAssetIcon($asset_type),
'tone' => $tones[$asset_type] ?? 'device',
'label' => $asset_type !== '' ? $asset_type : 'Asset',
];
}
$types = rackItemTypes();
$unit_type = isset($types[$unit_type]) ? $unit_type : 'Device';
return [
'icon' => $types[$unit_type]['icon'],
'tone' => $types[$unit_type]['tone'],
'label' => $unit_type,
];
}
/** "U7" or "U7-U8" (with an en dash) */
function rackPositionLabel($start, $end) {
$start = intval($start);
$end = intval($end);
return $start === $end ? "U$start" : "U$start&ndash;U$end";
}
/** Does an item mounted like this fill the given face? */
function rackUnitOnFace($unit_face, $unit_full_depth, $face) {
return $unit_full_depth || $unit_face === $face;
}
/**
* Units in use per face, plus the rack as a whole. A U counts as used on a face
* when anything fills that face there, and as used for the rack when it is used
* on either face - a half-depth panel at the front still takes the U.
*
* $units: rows with unit_start_number, unit_end_number, unit_face, unit_full_depth
* Returns front/rear/any (counts), free_any (count of U with nothing on either
* face) and largest_gap ['size', 'start', 'end'] - the biggest run of U that is
* free on BOTH faces, i.e. where a full-depth item could still go.
*/
function rackOccupancy(array $units, $rack_units) {
$rack_units = max(0, intval($rack_units));
$front = array_fill(1, max(1, $rack_units), false);
$rear = $front;
foreach ($units as $unit) {
$start = max(1, intval($unit['unit_start_number']));
$end = min($rack_units, intval($unit['unit_end_number']));
$face = ($unit['unit_face'] ?? 'front') === 'rear' ? 'rear' : 'front';
$full_depth = intval($unit['unit_full_depth'] ?? 1) === 1;
for ($u = $start; $u <= $end; $u++) {
if (rackUnitOnFace($face, $full_depth, 'front')) {
$front[$u] = true;
}
if (rackUnitOnFace($face, $full_depth, 'rear')) {
$rear[$u] = true;
}
}
}
$used_front = 0;
$used_rear = 0;
$used_any = 0;
$gap = ['size' => 0, 'start' => 0, 'end' => 0];
$run_start = 0;
for ($u = 1; $u <= $rack_units; $u++) {
$used_front += $front[$u] ? 1 : 0;
$used_rear += $rear[$u] ? 1 : 0;
$taken = $front[$u] || $rear[$u];
$used_any += $taken ? 1 : 0;
if (!$taken) {
if (!$run_start) {
$run_start = $u;
}
$size = $u - $run_start + 1;
if ($size > $gap['size']) {
$gap = ['size' => $size, 'start' => $run_start, 'end' => $u];
}
} else {
$run_start = 0;
}
}
return [
'front' => $used_front,
'rear' => $used_rear,
'any' => $used_any,
'free_any' => $rack_units - $used_any,
'largest_gap' => $gap,
];
}
/**
* The CSS grid row an item starts on, for a rack drawn one row per U. U1 sits
* at the bottom unless the rack numbers top-down.
*/
function rackGridRow($start, $end, $rack_units, $descending) {
return $descending ? intval($start) : intval($rack_units) - intval($end) + 1;
}
/**
* The first item that would clash with an item at $start..$end on $face, or
* null if the space is free. Two items clash when their units overlap and they
* share a face - which a full-depth item always does. $exclude_unit_id skips
* the item being moved.
*
* Returns the clashing item's display name and position, raw (escape it).
*/
function rackUnitConflict($rack_id, $start, $end, $face, $full_depth, $exclude_unit_id = 0) {
global $mysqli;
$rack_id = intval($rack_id);
$start = intval($start);
$end = intval($end);
$face = $face === 'rear' ? 'rear' : 'front';
$full_depth = $full_depth ? 1 : 0;
$exclude_unit_id = intval($exclude_unit_id);
$sql = mysqli_query($mysqli, "SELECT unit_device, unit_type, unit_start_number, unit_end_number, asset_name
FROM rack_units
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_rack_id = $rack_id
AND unit_id != $exclude_unit_id
AND unit_start_number <= $end AND unit_end_number >= $start
AND (unit_full_depth = 1 OR $full_depth = 1 OR unit_face = '$face')
ORDER BY unit_start_number
LIMIT 1");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
return null;
}
return [
'name' => rackUnitName($row['asset_name'] ?? '', $row['unit_device'], $row['unit_type']),
'start' => intval($row['unit_start_number']),
'end' => intval($row['unit_end_number']),
];
}
/** What to call an item: its asset, else its label, else its type. Raw. */
function rackUnitName($asset_name, $unit_device, $unit_type) {
$asset_name = trim((string) $asset_name);
$unit_device = trim((string) $unit_device);
if ($asset_name !== '') {
return $asset_name;
}
if ($unit_device !== '') {
return $unit_device;
}
return trim((string) $unit_type) !== '' ? (string) $unit_type : 'Unnamed item';
}
/**
* Store an uploaded rack photo under the client's upload folder, removing the
* one it replaces. Returns the stored file name, or '' when no usable file came.
*/
function rackStorePhoto($file, $client_id, $old_photo = '') {
$client_id = intval($client_id);
$new_file_name = checkFileUpload($file, ['jpg', 'jpeg', 'gif', 'png', 'webp']);
if (!$new_file_name) {
return '';
}
$upload_dir = __DIR__ . "/../uploads/clients/$client_id";
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
if (!move_uploaded_file($file['tmp_name'], "$upload_dir/$new_file_name")) {
return '';
}
rackDeletePhoto($client_id, $old_photo);
return $new_file_name;
}
/** Remove a rack photo file, if there is one. Never leaves the client's folder. */
function rackDeletePhoto($client_id, $photo) {
$photo = basename((string) $photo);
if ($photo === '' || $photo === '.' || $photo === '..') {
return;
}
$path = __DIR__ . "/../uploads/clients/" . intval($client_id) . "/$photo";
if (is_file($path)) {
unlink($path);
}
}
/**
* Every item in the given racks, keyed by rack id, with what the rack page and
* listing draw from its asset. Raw rows - escape them (rackUnitView() does).
*/
function rackLoadUnits(array $rack_ids) {
global $mysqli;
$rack_ids = array_filter(array_map('intval', $rack_ids));
$units = array_fill_keys($rack_ids, []);
if (empty($rack_ids)) {
return $units;
}
$sql = mysqli_query($mysqli, "SELECT unit_id, unit_rack_id, unit_start_number, unit_end_number, unit_device,
unit_face, unit_full_depth, unit_type, unit_power_watts, unit_notes,
asset_id, asset_name, asset_type, asset_make, asset_model, asset_serial, asset_status, asset_archived_at,
(SELECT interface_ip FROM asset_interfaces
WHERE interface_asset_id = asset_id AND interface_primary = 1 AND interface_ip IS NOT NULL AND interface_ip != ''
LIMIT 1) AS asset_primary_ip
FROM rack_units
LEFT JOIN assets ON asset_id = unit_asset_id
WHERE unit_rack_id IN (" . implode(',', $rack_ids) . ")
ORDER BY unit_start_number DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$units[intval($row['unit_rack_id'])][] = $row;
}
return $units;
}
/**
* One item, ready to draw. Every string in the result is HTML-escaped; numbers
* are ints. 'name' is what to call it, 'meta' the quieter line under it.
*/
function rackUnitView(array $row) {
$has_asset = intval($row['asset_id'] ?? 0) > 0;
$style = rackItemStyle($row['asset_type'] ?? '', $row['unit_type'] ?? '', $has_asset);
$start = intval($row['unit_start_number']);
$end = max($start, intval($row['unit_end_number']));
$make_model = trim(($row['asset_make'] ?? '') . ' ' . ($row['asset_model'] ?? ''));
$label = trim((string) ($row['unit_device'] ?? ''));
$name = rackUnitName($row['asset_name'] ?? '', $label, $row['unit_type'] ?? '');
// A label that just repeats the asset name ("SRV-01 - Dell R650", how items
// used to be labelled) says nothing the asset doesn't - drop it
$asset_name = trim((string) ($row['asset_name'] ?? ''));
if ($has_asset && $label !== '' && stripos($label, $asset_name) === 0) {
$label = '';
}
// Under the name: the asset's label if it has one, else its make and model.
// An unlinked item gets its type, unless its name already says it.
if ($has_asset) {
$meta = $label !== '' ? $label : $make_model;
} elseif ($label !== '' && stripos($label, $style['label']) === false && $style['label'] !== 'Device') {
$meta = $style['label'];
} else {
$meta = '';
}
return [
'id' => intval($row['unit_id']),
'start' => $start,
'end' => $end,
'height' => $end - $start + 1,
'face' => ($row['unit_face'] ?? 'front') === 'rear' ? 'rear' : 'front',
'full_depth' => intval($row['unit_full_depth'] ?? 1) === 1,
'asset_id' => $has_asset ? intval($row['asset_id']) : 0,
'asset_archived' => $has_asset && !empty($row['asset_archived_at']),
'name' => escapeHtml($name),
'meta' => escapeHtml($meta),
'label' => escapeHtml($label),
'make_model' => escapeHtml($make_model),
'serial' => escapeHtml($row['asset_serial'] ?? ''),
'status' => escapeHtml($row['asset_status'] ?? ''),
'ip' => escapeHtml($row['asset_primary_ip'] ?? ''),
'power' => intval($row['unit_power_watts'] ?? 0),
'notes' => escapeHtml($row['unit_notes'] ?? ''),
'icon' => $style['icon'],
'tone' => $style['tone'],
'type_label' => escapeHtml($style['label']),
'position' => rackPositionLabel($start, $end),
];
}
/** Where an asset is racked: the rack and its position, or null. Raw values. */
function rackPositionForAsset($asset_id) {
global $mysqli;
$asset_id = intval($asset_id);
$sql = mysqli_query($mysqli, "SELECT rack_id, rack_name, rack_archived_at, unit_start_number, unit_end_number, unit_face
FROM rack_units
JOIN racks ON rack_id = unit_rack_id
WHERE unit_asset_id = $asset_id
LIMIT 1");
return mysqli_fetch_assoc($sql) ?: null;
}