false, 'message' => '不支持的请求方法' ]); break; } } catch (Exception $e) { echo json_encode([ 'success' => false, 'message' => '服务器内部错误: ' . $e->getMessage() ]); } /** * 获取日志列表 * @param Database $db 数据库实例 */ function getLogs($db) { // 获取请求参数 $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = 10; $offset = ($page - 1) * $perPage; // 过滤条件 $search = isset($_GET['search']) ? $_GET['search'] : ''; $type = isset($_GET['type']) ? $_GET['type'] : ''; $startDate = isset($_GET['startDate']) ? $_GET['startDate'] : ''; $endDate = isset($_GET['endDate']) ? $_GET['endDate'] : ''; // 构建查询条件 $where = ''; $params = []; $conditions = []; if (!empty($search)) { $conditions[] = "message LIKE ?"; $params[] = "%$search%"; } if (!empty($type)) { $conditions[] = "type = ?"; $params[] = $type; } if (!empty($startDate)) { $conditions[] = "created_at >= ?"; $params[] = $startDate . " 00:00:00"; } if (!empty($endDate)) { $conditions[] = "created_at <= ?"; $params[] = $endDate . " 23:59:59"; } if (!empty($conditions)) { $where = "WHERE " . implode(" AND ", $conditions); } // 查询日志总数 $totalSql = "SELECT COUNT(*) as total FROM logs $where"; $totalResult = $db->fetchOne($totalSql, $params); $total = $totalResult['total']; // 查询日志列表 $logsSql = "SELECT * FROM logs $where ORDER BY created_at DESC LIMIT ? OFFSET ?"; $logsParams = array_merge($params, [$perPage, $offset]); $logs = $db->fetchAll($logsSql, $logsParams); // 格式化日志数据 $formattedLogs = []; foreach ($logs as $log) { $formattedLogs[] = [ 'id' => $log['id'], 'type' => $log['type'], 'message' => $log['message'], 'ip' => $log['ip'], 'user_id' => $log['user_id'], 'created_at' => $log['created_at'] ]; } // 返回响应 echo json_encode([ 'success' => true, 'data' => [ 'logs' => $formattedLogs, 'total' => $total, 'page' => $page, 'perPage' => $perPage, 'totalPages' => ceil($total / $perPage) ] ]); } /** * 删除日志 * @param Database $db 数据库实例 */ function deleteLogs($db) { // 获取请求参数 $id = isset($_GET['id']) ? (int)$_GET['id'] : 0; $all = isset($_GET['all']) ? $_GET['all'] : false; if ($id <= 0 && !$all) { echo json_encode([ 'success' => false, 'message' => '无效的日志ID' ]); return; } if ($all) { // 删除所有日志 $db->execute("DELETE FROM logs"); echo json_encode([ 'success' => true, 'message' => '所有日志已删除' ]); } else { // 删除指定日志 $db->delete("DELETE FROM logs WHERE id = ?", [$id]); echo json_encode([ 'success' => true, 'message' => '日志删除成功' ]); } }