diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f3ba3024..77c8fbef8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,11 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - API: projects can be read - one with its tickets and its progress and time - started for a client or as internal work, with a project template's tickets, changed, completed once none of its tickets is open, reopened, archived, unarchived and deleted once archived. A template's tickets can be added to an open project. A ticket goes on or off a project with tickets/create and tickets/update. - API: a ticket's tasks can be read, added, changed, marked done or not done, and deleted, and an approval can be asked of the client or your team, given by the key's agent, and taken off. A task waiting on an approval, or whose approval was declined, can't be marked done. - API: recurring tickets can be read, made - from a ticket template, with its fill-ins answered and its tasks for those answers - changed, paused and resumed, raised now and deleted. +- API: a network's documented IP addresses can be read, added - one at a time or a run of up to 256 - changed and deleted, with the same checks as the address plan: inside the subnet, not documented twice, and a DHCP reservation with its MAC. +- API: an asset's interfaces can be read - with what each is plugged into - added, changed, made the primary, plugged in or unplugged, and deleted, with the same checks as the interface window. +- API: a license's keys can be read, added, handed to the client's devices and users, and deleted, its seats can be set, and it can be renewed by a term or to a date. Reading licenses by software_key finds a license by any of its keys. +- API: asset and contact notes can be read, added with one of your note types, archived, unarchived and deleted once archived. +- API: racks can be read - one with what is mounted in it - made, changed, archived, unarchived and deleted once archived, and items mounted, moved and taken out, with the same checks as the rack page: an asset in one rack at a time, nothing else on that face, and a rack no shorter than what is in it. Rack photos are still added in ITFlow. ### Bug Fixes @@ -65,6 +70,10 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - API endpoints: `payments/` `read`, `create`, `update`, `delete`, `send` (the receipt); `projects/` `read`, `create`, `update`, `complete`, `reopen`, `archive`, `unarchive`, `delete`, `apply_template`; `tasks/` `read`, `create`, `update`, `complete`, `delete`; `task_approvals/` `create`, `approve`, `delete`; `recurring_tickets/` `read`, `create`, `update`, `status`, `raise`, `delete`. They call `billingMoneyCan()`, `invoiceCanPay()`, `updateInvoiceStatusFromPayments()`, `reconcileCheckChange()`, `reconcileCheckDelete()`, `transferDepositRelease()`, `billingPaymentSend()`, `projectNextNumber()`, `projectApplyTemplate()`, `projectComplete()`, `projectReopen()`, `projectArchive()`, `projectRestore()`, `projectDelete()`, `projectNotifyManager()`, `projectStats()`, `ticketMailTaskApproval()`, `recurringTicketRunNow()`, `recurringTicketNextRun()`, `ticketFillInAnswers()`, `ticketTemplateTaskApplies()` and `recurringTicketMailAssigned()`; the task and recurring ticket handlers work inline, and their endpoints do the same steps. Payment and recurring ticket fields go through `payments/payment_model.php` and `recurring_tickets/recurring_ticket_model.php`, project fields through `projects/project_model.php`. - `enforce_api_rbac.php` maps `payments` to `module_financial` (the endpoints also check Sales at Read through `billingMoneyCan()`), and `projects`, `tasks`, `task_approvals` and `recurring_tickets` to `module_support`, with `complete`, `approve`, `raise` and `apply_template` at level 2. - `tickets/ticket_model.php` takes `ticket_project_id` - the client's project or an internal one (`ticketClientOwnedId()`), 0 to take it off - and turns down any other id rather than dropping it; `tickets/create` and `tickets/update` write it and the ticket's history. +- API endpoints: `network_ips/` `read`, `create`, `update`, `delete`; `asset_interfaces/` `read`, `create`, `update`, `delete`; `software/` `seats`, `renew`; `software_keys/` `read`, `create`, `update`, `delete`; `asset_notes/` and `contact_notes/` `read`, `create`, `archive`, `unarchive`, `delete`; `racks/` `read`, `create`, `update`, `archive`, `unarchive`, `delete`; `rack_units/` `create`, `update`, `delete`. They call `networkIpFieldsSet()`, `checkIpForNetwork()`, `expandIpSuffix()`, `interfaceFormSet()`, `interfaceConnectTarget()`, `interfaceConnect()`, `interfaceMakePrimary()`, `interfaceLinks()`, `softwareSyncSeats()`, `softwareSeatHolders()`, `softwareRenewalExtended()`, `softwareAddKeys()`, `softwareKeys()`, `rackUnitConflict()`, `rackLoadUnits()` and `rackDeletePhoto()`; the note, key, rack and rack item handlers work inline, and their endpoints do the same steps. An update sends `interfaceFormSet()` and `networkIpFieldsSet()` the record's own values for the fields it leaves out. Asset and contact notes are one body, `api/v1/notes_body.php`, included with `$note_kind` and `$note_op`, as the billing lines are. +- `categoryPickedName($kind, $name, $keep = '')` (`functions/categories.php`) checks a name posted for a category kind held by name - a rack type, an interface type, a note type - against what the picker offers, in any case, and gives the category's own spelling, '' for blank, or null when it is none of them; while a kind has no categories set up, any name is taken. +- `enforce_api_rbac.php` maps `network_ips`, `asset_interfaces`, `software_keys`, `asset_notes`, `racks` and `rack_units` to `module_support` and `contact_notes` to `module_client`, with `seats` and `renew` at level 2. Deleting an IP, interface, key or rack item needs Full, as every API delete does, where the page lets Modify do it. +- `software/read.php` read `software_key` from the wrong parameter (`software_license`), so a lookup by key matched licenses with no key; it now matches the license's own key or one in `software_keys`. - `php_flag engine off` in `uploads/.htaccess`, its `backups`, `expenses`, `tmp` and `canned_responses` folders and `scripts/.htaccess` is wrapped in ``. Apache only knows `php_flag` under mod_php - with PHP-FPM through `mod_proxy_fcgi` it stops on the line and answers every request in the folder with a 500. Under FPM, PHP still can't run there: `uploads/.htaccess` denies `.php`, `.phtml`, `.phar` and the rest by name, and the other five deny everything. ## [26.11.8] diff --git a/api/v1/asset_interfaces/create.php b/api/v1/asset_interfaces/create.php new file mode 100644 index 000000000..c181732ca --- /dev/null +++ b/api/v1/asset_interfaces/create.php @@ -0,0 +1,64 @@ + Categories) + * interface_ip optional - An IP address, DHCP, or empty for none + * interface_network_id optional - One of the client's networks + * interface_mac, interface_nat_ip, interface_ipv6, interface_vlans, interface_description, interface_notes optional + * interface_primary optional - 1: the asset's primary interface + * connected_to optional - The interface it is plugged into, on another of the client's assets + * + * Answer: insert_id, and warnings - such as the address being on another device too. + */ + +require_once '../validate_api_key.php'; +require_once '../require_post_method.php'; + +$insert_id = false; + +$asset_id = intval($_POST['asset_id'] ?? 0); +$asset = $asset_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_client_id FROM assets WHERE asset_id = $asset_id " + . clientScopeSql('asset_client_id') . ($client_id ? " AND asset_client_id = $client_id" : '') . " LIMIT 1")) : null; + +if ($asset && apiUserCanAccessClient($asset['asset_client_id'])) { + + $client_id = intval($asset['asset_client_id']); + + require_once 'interface_model.php'; + + mysqli_query($mysqli, "INSERT INTO asset_interfaces SET $interface_set, interface_asset_id = $asset_id"); + $interface_id = intval(mysqli_insert_id($mysqli)); + + if ($interface_id) { + $insert_id = $interface_id; + + // The first one is the primary whether it is asked for or not + $has_primary = mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM asset_interfaces WHERE interface_asset_id = $asset_id AND interface_primary = 1 AND interface_archived_at IS NULL")); + if (!empty($_POST['interface_primary']) || !$has_primary) { + interfaceMakePrimary($interface_id, $asset_id); + } + if ($interface_connect) { + interfaceConnect($interface_id, $interface_connect); + } + + $return_arr['warnings'] = $interface_warnings; + + $label = escapeSql(trim($interface_post['name']) . ' on asset ' . $asset['asset_name']); + logAudit("Asset Interface", "Create", "Created interface $label via API ($api_key_name)", $client_id, $asset_id); + logAudit("API", "Success", "Created interface $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/asset_interfaces/delete.php b/api/v1/asset_interfaces/delete.php new file mode 100644 index 000000000..bc2956ab8 --- /dev/null +++ b/api/v1/asset_interfaces/delete.php @@ -0,0 +1,39 @@ + 0) { + $label = escapeSql($row['interface_name'] . ' from asset ' . $row['asset_name']); + logAudit("Asset Interface", "Delete", "Deleted interface $label via API ($api_key_name)", $client_id, intval($row['asset_id'])); + logAudit("API", "Success", "Deleted interface $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/asset_interfaces/interface_model.php b/api/v1/asset_interfaces/interface_model.php new file mode 100644 index 000000000..a4142b170 --- /dev/null +++ b/api/v1/asset_interfaces/interface_model.php @@ -0,0 +1,64 @@ + 'name', 'interface_description' => 'description', 'interface_type' => 'type', 'interface_mac' => 'mac', 'interface_ip' => 'ip', + 'interface_nat_ip' => 'nat_ip', 'interface_ipv6' => 'ipv6', 'interface_vlans' => 'vlans', 'interface_notes' => 'notes', 'interface_network_id' => 'network_id'] as $field => $key) { + $interface_post[$key] = array_key_exists($field, $_POST) ? (is_scalar($_POST[$field]) ? (string) $_POST[$field] : '') : (string) ($interface_row[$field] ?? ''); +} +// The address: an IP, DHCP, or empty for none +$interface_post['ip_mode'] = strtoupper(trim($interface_post['ip'])) === 'DHCP' ? 'dhcp' : (trim($interface_post['ip']) === '' ? 'none' : 'static'); + +// A type from Admin > Categories, as the picker offers - the one it has stays allowed +if (array_key_exists('interface_type', $_POST)) { + $type = categoryPickedName('network_interface', $interface_post['type'], (string) ($interface_row['interface_type'] ?? '')); + if ($type === null) { + $interface_refuse('interface_type is one of: ' . implode(', ', array_keys(categoryPicker('network_interface'))) . ' - or empty for none.'); + } + $interface_post['type'] = $type; +} + +// The network has to be the asset's client's +if (array_key_exists('interface_network_id', $_POST) && intval($_POST['interface_network_id']) + && !assetClientOwnedId('network', $_POST['interface_network_id'], $asset['asset_client_id'])) { + $interface_refuse("interface_network_id isn't one of the client's networks."); +} + +$error = ''; +$interface_warnings = []; +$interface_set = interfaceFormSet($interface_post, $asset, intval($interface_row['interface_id'] ?? 0), $error, $interface_warnings); +if ($interface_set === '') { + $interface_refuse($error); +} +$interface_warnings = array_map(function ($warning) { + return html_entity_decode(strip_tags($warning), ENT_QUOTES | ENT_HTML5, 'UTF-8'); +}, $interface_warnings); + +// What it is plugged into - one of the client's other assets' interfaces +$interface_connect = null; +if (array_key_exists('connected_to', $_POST)) { + $interface_connect = interfaceConnectTarget($_POST['connected_to'], $asset['asset_client_id'], $asset['asset_id']); + if (intval($_POST['connected_to']) && !$interface_connect) { + $interface_refuse("connected_to is an interface on another of the client's assets - not archived."); + } +} diff --git a/api/v1/asset_interfaces/read.php b/api/v1/asset_interfaces/read.php new file mode 100644 index 000000000..d8fe0be9e --- /dev/null +++ b/api/v1/asset_interfaces/read.php @@ -0,0 +1,54 @@ + 0 + WHERE " . ($interface_id ? "interface_id = $interface_id" : "interface_asset_id = $asset_id") . " " . apiClientScopeSql('asset_client_id') . " + ORDER BY interface_primary DESC, interface_name ASC"); + +$rows = []; +while ($sql && ($row = mysqli_fetch_assoc($sql))) { + $rows[intval($row['interface_id'])] = $row; +} + +if ($rows) { + $links = interfaceLinks(array_keys($rows)); + foreach ($rows as $id => $row) { + $link = $links[$id] ?? null; + $rows[$id]['connected_to'] = $link ? ['interface_id' => intval($link['interface_id']), 'interface_name' => $link['interface_name'], 'asset_id' => intval($link['asset_id']), 'asset_name' => $link['asset_name']] : null; + } + echo json_encode(['success' => 'True', 'count' => count($rows), 'data' => array_values($rows)]); + exit(); +} + +$sql = false; + +// Output +require_once "../read_output.php"; diff --git a/api/v1/asset_interfaces/update.php b/api/v1/asset_interfaces/update.php new file mode 100644 index 000000000..28fc558d2 --- /dev/null +++ b/api/v1/asset_interfaces/update.php @@ -0,0 +1,63 @@ + $asset_id, 'asset_name' => $interface_row['asset_name'], 'asset_type' => $interface_row['asset_type'], 'asset_client_id' => $client_id]; + + require_once 'interface_model.php'; + + if (mysqli_query($mysqli, "UPDATE asset_interfaces SET $interface_set WHERE interface_id = $interface_id")) { + $update_count = 1; + + if (!empty($_POST['interface_primary'])) { + interfaceMakePrimary($interface_id, $asset_id); + } + // Moved, or let go when 0 + if ($interface_connect !== null && $interface_connect !== intval($interface_row['link']['interface_id'] ?? 0)) { + if (!empty($interface_row['link'])) { + interfaceConnect($interface_id, 0); + } + if ($interface_connect) { + interfaceConnect($interface_id, $interface_connect); + } + } + + $return_arr['warnings'] = $interface_warnings; + + $label = escapeSql(trim($interface_post['name']) . ' on asset ' . $interface_row['asset_name']); + logAudit("Asset Interface", "Edit", "Edited interface $label via API ($api_key_name)", $client_id, $asset_id); + logAudit("API", "Success", "Edited interface $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/asset_notes/archive.php b/api/v1/asset_notes/archive.php new file mode 100644 index 000000000..c52a81ff0 --- /dev/null +++ b/api/v1/asset_notes/archive.php @@ -0,0 +1,14 @@ + 'module_support', 'domains' => 'module_support', 'networks' => 'module_support', + 'network_ips' => 'module_support', + 'asset_interfaces' => 'module_support', + 'asset_notes' => 'module_support', + 'racks' => 'module_support', + 'rack_units' => 'module_support', 'services' => 'module_support', 'software' => 'module_support', + 'software_keys' => 'module_support', 'tickets' => 'module_support', 'ticket_replies' => 'module_support', 'technicians' => 'module_support', @@ -156,6 +162,7 @@ $resource_module = [ 'recurring_tickets' => 'module_support', 'clients' => 'module_client', 'contacts' => 'module_client', + 'contact_notes' => 'module_client', 'locations' => 'module_client', 'portal_invites' => 'module_client', 'vendors' => 'module_client', @@ -205,6 +212,8 @@ $operation_level = [ 'approve.php' => 2, 'raise.php' => 2, 'apply_template.php' => 2, + 'seats.php' => 2, + 'renew.php' => 2, ]; if (!isset($resource_module[$resource])) { diff --git a/api/v1/network_ips/create.php b/api/v1/network_ips/create.php new file mode 100644 index 000000000..86dd089d7 --- /dev/null +++ b/api/v1/network_ips/create.php @@ -0,0 +1,94 @@ + $last_int) { + $ip_refuse('A range is two IPv4 addresses, the lower first.'); + } + if ($last_int - $first_int >= 256) { + $ip_refuse('A range is up to 256 addresses at a time.'); + } + for ($int = $first_int; $int <= $last_int; $int++) { + $ip = intToIpv4($int); + if (checkIpForNetwork($ip, $network_id) !== '') { + $skipped++; + continue; + } + mysqli_query($mysqli, "INSERT INTO network_ips SET ip_address = '" . escapeSql($ip) . "', $fields, ip_network_id = $network_id"); + $added[] = intval(mysqli_insert_id($mysqli)); + } + if (!$added) { + $ip_refuse("None of $first to $last could be documented - they are outside the subnet or documented already."); + } + $what = "$first - $last"; + } else { + $ip_error = checkIpForNetwork($ip_address, $network_id); + if ($ip_error) { + $ip_refuse($ip_error); + } + mysqli_query($mysqli, "INSERT INTO network_ips SET ip_address = '" . escapeSql($ip_address) . "', $fields, ip_network_id = $network_id"); + $added[] = intval(mysqli_insert_id($mysqli)); + $what = $ip_address; + } + + $insert_id = $added[0] ?: false; + $return_arr['added'] = count($added); + $return_arr['skipped'] = $skipped; + + $label = escapeSql("$what on network " . $network['network_name']); + logAudit("IP Address", "Create", "Documented " . count($added) . " address(es), $label via API ($api_key_name)", $client_id, $network_id); + logAudit("API", "Success", "Documented $label via API ($api_key_name)", $client_id); +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/network_ips/delete.php b/api/v1/network_ips/delete.php new file mode 100644 index 000000000..957afe800 --- /dev/null +++ b/api/v1/network_ips/delete.php @@ -0,0 +1,33 @@ + 0) { + $label = escapeSql($ip_row['ip_address'] . ' from network ' . $ip_row['network_name']); + logAudit("IP Address", "Delete", "Deleted IP $label via API ($api_key_name)", $client_id); + logAudit("API", "Success", "Deleted IP $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/network_ips/network_ip_find.php b/api/v1/network_ips/network_ip_find.php new file mode 100644 index 000000000..37a44a0ee --- /dev/null +++ b/api/v1/network_ips/network_ip_find.php @@ -0,0 +1,45 @@ + 'type', 'ip_hostname' => 'hostname', 'ip_mac' => 'mac', 'ip_description' => 'description'] as $field => $key) { + $post[$key] = array_key_exists($field, $_POST) ? (is_scalar($_POST[$field]) ? (string) $_POST[$field] : '') : (string) ($row[$field] ?? ''); + } + // A reservation documented without its MAC (an import) can still be changed, until a MAC is sent + $post['allow_no_mac'] = $row && $row['ip_type'] === 'Reservation' && (string) $row['ip_mac'] === '' && !array_key_exists('ip_mac', $_POST); + return $post; +}; + +$ip_refuse = function ($message) use (&$return_arr) { + http_response_code(400); + $return_arr['success'] = "False"; + $message = rtrim(html_entity_decode(strip_tags($message), ENT_QUOTES | ENT_HTML5, 'UTF-8')); + $return_arr['message'] = preg_match('/[.!?]$/', $message) ? $message : "$message."; + echo json_encode($return_arr); + exit(); +}; + +if (array_key_exists('ip_type', $_POST) && !isset(NETWORK_IP_TYPES[$_POST['ip_type']])) { + $ip_refuse('ip_type is one of: ' . implode(', ', array_keys(NETWORK_IP_TYPES)) . '.'); +} diff --git a/api/v1/network_ips/read.php b/api/v1/network_ips/read.php new file mode 100644 index 000000000..34f8bb6a3 --- /dev/null +++ b/api/v1/network_ips/read.php @@ -0,0 +1,35 @@ + Categories) and what was noted, by the agent who wrote it. Archived ones + * stay until deleted, and only an archived one can be deleted. + */ + +if (!function_exists('apiDeny') || !isset($note_kind, $note_op)) { + http_response_code(404); + exit(); +} + +$k = [ + 'asset' => ['table' => 'asset_notes', 'p' => 'asset_note_', 'owner' => 'asset_note_asset_id', 'parent' => 'assets', 'id' => 'asset_id', + 'name' => 'asset_name', 'client' => 'asset_client_id', 'category' => 'asset_note_type', 'audit' => 'Asset'], + 'contact' => ['table' => 'contact_notes', 'p' => 'contact_note_', 'owner' => 'contact_note_contact_id', 'parent' => 'contacts', 'id' => 'contact_id', + 'name' => 'contact_name', 'client' => 'contact_client_id', 'category' => 'contact_note_type', 'audit' => 'Contact'], +][$note_kind]; +$p = $k['p']; + +$note_refuse = function ($message) use (&$return_arr) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $message; + echo json_encode($return_arr); + exit(); +}; + +if ($note_op === 'read') { + $parent_id = intval($_GET[$k['id']] ?? 0); + $note_id = intval($_GET[$p . 'id'] ?? 0); + if (!$parent_id && !$note_id) { + $note_refuse("{$k['table']}/read.php needs {$k['id']} or {$p}id."); + } + $sql = mysqli_query($mysqli, "SELECT {$k['table']}.*, user_name AS {$p}created_by_name, {$k['client']} + FROM {$k['table']} + JOIN {$k['parent']} ON {$k['id']} = {$k['owner']} + LEFT JOIN users ON user_id = {$p}created_by + WHERE " . ($note_id ? "{$p}id = $note_id" : "{$k['owner']} = $parent_id") . " " . apiClientScopeSql($k['client']) . " + ORDER BY {$p}created_at DESC, {$p}id DESC LIMIT $limit OFFSET $offset"); + require_once __DIR__ . '/read_output.php'; +} + +if ($note_op === 'create') { + $insert_id = false; + $parent_id = intval($_POST[$k['id']] ?? 0); + $parent = $parent_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT {$k['id']}, {$k['name']}, {$k['client']} FROM {$k['parent']} WHERE {$k['id']} = $parent_id " + . clientScopeSql($k['client']) . ($client_id ? " AND {$k['client']} = $client_id" : '') . " LIMIT 1")) : null; + if ($parent && apiUserCanAccessClient($parent[$k['client']])) { + $client_id = intval($parent[$k['client']]); + $note_field = $note_kind . '_note'; + $note = trim((string) (is_scalar($_POST[$note_field] ?? '') ? ($_POST[$note_field] ?? '') : '')); + $type = categoryPickedName($k['category'], $_POST[$p . 'type'] ?? ''); + if ($note === '') { + $note_refuse("A note needs something in it - {$note_kind}_note."); + } + if ($type === null || $type === '') { + $note_refuse("{$p}type is one of: " . implode(', ', array_keys(categoryPicker($k['category']))) . '.'); + } + $type_sql = escapeSql($type); + mysqli_query($mysqli, "INSERT INTO {$k['table']} SET {$p}type = '$type_sql', {$note_kind}_note = '" . escapeSql($note) . "', {$p}created_by = " . intval($session_user_id) . ", {$k['owner']} = $parent_id"); + $insert_id = intval(mysqli_insert_id($mysqli)) ?: false; + if ($insert_id) { + $label = "a $type_sql note for $note_kind " . escapeSql($parent[$k['name']]); + logAudit($k['audit'], "Edit", "Created $label via API ($api_key_name)", $client_id, $parent_id); + logAudit("API", "Success", "Created $label via API ($api_key_name)", $client_id); + } + } + require_once __DIR__ . '/create_output.php'; +} + +// The rest act on one note, of a client the key's user can reach +$note_id = intval($_POST[$p . 'id'] ?? 0); +$row = $note_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT {$p}id, {$p}type, {$p}archived_at, {$k['id']}, {$k['name']}, {$k['client']} + FROM {$k['table']} JOIN {$k['parent']} ON {$k['id']} = {$k['owner']} + WHERE {$p}id = $note_id " . clientScopeSql($k['client']) . ($client_id ? " AND {$k['client']} = $client_id" : '') . " LIMIT 1")) : null; +if ($row && !apiUserCanAccessClient($row[$k['client']])) { + $row = null; +} +$client_id = intval($row[$k['client']] ?? 0); +$label = $row ? escapeSql($row[$p . 'type'] . " note for $note_kind " . $row[$k['name']]) : ''; + +if ($note_op === 'archive' || $note_op === 'unarchive') { + $update_count = false; + $archive = $note_op === 'archive'; + if ($row && empty($row[$p . 'archived_at']) === $archive) { + mysqli_query($mysqli, "UPDATE {$k['table']} SET {$p}archived_at = " . ($archive ? 'NOW()' : 'NULL') . " WHERE {$p}id = $note_id"); + $update_count = 1; + logAudit($k['audit'], "Edit", ($archive ? 'Archived' : 'Restored') . " the $label via API ($api_key_name)", $client_id, intval($row[$k['id']])); + logAudit("API", "Success", ($archive ? 'Archived' : 'Restored') . " the $label via API ($api_key_name)", $client_id); + } + require_once __DIR__ . '/update_output.php'; +} + +if ($note_op === 'delete') { + $delete_count = false; + // Archived first, as for the other records the API deletes + if ($row && !empty($row[$p . 'archived_at'])) { + mysqli_query($mysqli, "DELETE FROM {$k['table']} WHERE {$p}id = $note_id"); + $delete_count = mysqli_affected_rows($mysqli); + if ($delete_count > 0) { + logAudit($k['audit'], "Edit", "Deleted the $label via API ($api_key_name)", $client_id, intval($row[$k['id']])); + logAudit("API", "Success", "Deleted the $label via API ($api_key_name)", $client_id); + } + } + require_once __DIR__ . '/delete_output.php'; +} diff --git a/api/v1/rack_units/create.php b/api/v1/rack_units/create.php new file mode 100644 index 000000000..a3c9d1e8b --- /dev/null +++ b/api/v1/rack_units/create.php @@ -0,0 +1,46 @@ + 0) { + $what = escapeSql(rackUnitName($unit['asset_name'], $unit['unit_device'], $unit['unit_type']) . ' from rack ' . $rack['rack_name']); + logAudit("Rack", "Edit", "Removed $what via API ($api_key_name)", $client_id, $rack_id); + logAudit("API", "Success", "Removed $what via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/rack_units/unit_find.php b/api/v1/rack_units/unit_find.php new file mode 100644 index 000000000..401595d0b --- /dev/null +++ b/api/v1/rack_units/unit_find.php @@ -0,0 +1,18 @@ + $rack_units) { + $rack_refuse("That doesn't fit - this rack runs from U1 to U$rack_units."); +} + +// The asset has to be the client's, and in one place at a time +$asset_name = ''; +if ($asset_id) { + $asset_row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT asset_name FROM assets WHERE asset_id = $asset_id AND asset_client_id = " . intval($client_id))); + if (!$asset_row) { + $rack_refuse("asset_id isn't one of the client's assets."); + } + $asset_name = $asset_row['asset_name']; + $racked = mysqli_fetch_assoc(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 ($racked) { + $rack_refuse("$asset_name is already racked in {$racked['rack_name']} at " . html_entity_decode(rackPositionLabel($racked['unit_start_number'], $racked['unit_end_number'])) . '.'); + } +} elseif ($label === '') { + $rack_refuse('Send asset_id, or a name for the item in unit_device.'); +} + +$conflict = rackUnitConflict($rack['rack_id'], $start, $end, $face, $full_depth, $unit_id); +if ($conflict) { + $rack_refuse(html_entity_decode(rackPositionLabel($start, $end)) . " on the $face is taken by {$conflict['name']} (" . html_entity_decode(rackPositionLabel($conflict['start'], $conflict['end'])) . ")."); +} + +// A linked asset is drawn by its own asset type, so only unlinked items keep one +$unit_set = "unit_device = '" . escapeSql(mb_substr($label, 0, 200)) . "', unit_asset_id = " . ($asset_id ?: 'NULL') . ", unit_type = " . ($asset_id ? 'NULL' : "'" . escapeSql($unit_type) . "'") . ", + unit_start_number = $start, unit_end_number = $end, unit_face = '$face', unit_full_depth = $full_depth, + unit_power_watts = " . ($power_watts > 0 ? $power_watts : 'NULL') . ", unit_notes = '" . escapeSql($notes) . "'"; +$unit_label = rackUnitName($asset_name, $label, $unit_type) . ' at ' . html_entity_decode(rackPositionLabel($start, $end)) . " ($face)"; diff --git a/api/v1/rack_units/update.php b/api/v1/rack_units/update.php new file mode 100644 index 000000000..02aef9093 --- /dev/null +++ b/api/v1/rack_units/update.php @@ -0,0 +1,36 @@ + Categories) + * rack_units required - How tall, 1 to 70 units + * rack_units_descending optional - 1: U1 is at the top + * rack_model, rack_depth, rack_power_capacity (watts), rack_location_id (the client's), + * rack_physical_location, rack_description, rack_notes optional + */ + +require_once '../validate_api_key.php'; +require_once '../require_post_method.php'; + +$insert_id = false; + +$rack_lookup_id = 0; +require_once 'rack_find.php'; + +if (!$client_id || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL"))) { + $rack_refuse('client_id is required - the client the rack is for.'); +} + +require_once 'rack_model.php'; + +foreach (['rack_name' => 'A rack needs a name - rack_name.', 'rack_type' => 'rack_type is one of: ' . implode(', ', array_keys(categoryPicker('rack_type'))) . '.', 'rack_units' => 'rack_units is how tall it is - 1 to 70 units.'] as $field => $message) { + if (!isset($rack_set[$field])) { + $rack_refuse($message); + } +} +$rack_set['rack_client_id'] = $client_id; + +mysqli_query($mysqli, "INSERT INTO racks SET " . implode(', ', array_map(function ($column, $value) { + return "$column = $value"; +}, array_keys($rack_set), $rack_set))); +$rack_id = intval(mysqli_insert_id($mysqli)); + +if ($rack_id) { + $insert_id = $rack_id; + $name = escapeSql((string) getFieldById('racks', $rack_id, 'rack_name')); + logAudit("Rack", "Create", "Created rack $name via API ($api_key_name)", $client_id, $rack_id); + logAudit("API", "Success", "Created rack $name via API ($api_key_name)", $client_id); +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/racks/delete.php b/api/v1/racks/delete.php new file mode 100644 index 000000000..7d27ff10e --- /dev/null +++ b/api/v1/racks/delete.php @@ -0,0 +1,37 @@ + 0) { + rackDeletePhoto($client_id, $rack['rack_photo']); + rackDeletePhoto($client_id, $rack['rack_photo_rear']); + + $name = escapeSql($rack['rack_name']); + logAudit("Rack", "Delete", "Deleted rack $name via API ($api_key_name)", $client_id); + logAudit("API", "Success", "Deleted rack $name via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/racks/rack_find.php b/api/v1/racks/rack_find.php new file mode 100644 index 000000000..3ddcf2223 --- /dev/null +++ b/api/v1/racks/rack_find.php @@ -0,0 +1,27 @@ + SQL value). On an update $rack is the rack. +// $client_id is its client. + +if (!function_exists('apiDeny')) { + http_response_code(404); + exit(); +} + +$rack = $rack ?? null; +$rack_set = []; +$text = function ($field) { + return trim((string) (is_scalar($_POST[$field] ?? '') ? ($_POST[$field] ?? '') : '')); +}; + +if (array_key_exists('rack_name', $_POST)) { + if ($text('rack_name') === '') { + $rack_refuse('A rack needs a name - rack_name.'); + } + $rack_set['rack_name'] = "'" . escapeSql(mb_substr($text('rack_name'), 0, 200)) . "'"; +} +if (array_key_exists('rack_type', $_POST)) { + $type = categoryPickedName('rack_type', $text('rack_type'), (string) ($rack['rack_type'] ?? '')); + if ($type === null || $type === '') { + $rack_refuse('rack_type is one of: ' . implode(', ', array_keys(categoryPicker('rack_type'))) . '.'); + } + $rack_set['rack_type'] = "'" . escapeSql(mb_substr($type, 0, 50)) . "'"; +} +if (array_key_exists('rack_units', $_POST)) { + $units = intval($_POST['rack_units']); + if ($units < 1 || $units > 70) { + $rack_refuse('rack_units is how tall it is - 1 to 70 units.'); + } + $rack_set['rack_units'] = $units; +} +if (array_key_exists('rack_units_descending', $_POST)) { + $rack_set['rack_units_descending'] = intval($_POST['rack_units_descending']) === 1 ? 1 : 0; +} +if (array_key_exists('rack_power_capacity', $_POST)) { + $watts = intval($_POST['rack_power_capacity']); + $rack_set['rack_power_capacity'] = $watts > 0 ? $watts : 'NULL'; +} +if (array_key_exists('rack_location_id', $_POST)) { + $location = intval($_POST['rack_location_id']); + if ($location && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM locations WHERE location_id = $location AND location_client_id = " . intval($client_id)))) { + $rack_refuse("rack_location_id isn't one of the client's locations."); + } + $rack_set['rack_location_id'] = $location; +} +foreach (['rack_model' => 200, 'rack_depth' => 50, 'rack_physical_location' => 200, 'rack_description' => 0, 'rack_notes' => 0] as $field => $length) { + if (array_key_exists($field, $_POST)) { + $rack_set[$field] = "'" . escapeSql($length ? mb_substr($text($field), 0, $length) : $text($field)) . "'"; + } +} diff --git a/api/v1/racks/read.php b/api/v1/racks/read.php new file mode 100644 index 000000000..43ae893ff --- /dev/null +++ b/api/v1/racks/read.php @@ -0,0 +1,46 @@ + intval($unit['unit_id']), + 'unit_start_number' => intval($unit['unit_start_number']), + 'unit_end_number' => intval($unit['unit_end_number']), + 'unit_face' => $unit['unit_face'], + 'unit_full_depth' => intval($unit['unit_full_depth']), + 'unit_device' => $unit['unit_device'], + 'unit_type' => $unit['unit_type'], + 'unit_power_watts' => $unit['unit_power_watts'] !== null ? intval($unit['unit_power_watts']) : null, + 'unit_notes' => $unit['unit_notes'], + 'asset_id' => $unit['asset_id'] !== null ? intval($unit['asset_id']) : null, + 'asset_name' => $unit['asset_name'], + 'asset_type' => $unit['asset_type'], + ]; + }, array_reverse(rackLoadUnits([$id])[$id])); + echo json_encode(['success' => 'True', 'count' => 1, 'data' => [$row]]); + exit(); + } +} else { + $sql = mysqli_query($mysqli, "SELECT * FROM racks WHERE 1=1 " . apiClientScopeSql('rack_client_id') . " ORDER BY rack_id LIMIT $limit OFFSET $offset"); +} + +// Output +require_once "../read_output.php"; diff --git a/api/v1/racks/unarchive.php b/api/v1/racks/unarchive.php new file mode 100644 index 000000000..1ca8f3734 --- /dev/null +++ b/api/v1/racks/unarchive.php @@ -0,0 +1,30 @@ + $units ORDER BY unit_end_number DESC LIMIT 1")); + if ($row) { + $rack_refuse("Can't shrink the rack to {$units}U - " . rackUnitName($row['asset_name'], $row['unit_device'], $row['unit_type']) . " is mounted up to U" . intval($row['unit_end_number']) . ". Move or remove it first."); + } + } + + if (mysqli_query($mysqli, "UPDATE racks SET " . implode(', ', array_map(function ($column, $value) { + return "$column = $value"; + }, array_keys($rack_set), $rack_set)) . " WHERE rack_id = $rack_id")) { + $update_count = 1; + $name = escapeSql((string) getFieldById('racks', $rack_id, 'rack_name')); + logAudit("Rack", "Edit", "Edited rack $name via API ($api_key_name)", $client_id, $rack_id); + logAudit("API", "Success", "Edited rack $name via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/software/read.php b/api/v1/software/read.php index a5dda019b..cb9c37863 100644 --- a/api/v1/software/read.php +++ b/api/v1/software/read.php @@ -11,9 +11,9 @@ if (isset($_GET['software_id'])) { $sql = mysqli_query($mysqli, "SELECT * FROM software WHERE software_id = '$id' AND software_archived_at IS NULL AND 1=1 " . apiClientScopeSql('software_client_id') . ""); } elseif (isset($_GET['software_key'])) { - // Specific software via key - $key = mysqli_real_escape_string($mysqli, $_GET['software_license']); - $sql = mysqli_query($mysqli, "SELECT * FROM software WHERE software_key = '$key' AND software_archived_at IS NULL AND 1=1 " . apiClientScopeSql('software_client_id') . " ORDER BY software_id LIMIT $limit OFFSET $offset"); + // Specific software via key - its own, or one of its keys + $key = mysqli_real_escape_string($mysqli, (string) $_GET['software_key']); + $sql = mysqli_query($mysqli, "SELECT * FROM software WHERE (software_key = '$key' OR software_id IN (SELECT software_key_software_id FROM software_keys WHERE software_key = '$key')) AND software_archived_at IS NULL AND 1=1 " . apiClientScopeSql('software_client_id') . " ORDER BY software_id LIMIT $limit OFFSET $offset"); } elseif (isset($_GET['software_name'])) { // Software by name diff --git a/api/v1/software/renew.php b/api/v1/software/renew.php new file mode 100644 index 000000000..e4f61b7a1 --- /dev/null +++ b/api/v1/software/renew.php @@ -0,0 +1,58 @@ + ['asset_ids', 'assets'], 'contact' => ['contact_ids', 'contacts']] as $kind => [$field, $list]) { + if (array_key_exists($field, $_POST)) { + $ids = array_values(array_unique(array_filter(array_map('intval', (array) $_POST[$field])))); + $owned = softwareClientIds($kind, $ids, $client_id); + if (count($owned) !== count($ids)) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = "$field are the client's own {$kind}s, not archived - these aren't: " . implode(', ', array_diff($ids, $owned)) . '.'; + echo json_encode($return_arr); + exit(); + } + $wanted[$kind] = $owned; + } else { + $wanted[$kind] = array_map(function ($row) use ($kind) { + return intval($row[$kind . '_id']); + }, $holders[$list]); + } + } + + $changes = softwareSyncSeats($software_id, $client_id, $wanted['asset'], $wanted['contact']); + + $update_count = 1; + $return_arr['added'] = array_values($changes['added']); + $return_arr['removed'] = array_values($changes['removed']); + $return_arr['warning'] = $software_seat_warning($software_id); + + if ($changes['added'] || $changes['removed']) { + $label = escapeSql($software['software_name'] . softwareSeatChangeText($changes)); + logAudit("Software", "Seats", "Changed seats on license $label via API ($api_key_name)", $client_id, $software_id); + logAudit("API", "Success", "Changed seats on license " . escapeSql($software['software_name']) . " via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/software/software_find.php b/api/v1/software/software_find.php new file mode 100644 index 000000000..22ad4bb41 --- /dev/null +++ b/api/v1/software/software_find.php @@ -0,0 +1,24 @@ + 0) { + $label = escapeSql($software['software_name']); + logAudit("Software", "Keys", "Deleted a key from license $label via API ($api_key_name)", $client_id, intval($software['software_id'])); + logAudit("API", "Success", "Deleted a key from license $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/software_keys/key_find.php b/api/v1/software_keys/key_find.php new file mode 100644 index 000000000..71389ba68 --- /dev/null +++ b/api/v1/software_keys/key_find.php @@ -0,0 +1,17 @@ + $key['id'], + 'software_key' => $key['key'], + 'software_id' => $software_id, + 'assets' => array_map(function ($row) { + return ['asset_id' => intval($row['asset_id']), 'asset_name' => $row['asset_name']]; + }, $key['assets']), + 'contacts' => array_map(function ($row) { + return ['contact_id' => intval($row['contact_id']), 'contact_name' => $row['contact_name']]; + }, $key['contacts']), + ]; + } + if ($keys) { + echo json_encode(['success' => 'True', 'count' => count($keys), 'data' => $keys]); + exit(); + } + $sql = false; +} + +if (!$software_id) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = "software_keys/read.php needs software_id or software_key_id."; + echo json_encode($return_arr); + exit(); +} + +// Output +require_once "../read_output.php"; diff --git a/api/v1/software_keys/update.php b/api/v1/software_keys/update.php new file mode 100644 index 000000000..cc7fd1ccc --- /dev/null +++ b/api/v1/software_keys/update.php @@ -0,0 +1,88 @@ + 'asset_ids', 'contact' => 'contact_ids'] as $kind => $field) { + if ($refuse === '' && array_key_exists($field, $_POST)) { + $ids = array_values(array_unique(array_filter(array_map('intval', (array) $_POST[$field])))); + $holders[$kind] = softwareClientIds($kind, $ids, $client_id); + if (count($holders[$kind]) !== count($ids)) { + $refuse = "$field are the client's own {$kind}s, not archived - these aren't: " . implode(', ', array_diff($ids, $holders[$kind])) . '.'; + } + } + } + if ($refuse === '' && !array_key_exists('software_key', $_POST) && !$holders) { + $refuse = 'Send at least one of software_key, asset_ids or contact_ids.'; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + if (isset($key)) { + mysqli_query($mysqli, "UPDATE software_keys SET software_key = '" . escapeSql($key) . "' WHERE software_key_id = $software_key_id"); + } + + // Who it is handed to - each gets a seat if they had none + if (isset($holders['asset'])) { + mysqli_query($mysqli, "DELETE FROM software_key_asset_assignments WHERE software_key_id = $software_key_id"); + foreach ($holders['asset'] as $asset_id) { + mysqli_query($mysqli, "INSERT IGNORE INTO software_key_asset_assignments SET software_key_id = $software_key_id, asset_id = $asset_id"); + mysqli_query($mysqli, "INSERT IGNORE INTO software_assets SET software_id = $software_id, asset_id = $asset_id"); + } + } + if (isset($holders['contact'])) { + mysqli_query($mysqli, "DELETE FROM software_key_contact_assignments WHERE software_key_id = $software_key_id"); + foreach ($holders['contact'] as $contact_id) { + mysqli_query($mysqli, "INSERT IGNORE INTO software_key_contact_assignments SET software_key_id = $software_key_id, contact_id = $contact_id"); + mysqli_query($mysqli, "INSERT IGNORE INTO software_contacts SET software_id = $software_id, contact_id = $contact_id"); + } + } + + $update_count = 1; + $return_arr['warning'] = $software_seat_warning($software_id); + + $label = escapeSql($software['software_name']); + logAudit("Software", "Keys", "Updated a key on license $label via API ($api_key_name)", $client_id, $software_id); + logAudit("API", "Success", "Updated a key on license $label via API ($api_key_name)", $client_id); +} + +// Output +require_once '../update_output.php'; diff --git a/functions/categories.php b/functions/categories.php index bae7b3f08..7dc29a101 100644 --- a/functions/categories.php +++ b/functions/categories.php @@ -691,6 +691,29 @@ function categoryPicker($kind, $keep = [], array $opts = []) { return $rows; } +/* + * A name posted for a kind held by name (a rack type, an asset note type) as + * the picker would post it: one of the kind's current categories, in any case, + * or $keep (what the record has now). '' for blank, null when it is none of + * them - while the kind has none set up, any name is taken as it is. + */ +function categoryPickedName($kind, $name, $keep = '') { + $name = trim((string) $name); + if ($name === '') { + return ''; + } + $rows = categoryPicker($kind, (string) $keep !== '' ? [$keep] : []); + if (!$rows) { + return mb_substr($name, 0, 200); + } + foreach (array_keys($rows) as $value) { + if (categoryNameKey($value) === categoryNameKey($name)) { + return (string) $value; + } + } + return null; +} + /* One picker