90 lines
2.5 KiB
PHP
Executable File
90 lines
2.5 KiB
PHP
Executable File
<?php
|
|
require_once __DIR__ . '/../config/db.php';
|
|
|
|
// 产品切换
|
|
if (isset($_GET['set_product'])) {
|
|
$pid = (int)$_GET['set_product'];
|
|
if ($pid > 0) {
|
|
if (isAdmin()) {
|
|
$stmt = $pdo->prepare('SELECT id FROM products WHERE id = ? AND status = 1');
|
|
$stmt->execute([$pid]);
|
|
} else if (isset($_SESSION['user_id'])) {
|
|
$stmt = $pdo->prepare('SELECT p.id FROM products p INNER JOIN user_products up ON p.id = up.product_id WHERE p.id = ? AND p.status = 1 AND up.user_id = ?');
|
|
$stmt->execute([$pid, $_SESSION['user_id']]);
|
|
}
|
|
if ($stmt && $stmt->fetch()) {
|
|
$_SESSION['current_product_id'] = $pid;
|
|
}
|
|
}
|
|
$url = strtok($_SERVER['REQUEST_URI'], '?');
|
|
$params = $_GET;
|
|
unset($params['set_product']);
|
|
if ($params) {
|
|
$url .= '?' . http_build_query($params);
|
|
}
|
|
header("Location: $url");
|
|
exit;
|
|
}
|
|
|
|
function isLoggedIn(): bool {
|
|
return isset($_SESSION['user_id']);
|
|
}
|
|
|
|
function requireLogin(): void {
|
|
if (!isLoggedIn()) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
}
|
|
|
|
function isAdmin(): bool {
|
|
return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
|
|
}
|
|
|
|
function requireAdmin(): void {
|
|
requireLogin();
|
|
if (!isAdmin()) {
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
}
|
|
|
|
function getCurrentUserId(): ?int {
|
|
return $_SESSION['user_id'] ?? null;
|
|
}
|
|
|
|
function getCurrentUsername(): ?string {
|
|
return $_SESSION['username'] ?? null;
|
|
}
|
|
|
|
function getCurrentProductId(): ?int {
|
|
$pid = $_SESSION['current_product_id'] ?? null;
|
|
if ($pid) {
|
|
$products = getEnabledProducts();
|
|
$ids = array_column($products, 'id');
|
|
if (!in_array($pid, $ids)) {
|
|
unset($_SESSION['current_product_id']);
|
|
$pid = null;
|
|
}
|
|
}
|
|
if (!$pid) {
|
|
$products = getEnabledProducts();
|
|
if (!empty($products)) {
|
|
$_SESSION['current_product_id'] = (int)$products[0]['id'];
|
|
$pid = (int)$products[0]['id'];
|
|
}
|
|
}
|
|
return $pid;
|
|
}
|
|
|
|
function getEnabledProducts(): array {
|
|
global $pdo;
|
|
if (isAdmin()) {
|
|
$stmt = $pdo->query('SELECT id, name FROM products WHERE status = 1 ORDER BY id ASC');
|
|
} else {
|
|
$stmt = $pdo->prepare('SELECT p.id, p.name FROM products p INNER JOIN user_products up ON p.id = up.product_id WHERE up.user_id = ? AND p.status = 1 ORDER BY p.id ASC');
|
|
$stmt->execute([getCurrentUserId()]);
|
|
}
|
|
return $stmt->fetchAll();
|
|
}
|