['pdf','jpg','jpeg','png'], 'arquivo_romaneio' => ['pdf','xlsx','xls','doc','docx'], 'arquivo_outros' => ['zip','pdf','jpg','jpeg','png'] ]; /* ===================================================== */ /* ---------- Helpers ---------- */ function fail($msg){ header("Location: " . REDIRECT_ERROR . urlencode($msg)); exit; } function val($key){ return isset($_POST[$key]) ? trim((string)$_POST[$key]) : ""; } function boolstr($v){ $v = mb_strtolower($v,'UTF-8'); return ($v==='sim' || $v==='true' || $v==='1') ? 'Sim' : 'Não'; } /* ---------- Método ---------- */ if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo "Method not allowed"; exit; } /* Honeypot */ if (!empty($_POST['website'])) { fail("detected-spam"); } /* CSRF básico */ if (empty($_POST['csrf_token']) || !preg_match('/^[a-z0-9]+$/i', $_POST['csrf_token'])) { fail("csrf-invalid"); } /* reCAPTCHA v3 */ if (!empty(RECAPTCHA_SECRET)) { $token = $_POST['recaptcha_token'] ?? ''; if (!$token) fail("recaptcha-missing"); $resp = @file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".urlencode(RECAPTCHA_SECRET)."&response=".urlencode($token)); $json = @json_decode($resp, true); if (!$json || empty($json['success']) || (isset($json['score']) && $json['score'] < 0.4)) { fail("recaptcha-failed"); } } /* ---------- Campos ---------- */ $cnpj_pagador = val('cnpj_pagador'); $contato_nome = val('contato_nome'); $contato_email = val('contato_email'); $contato_tel = val('contato_tel'); $tipo_mercadoria = val('tipo_mercadoria'); $tipo_embalagem = val('tipo_embalagem'); $cep_origem = val('cep_origem'); $cep_destino = val('cep_destino'); $coletar = val('coletar'); $entregar = val('entregar'); $opt_operacional = val('opt_operacional'); $especie_nota = val('especie_nota'); $cnpj_remetente = val('cnpj_remetente'); $ie_remetente = val('ie_remetente'); $cnpj_destinatario = val('cnpj_destinatario'); $ie_destinatario = val('ie_destinatario'); $end_remetente = val('end_remetente'); $end_destinatario = val('end_destinatario'); $valor_nf = val('valor_nf'); $qtd_volumes = val('qtd_volumes'); $peso_real = val('peso_real'); $obs_embalagem = val('obs_embalagem'); $obs = val('obs'); $consent = isset($_POST['consent']); /* ---------- Validações ---------- */ $required = [ 'cnpj_pagador' => $cnpj_pagador, 'contato_nome' => $contato_nome, 'contato_email' => $contato_email, 'contato_tel' => $contato_tel, 'tipo_mercadoria' => $tipo_mercadoria, 'tipo_embalagem' => $tipo_embalagem, 'cep_origem' => $cep_origem, 'cep_destino' => $cep_destino, 'coletar' => $coletar, 'entregar' => $entregar, 'especie_nota' => $especie_nota, 'cnpj_remetente' => $cnpj_remetente, 'cnpj_destinatario'=> $cnpj_destinatario, 'valor_nf' => $valor_nf, 'qtd_volumes' => $qtd_volumes, 'peso_real' => $peso_real, ]; foreach($required as $k=>$v){ if($v==="") fail("campo-$k-obrigatorio"); } if (mb_strtolower($coletar,'UTF-8')==='sim' && $end_remetente==="") fail("endereco-remetente-obrigatorio-quando-coletar-sim"); if (mb_strtolower($entregar,'UTF-8')==='sim' && $end_destinatario==="") fail("endereco-destinatario-obrigatorio-quando-entregar-sim"); if (!$consent) fail("consentimento-obrigatorio"); /* Dimensões (linhas dinâmicas) */ $dimensoes = []; foreach($_POST as $k=>$v){ if (preg_match('/^comp_(\d+)$/',$k,$m)){ $i = $m[1]; $c = trim($v); $l = $_POST["larg_$i"] ?? ''; $a = $_POST["alt_$i"] ?? ''; $q = $_POST["qtd_$i"] ?? ''; if($c!=='' || $l!=='' || $a!=='' || $q!==''){ $dimensoes[] = "#$i: {$c}×{$l}×{$a} cm | Qtde: {$q}"; } } } /* ---------- Anexos ---------- */ $filesToAttach = []; foreach($ALLOWED as $field=>$exts){ if(isset($_FILES[$field]) && $_FILES[$field]['error'] !== UPLOAD_ERR_NO_FILE){ $err = $_FILES[$field]['error']; if($err !== UPLOAD_ERR_OK) fail("upload-falhou-$field-err$err"); if($_FILES[$field]['size'] > MAX_BYTES) fail("arquivo-muito-grande-$field"); $name = $_FILES[$field]['name']; $tmp = $_FILES[$field]['tmp_name']; $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION)); if(!in_array($ext, $exts)) fail("extensao-nao-permitida-$field"); $mime = function_exists('mime_content_type') ? mime_content_type($tmp) : 'application/octet-stream'; $data = file_get_contents($tmp); if($data === false) fail("nao-foi-possivel-ler-$field"); if (SAVE_UPLOADS) { @move_uploaded_file($tmp, __DIR__."/uploads/".basename($name)); /* opcional */ } $filesToAttach[] = ['name'=>$name, 'mime'=>$mime, 'data'=>$data]; } } /* ---------- Corpo texto ---------- */ $subject = "Cotação: {$tipo_mercadoria} — {$cep_origem} → {$cep_destino}"; $lines = [ "COTAÇÃO DE FRETE — Transportadora Jacareí Ltda.", "", "• DADOS DO SOLICITANTE", "CNPJ do pagador: $cnpj_pagador", "Contato: $contato_nome", "Telefone: $contato_tel", "E-mail: $contato_email", "Tipo de mercadoria: $tipo_mercadoria", "Tipo de embalagem: $tipo_embalagem", "", "• ORIGEM & DESTINO", "CEP de origem: $cep_origem", "CEP de destino: $cep_destino", "Coletar: ".boolstr($coletar), "Entregar: ".boolstr($entregar), "Opção operacional: ".($opt_operacional?:'-'), "", "• REMETENTE & DESTINATÁRIO", "CNPJ remetente: $cnpj_remetente", "IE remetente: ".($ie_remetente?:'-'), "Endereço remetente: ".($end_remetente?:'-'), "CNPJ destinatário: $cnpj_destinatario", "IE destinatário: ".($ie_destinatario?:'-'), "Endereço destinatário: ".($end_destinatario?:'-'), "", "• DADOS DA CARGA", "Espécie da Nota: $especie_nota", "Valor da NF: $valor_nf", "Qtde de volumes: $qtd_volumes", "Peso real (kg): $peso_real", "Obs. embalagem: ".($obs_embalagem?:'-'), "", "• DIMENSÕES (por volume)" ]; $lines = array_merge($lines, $dimensoes ?: ['(não informado)']); $lines[] = ""; $lines[] = "• OBSERVAÇÕES"; $lines[] = ($obs?:'-'); $lines[] = ""; $lines[] = "Confirmação: Li e concordo com a Política operacional e Nota de Privacidade."; $bodyText = implode("\r\n", $lines); /* ---------- PDF (opcional com Dompdf) ---------- */ $pdfAttachment = null; if (GENERATE_PDF) { // Requer: composer require dompdf/dompdf $dompdfAutoload = __DIR__ . '/vendor/autoload.php'; if (file_exists($dompdfAutoload)) { require_once $dompdfAutoload; try { $html = "

Cotação de Frete — Transportadora Jacareí

".htmlspecialchars($bodyText)."
"; $dompdf = new Dompdf\Dompdf(['isRemoteEnabled'=>true]); $dompdf->loadHtml($html, 'UTF-8'); $dompdf->setPaper('A4', 'portrait'); $dompdf->render(); $pdfAttachment = [ 'name' => 'cotacao-tj.pdf', 'mime' => 'application/pdf', 'data' => $dompdf->output() ]; } catch (Throwable $e) { /* segue sem PDF */ } } } /* ---------- Log CSV (simples) ---------- */ @touch(LOG_CSV); $fp = @fopen(LOG_CSV, 'a'); if ($fp) { @fputcsv($fp, [ date('Y-m-d H:i:s'), $contato_nome, $contato_email, $contato_tel, $cnpj_pagador, "{$cep_origem}->{$cep_destino}", $tipo_mercadoria, $qtd_volumes, $peso_real ], ';'); @fclose($fp); } /* ---------- Envio ---------- */ $sent = false; if (MAIL_TRANSPORT === 'smtp') { $autoload = __DIR__ . '/vendor/autoload.php'; if (file_exists($autoload)) { require_once $autoload; try { $mail = new PHPMailer\PHPMailer\PHPMailer(true); $mail->isSMTP(); $mail->Host = SMTP_HOST; $mail->Port = SMTP_PORT; $mail->SMTPAuth = true; $mail->Username = SMTP_USER; $mail->Password = SMTP_PASS; if (SMTP_SECURE) $mail->SMTPSecure = SMTP_SECURE; $mail->CharSet = 'UTF-8'; $mail->setFrom(FROM_EMAIL, 'Transportadora Jacareí'); $mail->addAddress(TO_EMAIL); if (!empty(BCC_EMAIL)) $mail->addBCC(BCC_EMAIL); $mail->addReplyTo($contato_email, $contato_nome); $mail->Subject = $subject; $mail->Body = $bodyText; if ($pdfAttachment) $mail->addStringAttachment($pdfAttachment['data'], $pdfAttachment['name'], 'base64', $pdfAttachment['mime']); foreach($filesToAttach as $f){ $mail->addStringAttachment($f['data'], $f['name'], 'base64', $f['mime']); } $sent = $mail->send(); } catch (Throwable $e) { // fallback abaixo } } } if (!$sent) { // Fallback: mail() multipart $boundary = "==Multipart_Boundary_x".md5(uniqid(time()))."x"; $headers = []; $headers[] = "From: Transportadora Jacareí <".FROM_EMAIL.">"; if (BCC_EMAIL) $headers[] = "Bcc: ".BCC_EMAIL; $headers[] = "Reply-To: $contato_nome <$contato_email>"; $headers[] = "MIME-Version: 1.0"; $headers[] = "Content-Type: multipart/mixed; boundary=\"$boundary\""; $message = "--$boundary\r\n"; $message .= "Content-Type: text/plain; charset=\"utf-8\"\r\n"; $message .= "Content-Transfer-Encoding: 8bit\r\n\r\n"; $message .= $bodyText . "\r\n"; if ($pdfAttachment){ $message .= "--$boundary\r\n"; $message .= "Content-Type: ".$pdfAttachment['mime']."; name=\"".$pdfAttachment['name']."\"\r\n"; $message .= "Content-Transfer-Encoding: base64\r\n"; $message .= "Content-Disposition: attachment; filename=\"".$pdfAttachment['name']."\"\r\n\r\n"; $message .= chunk_split(base64_encode($pdfAttachment['data'])) . "\r\n"; } foreach($filesToAttach as $f){ $message .= "--$boundary\r\n"; $message .= "Content-Type: ".$f['mime']."; name=\"".addslashes($f['name'])."\"\r\n"; $message .= "Content-Transfer-Encoding: base64\r\n"; $message .= "Content-Disposition: attachment; filename=\"".addslashes($f['name'])."\"\r\n\r\n"; $message .= chunk_split(base64_encode($f['data'])) . "\r\n"; } $message .= "--$boundary--"; $sent = @mail(TO_EMAIL, "=?UTF-8?B?".base64_encode($subject)."?=", $message, implode("\r\n", $headers)); } /* ---------- Resultado ---------- */ if ($sent) { header("Location: " . REDIRECT_SUCCESS); } else { fail("falha-envio-email"); }