File manager - Edit - /var/www/html/homologParquetecmar/app/Http/Controllers/ElementsController.php
Back
<?php namespace App\Http\Controllers; use App\Mail\ContactFormMail; use App\Services\FormSecurityService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Illuminate\Validation\Rule; class ElementsController extends Controller { private function getApiUrl(): string { return rtrim(config('services.angra_api.url', 'https://www.angra.rj.gov.br/api'), '/'); } /** * Faz a requisição HTTP à API do Angra (com suporte a localhost e domínios .test em desenvolvimento). */ private function httpGet(string $url): \Illuminate\Http\Client\Response { $client = Http::timeout(15)->connectTimeout(5); $isLocalUrl = str_contains($url, '127.0.0.1') || str_contains($url, 'localhost') || str_contains($url, '.test'); if ($isLocalUrl) { $client = $client->withoutVerifying(); } return $client->get($url); } /** * Extrai o array 'data' da resposta da API; fallback para resposta direta. */ private function parseApiData(\Illuminate\Http\Client\Response $response): array { $body = $response->json(); if (isset($body['data']) && is_array($body['data'])) { return $body['data']; } return is_array($body) ? $body : []; } public function index() { $editais = []; $decretosLeis = []; $noticias = []; $areas = []; $faqs = []; $startups = []; try { $editais = $this->fetchEditais(); } catch (\Throwable $e) { Log::error('Erro ao carregar editais na home', ['message' => $e->getMessage()]); } try { $decretosLeis = $this->fetchDecretosLeis(); } catch (\Throwable $e) { Log::error('Erro ao carregar decretos/leis na home', ['message' => $e->getMessage()]); } try { $noticias = $this->fetchNoticias(); } catch (\Throwable $e) { Log::error('Erro ao carregar notícias na home', ['message' => $e->getMessage()]); } try { $areas = $this->fetchAreas(); } catch (\Throwable $e) { Log::error('Erro ao carregar áreas na home', ['message' => $e->getMessage()]); } try { $faqs = $this->fetchFaqs(); } catch (\Throwable $e) { Log::error('Erro ao carregar FAQs na home', ['message' => $e->getMessage()]); } try { $startups = $this->fetchStartups(); } catch (\Throwable $e) { Log::error('Erro ao carregar startups na home', ['message' => $e->getMessage()]); } // Limitamos a 6 áreas para manter o layout atual da section "Nossas Áreas" $areas = array_slice($areas, 0, 6); return view('index', compact('editais', 'decretosLeis', 'noticias', 'areas', 'faqs', 'startups')); } /** * Página de detalhe de um edital (slug). */ public function editalShow(string $slug) { $edital = $this->fetchEditalBySlug($slug); if (empty($edital)) { abort(404, 'Edital não encontrado.'); } return view('editais.show', compact('edital')); } /** * Página de detalhe de um decreto/lei (slug). */ public function decretoLeiShow(string $slug) { $decretoLei = $this->fetchDecretoLeiBySlug($slug); if (empty($decretoLei)) { abort(404, 'Decreto ou lei não encontrado.'); } return view('decretos-leis.show', compact('decretoLei')); } /** * Busca um edital por slug na API do Angra. */ private function fetchEditalBySlug(string $slug): ?array { try { $url = $this->getApiUrl() . '/parquetecmar/editais/' . $slug; $response = $this->httpGet($url); if ($response->successful()) { return $response->json(); } } catch (\Exception $e) { Log::error('Erro ao buscar edital por slug', ['slug' => $slug, 'message' => $e->getMessage()]); } return null; } /** * Busca um decreto/lei por slug na API do Angra. */ private function fetchDecretoLeiBySlug(string $slug): ?array { try { $url = $this->getApiUrl() . '/parquetecmar/decretos-leis/' . $slug; $response = $this->httpGet($url); if ($response->successful()) { return $response->json(); } } catch (\Exception $e) { Log::error('Erro ao buscar decreto/lei por slug', ['slug' => $slug, 'message' => $e->getMessage()]); } return null; } /** * Busca editais da API do Angra (consumo direto; dados sempre atualizados). */ private function fetchEditais(): array { try { $url = $this->getApiUrl() . '/parquetecmar/editais?limit=6'; $response = $this->httpGet($url); if ($response->successful()) { return $this->parseApiData($response); } Log::warning('Falha ao buscar editais da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de editais', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/parquetecmar/editais?limit=6', ]); return []; } } /** * Busca decretos/leis da API do Angra (consumo direto; dados sempre atualizados). */ private function fetchDecretosLeis(): array { try { $url = $this->getApiUrl() . '/parquetecmar/decretos-leis?limit=6'; $response = $this->httpGet($url); if ($response->successful()) { return $this->parseApiData($response); } Log::warning('Falha ao buscar decretos/leis da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de decretos/leis', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/parquetecmar/decretos-leis?limit=6', ]); return []; } } /** * Busca as áreas de atuação do Parque Tecnológico do Mar na API do Angra. */ private function fetchAreas(): array { try { $url = $this->getApiUrl() . '/parque-tecnologico/areas'; $response = $this->httpGet($url); if ($response->successful()) { // A API retorna um array simples de áreas (sem wrapper "data") return $this->parseApiData($response); } Log::warning('Falha ao buscar áreas da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de áreas do Parque Tecnológico', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/parque-tecnologico/areas', ]); return []; } } /** * Busca notícias do Parque Tecnológico do Mar da API do Angra (consumo direto). */ private function fetchNoticias(): array { try { $url = $this->getApiUrl() . '/noticias?categoria=PARQUE_TECMAR&limite=12'; $response = $this->httpGet($url); if ($response->successful()) { $body = $response->json(); return is_array($body) ? array_slice($body, 0, 12) : []; } Log::warning('Falha ao buscar notícias da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de notícias', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/noticias?categoria=PARQUE_TECMAR&limite=12', ]); return []; } } /** * Busca perguntas frequentes do Parque Tecnológico do Mar na API do Angra. */ private function fetchFaqs(): array { try { $url = $this->getApiUrl() . '/parquetecmar/faqs?limit=10'; $response = $this->httpGet($url); if ($response->successful()) { return $this->parseApiData($response); } Log::warning('Falha ao buscar FAQs da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de FAQs do Parque Tecnológico', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/parquetecmar/faqs?limit=10', ]); return []; } } /** * Busca startups da API do Angra (consumo direto; dados sempre atualizados). */ private function fetchStartups(?string $segmento = null): array { try { $url = $this->getApiUrl() . '/parquetecmar/startups'; if ($segmento) { $url .= '?segmento=' . urlencode($segmento); } $response = $this->httpGet($url); if ($response->successful()) { return $this->parseApiData($response); } Log::warning('Falha ao buscar startups da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); return []; } catch (\Exception $e) { Log::error('Erro ao consumir API de startups', [ 'message' => $e->getMessage(), 'url' => $this->getApiUrl() . '/parquetecmar/startups', ]); return []; } } /** * Página de listagem de startups com filtro por segmento. */ public function startups(Request $request) { $segmento = $request->query('segmento'); $startups = $this->fetchStartups($segmento); $segmentos = [ 'tecnologia' => 'Tecnologia', 'energia' => 'Energia', 'logistica' => 'Logística', 'sustentabilidade' => 'Sustentabilidade', 'nautica_naval' => 'Náutica & Naval', ]; return view('startups', compact('startups', 'segmentos', 'segmento')); } /** * Página de detalhe dinâmico de uma startup (slug ou ID). */ public function startupShow(string $slug) { $startup = $this->fetchStartupBySlug($slug); if (empty($startup)) { abort(404, 'Startup não encontrada.'); } return view('startups.show', compact('startup')); } /** * Busca uma startup por slug na API do Angra. */ private function fetchStartupBySlug(string $slug): ?array { try { $url = $this->getApiUrl() . '/parquetecmar/startups/' . $slug; $response = $this->httpGet($url); if ($response->successful()) { return $response->json(); } } catch (\Exception $e) { Log::error('Erro ao buscar startup por slug', ['slug' => $slug, 'message' => $e->getMessage()]); } return null; } /** * Página completa de todos os editais. */ public function editais() { $editais = $this->fetchAllEditais(); return view('editais', compact('editais')); } /** * Página completa de todos os decretos e leis. */ public function decretosLeis() { $decretosLeis = $this->fetchAllDecretosLeis(); return view('decretos-leis', compact('decretosLeis')); } /** * Busca todos os editais da API do Angra (consumo direto; todas as páginas). */ private function fetchAllEditais(): array { try { $all = []; $page = 1; $perPage = 50; do { $url = $this->getApiUrl() . '/parquetecmar/editais?page=' . $page . '&per_page=' . $perPage; $response = $this->httpGet($url); if (!$response->successful()) { Log::warning('Falha ao buscar editais da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); break; } $body = $response->json(); $data = isset($body['data']) && is_array($body['data']) ? $body['data'] : []; $all = array_merge($all, $data); $lastPage = $body['meta']['last_page'] ?? 1; $page++; } while ($page <= $lastPage && count($data) === $perPage); return $all; } catch (\Exception $e) { Log::error('Erro ao consumir API de todos os editais', ['message' => $e->getMessage()]); return []; } } /** * Busca todos os decretos/leis da API do Angra (consumo direto; todas as páginas). */ private function fetchAllDecretosLeis(): array { try { $all = []; $page = 1; $perPage = 50; do { $url = $this->getApiUrl() . '/parquetecmar/decretos-leis?page=' . $page . '&per_page=' . $perPage; $response = $this->httpGet($url); if (!$response->successful()) { Log::warning('Falha ao buscar decretos/leis da API do Angra', [ 'status' => $response->status(), 'url' => $url, 'body' => $response->body(), ]); break; } $body = $response->json(); $data = isset($body['data']) && is_array($body['data']) ? $body['data'] : []; $all = array_merge($all, $data); $lastPage = $body['meta']['last_page'] ?? 1; $page++; } while ($page <= $lastPage && count($data) === $perPage); return $all; } catch (\Exception $e) { Log::error('Erro ao consumir API de todos os decretos/leis', ['message' => $e->getMessage()]); return []; } } /** * Processa o formulário de contato e envia emails. * Proteções aplicadas: honeypot, time trap, user-agent, sanitização anti-HTML, * token CSRF (middleware), rate-limit por IP (middleware), Cloudflare Turnstile (se configurado). */ public function sendContactForm(Request $request) { $security = app(FormSecurityService::class); $sanitized = []; // Executa todas as verificações de segurança; em falha, redireciona com mensagem genérica if (! $security->runAllChecks($request, $sanitized)) { return redirect() ->route('index') ->with('error', FormSecurityService::MESSAGE_INVALID_SUBMISSION) ->withFragment('contact') ->withInput($request->only(['nome', 'email', 'telefone', 'cpf_cnpj', 'area_interesse', 'sugestoes', 'lgpd_aceite'])); } // Validações de formato no backend (conteúdo sem HTML já garantido pelo FormSecurityService) $request->validate([ 'nome' => 'required|string|max:255', 'email' => 'required|email:rfc,dns|max:255', 'telefone' => 'nullable|string|max:30', 'cpf_cnpj' => 'nullable|string|max:25', 'area_interesse' => ['required', Rule::in(config('form-security.areas_interesse', []))], 'sugestoes' => 'required|string|max:5000', 'lgpd_aceite' => 'required|accepted', ]); try { $nome = $sanitized['nome']; $email = $sanitized['email']; $telefone = $sanitized['telefone'] ?? ''; $cpfCnpj = $sanitized['cpf_cnpj'] ?? ''; $areaInteresse = $sanitized['area_interesse']; $sugestoes = $sanitized['sugestoes']; $emailsDestino = config('form-security.contact_emails', []); if (empty($emailsDestino)) { Log::error('Formulário de contato: nenhum e-mail de destino configurado (CONTACT_FORM_EMAILS no .env)'); return redirect() ->route('index') ->with('error', 'Erro ao enviar mensagem. Por favor, tente novamente mais tarde.') ->withFragment('contact'); } foreach ($emailsDestino as $emailDestino) { Mail::to($emailDestino)->send(new ContactFormMail($nome, $email, $telefone, $cpfCnpj, $areaInteresse, $sugestoes)); } return redirect() ->route('index') ->with('success', 'Mensagem enviada com sucesso! Entraremos em contato em breve.') ->withFragment('contact'); } catch (\Exception $e) { Log::error('Erro ao enviar formulário de contato', [ 'message' => $e->getMessage(), 'nome' => $request->input('nome'), 'email' => $request->input('email'), ]); return redirect() ->route('index') ->with('error', 'Erro ao enviar mensagem. Por favor, tente novamente mais tarde.') ->withFragment('contact'); } } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings