/
delphin
/
CatRW
Обзор
Документация
Войти
/
delphin
/
CatRW
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
index.php
310 строк
9 KB
delphin
перед глобальным изменением
04 мар 2026, 09:56
Верифицирован
04 мар 2026, 09:56
c6cfdf3
Код
Авторство
О чём код?
<?php // index.php - главный роутер с отладкой error_log("=== INDEX.PHP START ==="); error_log("REQUEST_URI: " . $_SERVER['REQUEST_URI']); error_log("SCRIPT_NAME: " . $_SERVER['SCRIPT_NAME']); require_once 'config.php'; // Глобальная фиксация типоразмера function getActiveScale() { // СНАЧАЛА кука (самая свежая, только что установленная JS) if (isset($_COOKIE['active_scale'])) { // Синхронизируем с сессией $_SESSION['active_scale'] = $_COOKIE['active_scale']; return $_COOKIE['active_scale']; } // ПОТОМ сессия if (isset($_SESSION['active_scale'])) { return $_SESSION['active_scale']; } return null; } function setActiveScale($scale) { $_SESSION['active_scale'] = $scale; if ($scale) { setcookie('active_scale', $scale, time() + 60*60*24*30, '/'); } else { setcookie('active_scale', '', time() - 3600, '/'); } } function applyScaleFilter($sql) { $scale = getActiveScale(); if (!$scale) return $sql; // Фильтруем только запросы к catalog_models if (stripos($sql, 'catalog_models') !== false) { // Проверяем, есть ли уже WHERE if (stripos($sql, 'WHERE') === false) { // Нет WHERE - добавляем перед GROUP BY/ORDER BY/LIMIT $patterns = [ '/GROUP\s+BY/i', '/ORDER\s+BY/i', '/LIMIT/i', '/HAVING/i', '/$/' // конец строки ]; foreach ($patterns as $pattern) { if (preg_match($pattern, $sql, $matches, PREG_OFFSET_CAPTURE)) { $pos = $matches[0][1]; $sql = substr($sql, 0, $pos) . " WHERE scale_code = '$scale' " . substr($sql, $pos); break; } } } else { // Есть WHERE - добавляем после него с AND $sql = preg_replace('/WHERE\s+/i', "WHERE scale_code = '$scale' AND ", $sql, 1); } error_log("🔍 Applied scale filter ($scale): " . $sql); } return $sql; } session_start(); // Получаем путь из URL $request_uri = $_SERVER['REQUEST_URI']; $script_name = $_SERVER['SCRIPT_NAME']; // Убираем параметры запроса $uri = parse_url($request_uri, PHP_URL_PATH); error_log("Parsed URI: " . $uri); // Если запускаем из корня, базовый путь пустой $base_path = dirname($script_name); if ($base_path === '/') { $base_path = ''; } error_log("Base path: " . $base_path); // Получаем маршрут без базового пути $route = substr($uri, strlen($base_path)); error_log("Route: " . $route); // Убираем начальный и конечный слеши $route = trim($route, '/'); error_log("Trimmed route: " . $route); // Разбиваем путь на части $parts = explode('/', $route); $main = $parts[0] ?? ''; error_log("Main part: " . $main); error_log("All parts: " . print_r($parts, true)); // ========== API РОУТИНГ ========== if ($main === 'api') { error_log("=== API REQUEST DETECTED ==="); header('Content-Type: application/json; charset=utf-8'); if (end($parts) === 'logo') { // Это запрос к логотипу array_pop($parts); // Убираем 'logo' if (count($parts) >= 2 && is_numeric($parts[1])) { $id = (int)$parts[1]; $_GET['id'] = $id; if ($method === 'DELETE') { $_GET['action'] = 'delete_logo'; } elseif ($method === 'POST') { $_GET['action'] = 'upload_logo'; } } } // Убираем 'api' из частей array_shift($parts); // endpoint - первый элемент после api $endpoint = $parts[0] ?? ''; error_log("API endpoint: " . $endpoint); if (empty($endpoint)) { error_log("ERROR: No endpoint specified"); http_response_code(400); echo json_encode(['error' => 'API endpoint required']); exit; } // Файл endpoint'а $api_file = "api/{$endpoint}.php"; error_log("API file: " . $api_file); if (!file_exists($api_file)) { error_log("ERROR: API file not found"); http_response_code(404); echo json_encode(['error' => 'API endpoint not found: ' . $endpoint]); exit; } // Определяем метод $method = $_SERVER['REQUEST_METHOD']; error_log("HTTP Method: " . $method); // Парсим RESTful параметры $id = null; $subaction = null; // /api/manufacturers/123 → endpoint=manufacturers, parts[1]=123 if (isset($parts[1]) && is_numeric($parts[1])) { $id = (int)$parts[1]; error_log("ID from URL: " . $id); $_GET['id'] = $id; } // /api/manufacturers/search/query → endpoint=manufacturers, parts[1]=search, parts[2]=query if (isset($parts[1]) && !is_numeric($parts[1])) { $subaction = $parts[1]; error_log("Subaction: " . $subaction); $_GET['action'] = $subaction; if (isset($parts[2])) { $_GET['param'] = $parts[2]; error_log("Param: " . $parts[2]); } } if ($endpoint === 'stats') { error_log("📊 Stats endpoint detected"); $api_file = "api/stats.php"; if (file_exists($api_file)) { require_once $api_file; } else { http_response_code(404); echo json_encode(['error' => 'Stats API not found']); } exit; } // Определяем action на основе метода switch ($method) { case 'GET': // Если action уже указан в GET параметрах - не перезаписываем if (empty($_GET['action'])) { if ($id) { $_GET['action'] = 'get'; } elseif ($subaction === 'search') { $_GET['action'] = 'search'; } else { $_GET['action'] = 'list'; } } break; case 'POST': $_GET['action'] = 'create'; break; case 'PUT': if ($id) { $_GET['action'] = 'update'; } break; case 'DELETE': if ($id) { $_GET['action'] = 'delete'; } elseif ($subaction === 'logo' && isset($parts[2]) && is_numeric($parts[2])) { $_GET['action'] = 'delete_logo'; $_GET['id'] = (int)$parts[2]; } break; } error_log("Final GET params: " . print_r($_GET, true)); // Подключаем endpoint error_log("Loading API file: " . realpath($api_file)); require_once $api_file; error_log("=== API REQUEST COMPLETE ==="); exit; } // ========== ФРОНТЕНД РОУТИНГ ========== error_log("=== FRONTEND ROUTING ==="); // Проверка авторизации для защищенных страниц $protected_pages = ['admin', 'users', 'collection', 'logout', 'profile']; $public_pages = ['login', 'register', 'home', 'catalog', 'manufacturers', '']; if (in_array($main, $protected_pages) && !isset($_SESSION['user_id'])) { error_log("Redirect to login (protected page)"); header('Location: /login'); exit; } // Если уже авторизован, но пытается зайти на login/register if (in_array($main, ['login', 'register']) && isset($_SESSION['user_id'])) { error_log("Redirect to home (already logged in)"); header('Location: /'); exit; } // Инициализация языка $lang = $_GET['lang'] ?? $_COOKIE['lang'] ?? DEFAULT_LANG ?? 'ru'; if (!isset($_COOKIE['lang']) || $_COOKIE['lang'] != $lang) { setcookie('lang', $lang, time() + 86400 * 30, '/'); } // Маршруты фронтенда $frontend_routes = [ '' => 'catalog', 'catalog' => 'catalog', // Публичный каталог 'models' => 'models', // Админка моделей 'collection' => 'collection', 'admin' => 'admin', 'login' => 'login', 'register' => 'register', 'logout' => 'logout', 'manufacturers' => 'manufacturers', 'users' => 'users', 'profile' => 'profile', '404' => '404' ]; // Определяем какой шаблон загружать $template = $frontend_routes[$main] ?? '404'; error_log("Template: " . $template); // Для выхода - особый обработчик if ($main === 'logout') { session_destroy(); header('Location: /login'); exit; } // Загружаем шаблон $template_file = "templates/{$template}.php"; error_log("Template file: " . $template_file); if (file_exists($template_file)) { // Передаем данные в шаблон $page_data = [ 'user' => $_SESSION['user'] ?? null, 'user_id' => $_SESSION['user_id'] ?? null, 'is_admin' => $_SESSION['is_admin'] ?? false, 'lang' => $lang, 'current_page' => $main ]; extract($page_data); require_once $template_file; } else { error_log("ERROR: Template not found"); header("HTTP/1.0 404 Not Found"); echo "<h1>404 - Страница не найдена</h1>"; echo "<p>Шаблон: " . htmlspecialchars($template_file) . "</p>"; } error_log("=== INDEX.PHP END ==="); ?>