$maxFileBytes) { header('Location: /account/profile/?error=' . urlencode('Plik musi miec od 1B do 3MB.')); exit(); } $allowedMime = [ 'image/jpeg' => true, 'image/png' => true, 'image/gif' => true, 'image/webp' => true, ]; $detectedMime = null; if (function_exists('finfo_open')) { $fi = finfo_open(FILEINFO_MIME_TYPE); if ($fi) { $detectedMime = finfo_file($fi, $tmpName) ?: null; finfo_close($fi); } } $fileMime = (string)($detectedMime ?: ($upload['type'] ?? '')); if (!isset($allowedMime[$fileMime])) { header('Location: /account/profile/?error=' . urlencode('Dozwolone sa tylko obrazy JPG, PNG, GIF, WEBP.')); exit(); } $originalName = (string)($upload['name'] ?? 'avatar'); $oldAvatarFile = og_get_user_avatar_file($pdo, $userId); $newAvatarFile = ''; try { $result = get_file_api_client()->upload('user_files/profile', $tmpName, $originalName, $fileMime); $newAvatarFile = trim((string)($result['stored_name'] ?? '')); if ($newAvatarFile === '') { throw new RuntimeException('Serwis plikow nie zwrocil nazwy pliku.'); } $stmt = $pdo->prepare('UPDATE users SET profile_avatar_file = ? WHERE id = ?'); $stmt->execute([$newAvatarFile, $userId]); $_SESSION['profile_avatar_file'] = $newAvatarFile; if (is_string($oldAvatarFile) && $oldAvatarFile !== '' && $oldAvatarFile !== $newAvatarFile) { try { get_file_api_client()->deleteFile('user_files/profile', $oldAvatarFile); } catch (Throwable $ignored) { } } header('Location: /account/profile/?success=avatar_updated'); exit(); } catch (Throwable $e) { // Jeśli upload się udał, ale dalszy zapis nie, usuń nowy plik żeby nie zostawiać osieroconych avatarów. if ($newAvatarFile !== '') { try { get_file_api_client()->deleteFile('user_files/profile', $newAvatarFile); } catch (Throwable $ignored) { } } header('Location: /account/profile/?error=' . urlencode('Nie udalo sie przeslac zdjecia profilowego.')); exit(); }