) sont forcément à la racine. Sinon, on est servi depuis un sous-dossier (WAMP : /FWS-Website). */ if (preg_match('~/((?:inc|api|admin|cache)|p/(?:index|dl|paquets|equipe|contact|assets))(?:/|$)~', $dir, $m)) { $base = substr($dir, 0, (int) strrpos($dir, $m[0])); } else { $base = $dir; } return $base; } } if (!function_exists('fws_url')) { /** URL d'une route ou d'un asset local, préfixée par la base URL. */ function fws_url(string $path): string { if ($path === '' || preg_match('~^(?:[a-z][a-z0-9+.-]*:|//)~i', $path)) { return $path; /* absolu, mailto:, tel:, //… : inchangé */ } $base = fws_base_url(); if ($base !== '' && ($path === $base || str_starts_with($path, $base . '/'))) { return $path; /* déjà préfixé (idempotence) */ } return $base . '/' . ltrim($path, '/'); } } /* En CLI (scripts d'administration dans le conteneur), on affiche tout : * c'est interactif, l'opérateur doit voir les problèmes. */ if (PHP_SAPI === 'cli') { ini_set('display_errors', '1'); } /* ── Portabilité : polyfills mbstring ────────────────────────────────────── * L'extension mbstring est absente de certaines installations PHP de Windows * (et de quelques images Docker minimales). Le site doit tourner quand même : * on fournit des équivalents UTF-8 corrects pour les 4 fonctions mb_* du * projet. Si mbstring est présente (cas Linux standard), on n'y touche pas. */ if (!function_exists('mb_strlen')) { function fws_mb_chars(string $s): array { $c = preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY); return is_array($c) ? $c : ((str_split($s) === false) ? [] : str_split($s)); } function mb_strlen(string $s, ?string $enc = null): int { return count(fws_mb_chars($s)); } function mb_substr(string $s, int $start, ?int $len = null, ?string $enc = null): string { $c = fws_mb_chars($s); $n = count($c); if ($start < 0) { $start = max(0, $n + $start); } if ($len === null) { $len = $n; } elseif ($len < 0) { $len = max(0, $n - $start + $len); } return implode('', array_slice($c, $start, $len)); } function mb_check_encoding(string $s, ?string $enc = null): bool { return (bool) preg_match('//u', $s); } function mb_convert_encoding(string $s, string $to, ?string $from = null): string { if (function_exists('iconv') && strcasecmp($to, 'UTF-8') === 0) { $conv = @iconv((string) $from, 'UTF-8//TRANSLIT//IGNORE', $s); if (is_string($conv)) { return $conv; } } /* Dernier recours : on retire les octets qui cassent l'UTF-8. */ $clean = preg_replace('/[\x80-\xFF]+/', '?', $s); return is_string($clean) ? $clean : $s; } } /* Journal : api/bugs/data/ (déjà interdit au web par .htaccess + gitigné). */ $fwsErrorLogDir = dirname(__DIR__) . '/api/bugs/data'; if (!is_dir($fwsErrorLogDir)) { @mkdir($fwsErrorLogDir, 0770, true); } if (is_dir($fwsErrorLogDir) && is_writable($fwsErrorLogDir)) { ini_set('error_log', $fwsErrorLogDir . '/php-errors.log'); } unset($fwsErrorLogDir); /* ── 3. Réponses d'erreur propres ──────────────────────────────────────── */ if (!function_exists('fws_error_wants_json')) { /** * Le client attend-il du JSON ? * * Un navigateur (navigation réelle) demande explicitement du HTML * (« Accept: text/html, … ») → il recevra une page visuelle. * Tout le reste — curl (Accept générique), scripts, apps, appels fetch() * ou clients qui annoncent du JSON — reçoit du JSON. */ function fws_error_wants_json(): bool { $accept = strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')); if (str_contains($accept, 'text/html')) { return false; /* navigateur → page visuelle */ } return true; /* curl, scripts, API clients → JSON */ } /** * Réponse d'erreur finale : JSON ou page HTML minimaliste, sans aucun * détail technique. Ne fait rien si les en-têtes sont déjà partis. */ function fws_error_render(int $status, string $message): void { if (headers_sent()) { return; /* trop tard pour propre : on referme silencieusement */ } http_response_code($status); if (fws_error_wants_json()) { header('Content-Type: application/json; charset=utf-8'); header('X-Content-Type-Options: nosniff'); header('Cache-Control: no-store'); echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE); return; } header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: no-store'); $msg = htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); echo << Erreur | FWS Linux

Oups…

{$msg}

Retour à l'accueil
HTML; } } if (!function_exists('fws_error_install')) { /** Pose les handlers (une seule fois, jamais en CLI). */ function fws_error_install(): void { static $installed = false; if ($installed || PHP_SAPI === 'cli') { return; } $installed = true; /* Exception non interceptée → 500 propre. */ set_exception_handler(static function (Throwable $e): void { error_log('[fws] exception non interceptée : ' . $e->getMessage() . ' — ' . $e->getFile() . ':' . $e->getLine()); fws_error_render(500, 'Une erreur inattendue est survenue. Merci de réessayer plus tard.'); }); /* Erreur fatale (mémoire, parse, include manquant…) → 500 propre. * NB : les warnings/notices restent simplement journalisés — on ne * les transforme pas en exceptions pour ne pas casser les pages. */ register_shutdown_function(static function (): void { $e = error_get_last(); if ($e === null) { return; } $fatals = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; if (!in_array((int) $e['type'], $fatals, true)) { return; } error_log('[fws] erreur fatale : ' . $e['message'] . ' — ' . $e['file'] . ':' . $e['line']); fws_error_render(500, 'Une erreur inattendue est survenue. Merci de réessayer plus tard.'); }); } } fws_error_install();