Files
site_for_glpi/get_glpi_data.php
T

88 lines
3.4 KiB
PHP

<?php
// Отключаем вывод ошибок в браузер – чтобы JSON был чистым
ini_set('display_errors', 0);
error_reporting(0);
// Логируем ошибки в файл (можно будет посмотреть при необходимости)
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php-errors.log');
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/glpi_api.php';
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
http_response_code(403);
exit('Доступ запрещён');
}
$user = checkAuth($pdo);
if (!$user) {
http_response_code(401);
exit('Unauthorized');
}
$type = $_GET['type'] ?? '';
if (!in_array($type, ['locations', 'computers', 'itilcategories'])) {
http_response_code(400);
exit('Неверный тип данных');
}
$glpi = new GlpiApi(GLPI_API_URL, GLPI_APP_TOKEN, GLPI_USERNAME, GLPI_PASSWORD);
try {
$items = [];
switch ($type) {
case 'locations':
$items = $glpi->getItems('Location', ['is_deleted' => 0, 'range' => '0-1000']);
break;
case 'computers':
$items = $glpi->getItems('Computer', ['is_deleted' => 0, 'range' => '0-1000']);
// Если GLPI вернул пустой массив, пробуем запросить мониторы или периферию
if (empty($items)) {
$items = $glpi->getItems('Monitor', ['is_deleted' => 0, 'range' => '0-100']);
}
if (empty($items)) {
$items = $glpi->getItems('Peripheral', ['is_deleted' => 0, 'range' => '0-100']);
}
break;
case 'itilcategories':
$items = $glpi->getItems('ITILCategory', ['is_deleted' => 0, 'range' => '0-1000']);
break;
}
$result = [];
if (is_array($items)) {
foreach ($items as $item) {
$id = $item['id'] ?? null;
$name = $item['name'] ?? $item['completename'] ?? null;
if ($id && $name) {
// Для компьютеров добавляем инвентарный номер (otherserial или serial)
if ($type === 'computers') {
$inventory = $item['otherserial'] ?? $item['serial'] ?? '';
if (!empty($inventory)) {
$name .= ' (Инв.№: ' . htmlspecialchars($inventory) . ')';
}
}
$result[] = ['id' => $id, 'name' => $name];
}
}
}
// Fallback для компьютеров – если данных нет, отдаём статический список
if ($type === 'computers' && empty($result)) {
$result = [
['id' => 'pc', 'name' => 'Персональный компьютер'],
['id' => 'laptop', 'name' => 'Ноутбук'],
['id' => 'printer', 'name' => 'Принтер / МФУ'],
['id' => 'network', 'name' => 'Сетевое оборудование'],
['id' => 'other', 'name' => 'Другое'],
];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
} catch (Exception $e) {
error_log("GLPI data fetch error ($type): " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
exit;