File manager - Edit - /var/www/html/portal/app/Http/Controllers/Controller.php
Back
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; use Illuminate\Support\Facades\File; use App\Models\Endereco; use App\Models\Accounts\Chamados\Mensagem; use Carbon\Carbon; use App\Models\User; use Illuminate\Http\RedirectResponse; use App\Helpers\FileUploadHelper; class Controller extends BaseController { use AuthorizesRequests, ValidatesRequests; protected function __ocupacoes() { $path = public_path('pmar/generics/apis/ocupacoes.json'); if (!File::exists($path)) { return response()->json(['error' => 'Arquivo não encontrado'], 404); } $json = File::get($path); $data = json_decode($json, true); //return response()->json($data); return $data; } protected function __paises() { $path = public_path('pmar/generics/apis/paises.json'); if (!File::exists($path)) { return response()->json(['error' => 'Arquivo não encontrado'], 404); } $json = File::get($path); $data = json_decode($json, true); //return response()->json($data); return $data; } public function recaptcha($recaptcha, $secret = null) { if (!config('recaptcha.enabled', true)) { return true; } $data = array( "secret" => $secret ?? config('recaptcha.secret'), "response" => $recaptcha ); $url = "https://www.google.com/recaptcha/api/siteverify"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($curl)); curl_close($curl); if (isset($result->success) && $result->success) { return true; } else { $curl = curl_init(); curl_setopt($curl, CURLOPT_PROXY, '1.1.1.1'); curl_setopt($curl, CURLOPT_PROXYPORT, '3128'); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = json_decode(curl_exec($curl)); curl_close($curl); if (isset($result->success) && $result->success) { return true; } else { return false; } } } function removeHtmlAttributesRegex($html) { // Remover completamente as tags <style> e <script> com seus conteúdos $html = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $html); $html = preg_replace('/<style\b[^>]*>.*?<\/style>/is', '', $html); // Usar preg_replace_callback para processar as tags restantes return preg_replace_callback( '/<(\w+)([^>]*)>/', function ($matches) { $tag = $matches[1]; // Nome da tag (ex: div, a, etc.) $attributes = $matches[2]; // Atributos da tag if ($tag === 'a') { // Preserve o atributo href nas tags <a> if (preg_match('/\shref=["\'].*?["\']/', $attributes, $hrefMatch)) { return "<$tag{$hrefMatch[0]}>"; } } // Remove todos os atributos para outras tags return "<$tag>"; }, $html ); } protected function getArrayFieldsBulleins() { return [ 'id', 'created_at', 'updated_at', 'publicationDate', 'month', 'number', 'title', 'url', 'fileSizeKB', 'fileName', 'extraordinaryEdition', 'indexado', 'status' ]; } /** * Format a date to Portuguese (pt-BR). * * @param string $date The date to be formatted. * @return string The formatted date. */ public function formatDateToPortuguese($date) { setlocale(LC_TIME, 'pt_BR.UTF-8'); Carbon::setLocale('pt_BR'); return Carbon::parse($date)->translatedFormat('d \d\e F \d\e Y'); } protected function clearCpfCnpj($value) { $value = str_replace(".", "", $value); $value = str_replace("-", "", $value); $value = str_replace("/", "", $value); return $value; } public function formatCnpjCpf($value) { $value = str_replace(".", "", $value); $value = str_replace("-", "", $value); $value = str_replace("/", "", $value); $CPF_LENGTH = 11; if (strlen($value) >= 11) { $cnpj_cpf = preg_replace("/\D/", '', $value); if (strlen($cnpj_cpf) === $CPF_LENGTH) { return preg_replace("/(\d{3})(\d{3})(\d{3})(\d{2})/", "\$1.\$2.\$3-\$4", $cnpj_cpf); } return preg_replace("/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/", "\$1.\$2.\$3/\$4-\$5", $cnpj_cpf); } else { return $value; } } public function getRandMatricula() { $m = null; do { $m = str_pad(mt_rand(1, 9), 1, '0') . str_pad(mt_rand(0, 999999999999999999), 19, '0', STR_PAD_LEFT); } while (User::where('matriculation', $m)->exists()); return $m; } public function clearCPF($cpf) { return str_replace(['.', '-'], '', $cpf); } public function handleFileUpload($request, string $inputName, string $folder, string $default = "pmar/assets/img/icons/neutro.png") { if ($request->hasFile($inputName) && $request->file($inputName)->isValid()) { $file = $request->file($inputName); $path = FileUploadHelper::processSafeImageUpload($file, $folder); if ($path) { return $path; } } return $default; } public function handleFileDestroyArquivo($path, string $default = "pmar/assets/img/icons/neutro.png"): bool { $ds = DIRECTORY_SEPARATOR; if ($path != $default) { $search = "pmar{$ds}assets{$ds}img"; $file_exist = storage_path() . str_replace($search, "{$ds}app{$ds}public", $path); if (@file_exists($file_exist)) { @unlink($file_exist); } } return true; } public function handleFileUploadLoop($file, string $inputName, string $folder, string $default = "pmar/assets/img/icons/neutro.png") { if ($file != null && $file->isValid()) { $path = FileUploadHelper::processSafeImageUpload($file, $folder); if ($path) { return $path; } // Validação do FileUploadHelper rejeitou o arquivo (extensão/MIME/magic bytes) return null; } return $default; } public function getPathImageUser($request, ?User $user = null) { if (isset($user->id)) { $path = $user->photo; } else { $path = "pmar/assets/img/profile.jpg"; } if ($request->hasFile('photo') && $request->file('photo')->isValid()) { $file = $request->file('photo'); $uploadedPath = FileUploadHelper::processSafeImageUpload($file, 'contas'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } public function getPathImageUserField($request, string $inputName, ?User $user = null) { $ds = DIRECTORY_SEPARATOR; if ($user && isset($user->id) && $user->photo) { $path = $user->photo; } else { $path = "pmar{$ds}assets{$ds}img{$ds}profile.jpg"; // padrão } if ($request->hasFile($inputName) && $request->file($inputName)->isValid()) { $file = $request->file($inputName); $uploadedPath = FileUploadHelper::processSafeImageUpload($file, 'contas'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } public function getPathImageComprovanteResidencia($request, ?Endereco $endereco = null) { $ds = DIRECTORY_SEPARATOR; if ($request->hasFile('comprovante') && $request->file('comprovante')->isValid()) { $file = $request->file('comprovante'); $uploadedPath = FileUploadHelper::processSafeImageUpload($file, 'comprovantes'); if ($uploadedPath) { return $uploadedPath; } } if (isset($endereco) && $endereco->comprovante) { return $endereco->comprovante; } return "pmar{$ds}assets{$ds}img{$ds}comprovante-residencia-default.jpg"; } public function getProofOfResidence($request, $fileRequestName = "comprovante", ?Endereco $endereco = null) { $ds = DIRECTORY_SEPARATOR; if ($endereco && isset($endereco->id) && $endereco->comprovante) { $path = $endereco->comprovante; } else { $path = "pmar{$ds}assets{$ds}img{$ds}comprovante-residencia-default.jpg"; } if ($request->hasFile($fileRequestName) && $request->file($fileRequestName)->isValid()) { $file = $request->file($fileRequestName); $uploadedPath = FileUploadHelper::processSafeImageUpload($file, 'comprovantes'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } public function getPathImageFibromialgiaLaudos($file) { $path = "pmar/assets/img/icons/usuario.png"; if ($file->isValid()) { $uploadedPath = FileUploadHelper::processSafeDocumentUpload($file, 'fibromialgia_laudos'); if ($uploadedPath) { $ds = DIRECTORY_SEPARATOR; // Ajusta o caminho para files em vez de img $path = str_replace("pmar{$ds}assets{$ds}img", "pmar{$ds}assets{$ds}files", $uploadedPath); } } return $path; } public function getPathImageFibromialgiaArquivo($request, $nameCollumn) { $path = "pmar/assets/img/icons/neuto.png"; if ($request->hasFile($nameCollumn) && $request->file($nameCollumn)->isValid()) { $file = $request->file($nameCollumn); $uploadedPath = FileUploadHelper::processSafeGeneralUpload($file, 'arquivos'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } public function getPathImageFibromialgiaArquivoUpdate($request, $path, $nameCollumn) { if ($request->hasFile($nameCollumn) && $request->file($nameCollumn)->isValid()) { $file = $request->file($nameCollumn); $uploadedPath = FileUploadHelper::processSafeGeneralUpload($file, 'arquivos'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } public function getPathImageMusicoArquivoUpdate($request, $path, $nameCollumn) { if ($request->hasFile($nameCollumn) && $request->file($nameCollumn)->isValid()) { $file = $request->file($nameCollumn); $uploadedPath = FileUploadHelper::processSafeGeneralUpload($file, 'arquivos'); if ($uploadedPath) { $path = $uploadedPath; } } return $path; } /** * Valida um CPF conforme regras oficiais da Receita Federal. * * @param string $cpf CPF com ou sem máscara (ex: "123.456.789-09" ou "12345678909"). * @return bool Retorna true se o CPF for válido, false caso contrário. */ public static function isValidCPF(string $cpf): bool { // Remove qualquer caractere não numérico $cpf = preg_replace('/\D/', '', $cpf); // Verifica se o CPF possui 11 dígitos if (strlen($cpf) !== 11) { return false; } // Elimina CPFs com todos os dígitos iguais (ex: 11111111111) if (preg_match('/^(\d)\1{10}$/', $cpf)) { return false; } // Valida os dois dígitos verificadores for ($t = 9; $t < 11; $t++) { $soma = 0; for ($i = 0; $i < $t; $i++) { $soma += $cpf[$i] * (($t + 1) - $i); } $digito = ((10 * $soma) % 11) % 10; if ($cpf[$t] != $digito) { return false; } } return true; } public function validaCPF($cpf) { // Extrai somente os números $cpf = preg_replace('/[^0-9]/is', '', $cpf); // Verifica se foi informado todos os digitos corretamente if (strlen($cpf) != 11) { return false; } // Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11 if (preg_match('/(\d)\1{10}/', $cpf)) { return false; } // Faz o calculo para validar o CPF for ($t = 9; $t < 11; $t++) { for ($d = 0, $c = 0; $c < $t; $c++) { $d += $cpf[$c] * (($t + 1) - $c); } $d = ((10 * $d) % 11) % 10; if ($cpf[$c] != $d) { return false; } } return true; } public function validaCNPJ($cnpj) { // Extrai somente os números $cnpj = preg_replace('/[^0-9]/', '', $cnpj); // Verifica se possui 14 dígitos if (strlen($cnpj) != 14) { return false; } // Verifica se foi informada uma sequência de dígitos repetidos if (preg_match('/(\d)\1{13}/', $cnpj)) { return false; } // Lista de multiplicadores para os cálculos $multiplicadores1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; $multiplicadores2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; // Calcula o primeiro dígito verificador for ($i = 0, $soma = 0; $i < 12; $i++) { $soma += $cnpj[$i] * $multiplicadores1[$i]; } $resto = $soma % 11; $digito1 = ($resto < 2) ? 0 : 11 - $resto; // Calcula o segundo dígito verificador for ($i = 0, $soma = 0; $i < 13; $i++) { $soma += $cnpj[$i] * $multiplicadores2[$i]; } $resto = $soma % 11; $digito2 = ($resto < 2) ? 0 : 11 - $resto; // Verifica se os dígitos calculados conferem com os informados return ($cnpj[12] == $digito1 && $cnpj[13] == $digito2); } public function formatarTelefone(string $numero): string { // remove tudo que não for número $numero = preg_replace('/\D/', '', $numero); // se for celular (11 dígitos) if (strlen($numero) === 11) { return sprintf('(%s) %s-%s', substr($numero, 0, 2), substr($numero, 2, 5), substr($numero, 7) ); } // se for fixo (10 dígitos) if (strlen($numero) === 10) { return sprintf('(%s) %s-%s', substr($numero, 0, 2), substr($numero, 2, 4), substr($numero, 6) ); } // se não bater, retorna o número cru return $numero; } public function formatarCep(string $cep): string { // Remove tudo que não for número $cep = preg_replace('/\D/', '', $cep); // Garante que tem 8 dígitos if (strlen($cep) === 8) { return substr($cep, 0, 5) . '-' . substr($cep, 5); } // Se não tiver o tamanho certo, retorna o valor original return $cep; } public function setPermissions($requestPermission) { if (empty($requestPermission)) { return 'GUEST'; } if ($requestPermission instanceof \UnitEnum) { return $requestPermission->name; } if (is_array($requestPermission)) { return implode(',', array_map(function ($permission) { return $permission instanceof \UnitEnum ? $permission->name : (string) $permission; }, $requestPermission)); } return (string) $requestPermission; } public function setPapers($requestPapers) { $papers = $requestPapers ?? ['EDIT']; if (is_array($papers)) { return implode(',', $papers); } return $papers; } function resolveFullname(string $fullname): array { $parts = array_filter(explode(' ', trim($fullname))); return [ 'firstName' => $parts ? array_shift($parts) : '', 'lastName' => $parts ? implode(' ', $parts) : '' ]; } function converterDataParaAmericano($data) { if (preg_match('/^(\d{2})\/(\d{2})\/(\d{2}|\d{4})$/', $data, $matches)) { $dia = $matches[1]; $mes = $matches[2]; $ano = $matches[3]; if (strlen($ano) == 2) { $ano = ($ano >= 50) ? "19$ano" : "20$ano"; } if (checkdate((int) $mes, (int) $dia, (int) $ano)) { return "$ano-$mes-$dia"; } else { return false; } } else { return false; } } protected function checkPermissao($permissao, $papel): ?RedirectResponse { $user = auth()->user(); if (!$user) { return redirect() ->route('admin.login') ->with('error', __('Permissão negada! Entre em contato com o administrador do sistema.')); } // Converte Enum para string se necessário $permissaoString = $permissao instanceof \UnitEnum ? $permissao->name : (string) $permissao; $detalhes = $user->getPermissaoDetalhes($permissaoString); if (!$detalhes || empty($detalhes[$papel]) || !$detalhes[$papel]) { return redirect() ->route('admin.contaAngra.index') ->with('error', __('Permissão negada! Entre em contato com o administrador do sistema.')); } return null; } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.11 |
proxy
|
phpinfo
|
Settings