0) {
@ob_end_flush();
return true;
}
return false;
}
/**
* Função segura para ob_end_clean()
* Verifica se há buffer ativo antes de executar
*/
function safe_ob_end_clean() {
if (ob_get_level() > 0) {
@ob_end_clean();
return true;
}
return false;
}
/**
* Função segura para ob_clean()
* Verifica se há buffer ativo antes de executar
*/
function safe_ob_clean() {
if (ob_get_level() > 0) {
@ob_clean();
return true;
}
return false;
}
/**
* Função segura para ob_flush()
* Verifica se há buffer ativo antes de executar
*/
function safe_ob_flush() {
if (ob_get_level() > 0) {
@ob_flush();
return true;
}
return false;
}
/**
* Limpa todos os buffers de saída de forma segura
*/
function safe_ob_clean_all() {
while (ob_get_level() > 0) {
safe_ob_end_clean();
}
}
// ==============================================
// FIM DAS FUNÇÕES DE BUFFERING SEGURO
// ==============================================
// Configurações de erro (código existente mantido)
if (isset($_SESSION['exibir_erros_php'])) {
$valorSessao = strtolower(trim($_SESSION['exibir_erros_php']));
$errosAtivados = ($valorSessao === '1' || $valorSessao === 'true' || $valorSessao === 'ativada' || $valorSessao === 'on');
require_once($_SERVER['DOCUMENT_ROOT'] . '/configuracoes_gerais/erros_php___modo2.php');
}
// ==============================================
// CONFIGURAÇÃO INICIAL E DEBUG MODE
// ==============================================
define('DEBUG_MODE', false);
function debug($message, $level = 'info', $options = []) {
if (!DEBUG_MODE) return;
// Evita saídas para APIs JSON puro
global $api_necessita_gerar_dados_json_puro;
if ($api_necessita_gerar_dados_json_puro === 1) {
error_log("[{$level}] " . print_r($message, true));
return;
}
$colors = [
'error' => 'color: #ff4444; font-weight: bold;',
'warning' => 'color: #ffbb33;',
'success' => 'color: #00C851;',
'info' => 'color: #33b5e5;',
'system' => 'color: #aa66cc;',
'database' => 'color: #2BBBAD;',
'request' => 'color: #ff8800;'
];
$color = $colors[$level] ?? $colors['info'];
$timestamp = date('Y-m-d H:i:s.v');
if (is_array($message) || is_object($message)) {
$message = "
" . print_r($message, true) . "
";
}
$output = "";
$output .= "
[{$timestamp}][{$level}] {$message}";
if (!empty($options['backtrace'])) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$output .= "
Backtrace:";
foreach ($backtrace as $i => $trace) {
$file = $trace['file'] ?? 'unknown';
$line = $trace['line'] ?? 'unknown';
$function = $trace['function'] ?? 'unknown';
$output .= "
#{$i} {$file} (line {$line}): {$function}
";
}
$output .= "
";
}
$output .= "
";
echo $output;
}
// Inicia medição de performance
$start_time = microtime(true);
$start_memory = memory_get_usage();
// ==============================================
// INCLUDES OBRIGATÓRIOS (EXCETO O GERENCIADOR, QUE JÁ FOI INCLUÍDO)
// ==============================================
debug("Iniciando carregamento de includes obrigatórios", "system");
$required_files = [
'/configuracoes_gerais/configuracoes_gerais.php',
'/SERVICOS/controle_de_rotas/verifica_se_requisicao__foi_do_tipo_htmx.php'
];
foreach ($required_files as $file) {
$full_path = $_SERVER['DOCUMENT_ROOT'] . $file;
if (file_exists($full_path)) {
debug("Incluindo arquivo obrigatório: {$file}", "system");
require_once($full_path);
} else {
debug("Arquivo obrigatório não encontrado: {$file}", "error", ['backtrace' => true]);
die("Arquivo essencial não encontrado: {$file}");
}
}
// ==============================================
// TRATAMENTO DE REQUISIÇÃO E URL
// ==============================================
debug("Processando requisição", "request");
$requisicao_foi_do_tipo_htmx = isset($_SERVER['HTTP_HX_REQUEST']) && $_SERVER['HTTP_HX_REQUEST'] === 'true';
debug("Requisição HTMX: " . ($requisicao_foi_do_tipo_htmx ? 'Sim' : 'Não'), "request");
$request_url = $_SERVER['REQUEST_URI'];
debug("URL original: {$request_url}", "request");
$request_url___sem_barra = rtrim($request_url, '/');
debug("URL sem barra final: {$request_url___sem_barra}", "request");
$request_url_sem_query_string = strtok($request_url___sem_barra, '?');
debug("URL sem query string: {$request_url_sem_query_string}", "request");
$url_absoluta_com_parametros = $url_deste_site . $request_url;
$url_absoluta_sem_parametros = $url_deste_site . $request_url_sem_query_string;
$url_absoluta_sem_parametros_e_sem_barra = rtrim($url_absoluta_sem_parametros, '/');
$caminho_relativo_sem_parametros_e_sem_barra = rtrim($request_url_sem_query_string, '/');
debug("URLs construídas:", "request", [
'Com parâmetros' => $url_absoluta_com_parametros,
'Sem parâmetros' => $url_absoluta_sem_parametros,
'url_absoluta_sem_parametros_e_sem_barra' => $url_absoluta_sem_parametros_e_sem_barra,
'Caminho relativo' => $caminho_relativo_sem_parametros_e_sem_barra
]);
$query_string = parse_url($request_url, PHP_URL_QUERY);
if ($query_string !== null && $query_string !== '') {
parse_str($query_string, $params);
debug("Parâmetros da URL extraídos:", "request", $params);
} else {
$params = [];
debug("Nenhum parâmetro na URL", "request");
}
// ==============================================
// VERIFICAÇÃO DE ARQUIVO FÍSICO
// ==============================================
$file_path = $_SERVER['DOCUMENT_ROOT'] . $caminho_relativo_sem_parametros_e_sem_barra;
debug("Caminho físico do arquivo: {$file_path}", "system");
if (file_exists($file_path)) {
debug("Arquivo físico encontrado", "success");
extract($params);
debug("Parâmetros extraídos para escopo global", "system", array_keys($params));
} else {
debug("Arquivo físico não encontrado", "warning");
}
// ==============================================
// REDIRECIONAMENTOS ESPECÍFICOS
// ==============================================
$urls_raiz = [
$url_deste_site,
$url_deste_site . "/",
$url_deste_site . "/index.php",
$url_deste_site . "/index.php/"
];
// ==============================================
// VERIFICA SE A REQUISIÇÃO JÁ É UM REDIRECIONAMENTO INTERNO
// ==============================================
// Se já veio de um redirecionamento (header X-Redirecionar-Header existe)
// NÃO redireciona novamente para evitar loop
$is_redirecionamento_interno = isset($_SERVER['HTTP_X_REDIRECIONAR_HEADER']) &&
in_array($_SERVER['HTTP_X_REDIRECIONAR_HEADER'], ['n', 's']);
debug("Verificando URLs raiz para redirecionamento", "request");
debug("É redirecionamento interno? " . ($is_redirecionamento_interno ? 'Sim' : 'Não'), "request");
if (!$is_redirecionamento_interno && in_array($url_absoluta_sem_parametros, $urls_raiz)) {
debug("URL raiz detectada - redirecionando para conteúdo padrão", "info");
header("X-Redirecionar-Header: n");
header("Location: {$url_deste_site}/SERVICOS/opcoes/conteudo_dinamico_padrao.php");
safe_ob_end_flush(); // Substituído por versão segura
exit;
}
// Se for redirecionamento interno e está na raiz, continua normalmente
if ($is_redirecionamento_interno && in_array($url_absoluta_sem_parametros, $urls_raiz)) {
debug("Requisição é redirecionamento interno na raiz - processando normalmente", "info");
// Não faz nada, apenas continua o fluxo
}
// ==============================================
// GERENCIAMENTO DE ROTAS
// ==============================================
debug("Verificando condições para roteamento", "system");
if (isset($url_absoluta_sem_parametros) && $url_absoluta_sem_parametros !== $url_raiz_do_site) {
debug("Incluindo gerenciador de URLs e arquivos", "info");
require_once($_SERVER['DOCUMENT_ROOT'] . '/SERVICOS/gerenciamento_de_urls_e_arquivos_do_site/gerenciamento_de_urls_e_arquivos_do_site.php');
}
// ==============================================
// CONSULTA AO BANCO DE DADOS PARA ROTEAMENTO
// ==============================================
debug("Iniciando consulta ao banco de dados", "info");
// Valores padrão
$usar_template_index_principal = 0;
$carregar_dentro_de_iframe = 0;
$refresh_obrigatorio = 0;
$titulo_pagina = $frase_padrao_do_site ?? 'Atenção aqui...';
$voltar_ao_topo_apos_carregamento_ou_refresh = 0;
$api_necessita_gerar_dados_json_puro = 0;
if (isset($pool)) {
try {
debug("Preparando consulta ao banco para URL: " . $url_absoluta_sem_parametros_e_sem_barra, "info");
// CORRETO: Pega a conexão persistente do Pool
$conexao = $pool->getMysqliConnection();
$sql = "SELECT usar_template_index_principal,
carregar_dentro_de_iframe,
refresh_obrigatorio,
titulo_pagina,
voltar_ao_topo_apos_carregamento_ou_refresh,
api___necessita_gerar_dados_json_puro
FROM gerenciamentos___arquivos_do_site___lista_permanente
WHERE url = ? LIMIT 1";
$stmt = $conexao->prepare($sql);
if ($stmt) {
$stmt->bind_param("s", $url_absoluta_sem_parametros_e_sem_barra);
$stmt->execute();
$resultado_obj = $stmt->get_result();
if ($resultado = $resultado_obj->fetch_assoc()) {
debug("Resultado da consulta encontrado.", "success");
$usar_template_index_principal = (int)$resultado['usar_template_index_principal'];
$carregar_dentro_de_iframe = (int)$resultado['carregar_dentro_de_iframe'];
$refresh_obrigatorio = (int)$resultado['refresh_obrigatorio'];
$titulo_pagina = $resultado['titulo_pagina'] ?? $titulo_pagina;
$voltar_ao_topo_apos_carregamento_ou_refresh = (int)$resultado['voltar_ao_topo_apos_carregamento_ou_refresh'];
$api_necessita_gerar_dados_json_puro = (int)$resultado['api___necessita_gerar_dados_json_puro'];
}
$stmt->close(); // FECHA O COMANDO AGORA! Libera o MySQL para outros processos.
}
} catch (Exception $e) {
debug("Erro ao consultar roteamento: " . $e->getMessage(), "error");
}
}
// ==============================================
// VERIFICAÇÃO PARA REQUISIÇÕES AJAX
// ==============================================
$is_ajax_request = isset($_GET['ajax']) ||
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
if ($is_ajax_request) {
debug("Requisição AJAX detectada - permitindo processamento direto", "request");
// Verificar se o arquivo existe
if (file_exists($file_path) && pathinfo($file_path, PATHINFO_EXTENSION) === 'php') {
safe_ob_end_clean();
include $file_path;
exit;
}
}
// ==============================================
// DECISÃO DE ROTEAMENTO - GLOBAL PARA APIS
// ==============================================
debug("Iniciando decisão de roteamento", "info");
// NOVA REGRA: Se a URL contiver "/apis/", o roteamento é automático e direto
$is_api_folder = (strpos($request_url, '/apis/') !== false);
if ($api_necessita_gerar_dados_json_puro === 1 || $is_api_folder) {
debug("Pasta API ou JSON puro detectada - processamento direto.", "success");
if (file_exists($file_path) && pathinfo($file_path, PATHINFO_EXTENSION) === 'php') {
safe_ob_clean_all(); // Limpa qualquer lixo de buffer dos includes anteriores
include $file_path;
exit;
}
}
// ==============================================
// DECISÃO DE ROTEAMENTO SIMPLIFICADA
// ==============================================
// CASO 1: API JSON puro (SEMPRE sai com exit)
if ($api_necessita_gerar_dados_json_puro === 1) {
debug("API JSON puro detectada - incluindo arquivo diretamente: " . $file_path, "success");
if (file_exists($file_path) && pathinfo($file_path, PATHINFO_EXTENSION) === 'php') {
safe_ob_end_clean();
include $file_path;
exit;
} else {
debug("Arquivo não encontrado para API JSON - retornando erro", "error");
http_response_code(404);
echo json_encode(['error' => 'Arquivo da API não encontrado']);
exit;
}
}
// CASO 2: Arquivo NÃO existe → 404
if (!file_exists($file_path)) {
debug("Arquivo não encontrado - redirecionando para 404", "error");
http_response_code(404);
header('Location: ' . $url_deste_site . '/SERVICOS/opcoes/conteudo_dinamico_padrao.php');
safe_ob_end_flush();
exit;
}
// CASO 3: É arquivo estático (NÃO é PHP) → Apache serve
$extensao = pathinfo($file_path, PATHINFO_EXTENSION);
if ($extensao !== 'php') {
debug("Arquivo estático (.{$extensao}) - deixando o servidor web servir", "info");
safe_ob_end_flush();
return false; // APENAS return, NÃO exit
}
// CASO 4: Arquivo PHP mas NÃO usa template → Inclui direto
if ($usar_template_index_principal === 0) {
debug("Arquivo PHP sem template - incluindo diretamente: " . $file_path, "success");
include $file_path;
safe_ob_end_flush();
exit;
}
// CASO 5: Se chegou aqui → Arquivo PHP COM template
// O fluxo CONTINUA para carregar o template (NÃO faz exit)
debug("Arquivo PHP COM template - continuando para carregar template", "success");
if ($refresh_obrigatorio === 1) {
debug("Refresh obrigatório ativado", "warning");
header("Refresh: 0; url=" . $url_absoluta_sem_parametros_e_sem_barra);
safe_ob_end_flush(); // Substituído por versão segura
exit;
}
if ($voltar_ao_topo_apos_carregamento_ou_refresh === 1) {
debug("voltar_ao_topo_apos_carregamento_ou_refresh ativado", "warning");
// Não faz refresh, apenas marca que a rolagem deve voltar ao topo
// O script será injetado no abaixo
}
debug("Usando template principal", "success");
// ==============================================
// TEMPLATE PRINCIPAL
// ==============================================
$titulo = $titulo_pagina;
$template___configuracoes_gerais___obrigatorio = true;
$template___erros_php___obrigatorio = false;
$template___autenticacao_do_usuario___obrigatoria = false;
$template___css___estilos_globais___obrigatorio = true;
$template___javascripts_gerais___obrigatorio = true;
$template___biblioteca_htmx___obrigatorio = false;
$template___meta_tags_definidas_pelo_dono_do_site = true;
$template___header___obrigatorio = true;
$template___main___obrigatorio = true;
$template___menu_lateral_esquerdo___obrigatorio = true;
$template___modal_flutuante_central___obrigatorio = false;
$template___footer___obrigatorio = true;
$template___alternar_tela_cheia = true;
debug("Configurações do template:", "info", [
'titulo' => $titulo,
'template_configs' => [
'configuracoes_gerais' => $template___configuracoes_gerais___obrigatorio,
'erros_php' => $template___erros_php___obrigatorio,
'autenticacao' => $template___autenticacao_do_usuario___obrigatoria,
'css' => $template___css___estilos_globais___obrigatorio,
'javascript' => $template___javascripts_gerais___obrigatorio,
'htmx' => $template___biblioteca_htmx___obrigatorio,
'meta_tags' => $template___meta_tags_definidas_pelo_dono_do_site,
'header' => $template___header___obrigatorio,
'main' => $template___main___obrigatorio,
'menu_lateral' => $template___menu_lateral_esquerdo___obrigatorio,
'modal_flutuante_central' => $template___modal_flutuante_central___obrigatorio,
'footer' => $template___footer___obrigatorio,
'tela_cheia' => $template___alternar_tela_cheia
]
]);
// Gera o HTML apenas se não houver redirecionamento
safe_ob_end_flush(); // Substituído por versão segura
?>
document.addEventListener("DOMContentLoaded", function() {
resetarEstadoDaRolagem___manualmente();
const url = window.location.href;
const estadosRolagem = JSON.parse(sessionStorage.getItem("estadosRolagem") || "{}");
if (estadosRolagem[url]) {
delete estadosRolagem[url];
sessionStorage.setItem("estadosRolagem", JSON.stringify(estadosRolagem));
console.log(`Estado de rolagem limpo para a URL ${url}`);
}
console.warn("Rolagem resetada automaticamente após envio do formulário");
});
';
unset($_SESSION['form_submitted']);
}
?>
round($execution_time, 4) . ' segundos',
'Uso de memória' => round($memory_usage, 2) . ' MB',
'Arquivos incluídos' => count(get_included_files())
]);
}
});
?>