Jasne, przeróbmy plik file_explorer.php, dodając przyciski do kopiowania całego kodu aplikacji lub pobierania go jako plik tekstowy, z wykluczeniem samego eksploratora.
Zmiany obejmą:
- Dodanie nowej funkcji PHP, która będzie rekurencyjnie przechodzić przez pliki i katalogi (z uwzględnieniem konfiguracji wykluczeń) i zwracać połączony string z zawartością plików, poprzedzonych ścieżką pliku.
- Dodanie w sekcji PHP obsługi nowego żądania AJAX, które wywoła tę nową funkcję i zwróci połączony kod jako tekst.
- Dodanie dwóch nowych przycisków w HTML (Kopiuj cały kod, Pobierz cały kod).
- Dodanie w JavaScript obsługi kliknięć tych przycisków, wysyłania żądania AJAX do nowego endpointu i obsługi odpowiedzi (kopiowanie do schowka lub tworzenie pliku do pobrania).
Pamiętaj, że pobieranie i wyświetlanie kodu plików może mieć implikacje bezpieczeństwa, jeśli ten skrypt będzie dostępny publicznie. Upewnij się, że skrypt jest chroniony (np. hasłem, dostępem tylko z określonych adresów IP, lub umieszczony w katalogu, do którego dostęp mają tylko zaufani użytkownicy).
Oto zmodyfikowany kod:
<?php
// file_explorer.php - umieść ten plik w katalogu głównym swojej aplikacji
// Zmodyfikowany o możliwość kopiowania/pobierania całego kodu aplikacji
// Konfiguracja
$baseDir = './'; // Katalog główny aplikacji
$excludeDirs = ['.git', 'node_modules', 'vendor']; // Katalogi do pominięcia
$allowedExtensions = ['js', 'php', 'css', 'html', 'htm']; // Obsługiwane rozszerzenia plików
$explorerFileName = basename(__FILE__); // Nazwa tego pliku eksploratora
// Funkcja do skanowania katalogów rekurencyjnie dla widoku drzewa (z htmlspecialchars)
function scanDirectory($dir, $basePath = '') {
global $excludeDirs, $allowedExtensions, $explorerFileName;
$result = [];
$files = @scandir($dir); // Użyj @, aby stłumić błędy czytania katalogu
if ($files === false) {
// Można dodać logowanie błędu, jeśli scandir zawiedzie
return [];
}
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
// Użyj realpath, aby upewnić się, że ścieżka jest poprawna i rozwiązać linki symboliczne
$realPath = realpath($path);
if ($realPath === false) continue; // Pomiń, jeśli realpath się nie powiedzie
$relativePath = ltrim($basePath . '/' . $file, './'); // Usuń wiodące './'
if (is_dir($realPath)) {
// Pomijanie wykluczonych katalogów
if (in_array($file, $excludeDirs)) continue;
// Dodajemy katalog do wyniku, nawet jeśli jest pusty lub zawiera tylko wykluczone pliki/katalogi
// Ale skanujemy dalej, aby znaleźć dozwolone pliki w podkatalogach
$contents = scanDirectory($realPath, $relativePath);
// Opcjonalnie: Pomiń pusty katalog, jeśli chcesz
// if (empty($contents)) continue;
$result[$file] = [
'type' => 'directory',
'path' => $relativePath,
'contents' => $contents
];
} else {
// Sprawdzanie rozszerzenia pliku
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array(strtolower($extension), array_map('strtolower', $allowedExtensions))) continue; // Porównanie bez uwzględniania wielkości liter
// Pomijanie samego pliku eksploratora w drzewie, jeśli chcesz (domyślnie jest dozwolony)
// if ($file === $explorerFileName) continue;
$result[$file] = [
'type' => 'file',
'path' => $relativePath,
'extension' => $extension,
'size' => @filesize($realPath), // Użyj @, aby stłumić błędy filesize
'content' => htmlspecialchars(@file_get_contents($realPath)) // Użyj @, aby stłumić błędy file_get_contents
];
}
}
return $result;
}
// Nowa funkcja do budowania połączonego stringa kodu (bez htmlspecialchars)
function buildCombinedCodeString($dir, $basePath = '') {
global $excludeDirs, $allowedExtensions, $explorerFileName;
$output = '';
$files = @scandir($dir);
if ($files === false) {
// Można dodać logowanie błędu
return '';
}
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
$realPath = realpath($path);
if ($realPath === false) continue;
$relativePath = ltrim($basePath . '/' . $file, './');
if (is_dir($realPath)) {
// Pomijanie wykluczonych katalogów
if (in_array($file, $excludeDirs)) continue;
// Rekurencyjne wywołanie dla podkatalogów
$output .= buildCombinedCodeString($realPath, $relativePath);
} else {
// Sprawdzanie rozszerzenia pliku
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array(strtolower($extension), array_map('strtolower', $allowedExtensions))) continue;
// *** Kluczowe: Pomijanie samego pliku eksploratora ***
if ($file === $explorerFileName) continue;
// Pobieranie surowej zawartości pliku
$content = @file_get_contents($realPath);
if ($content === false) {
// Można dodać logowanie błędu odczytu pliku
continue; // Pomiń plik, którego nie można odczytać
}
// Dodanie nagłówka i zawartości do stringa
$output .= "// --- Plik: " . $relativePath . " ---\n";
$output .= $content;
$output .= "\n\n"; // Dodaj dwie nowe linie między plikami dla lepszej czytelności
}
}
return $output;
}
// Obsługa żądań AJAX
if (isset($_GET['ajax'])) {
// Żądanie struktury drzewa plików (dla lewego panelu)
header('Content-Type: application/json');
echo json_encode(scanDirectory($baseDir));
exit;
} elseif (isset($_GET['action']) && $_GET['action'] === 'get_all_code') {
// Nowe żądanie pobrania całego kodu aplikacji
header('Content-Type: text/plain'); // Zwracamy czysty tekst
header('Content-Disposition: inline; filename="application_code.txt"'); // Sugerowana nazwa pliku przy pobieraniu
echo buildCombinedCodeString($baseDir);
exit;
}
// Generowanie HTML dla interfejsu użytkownika
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Eksplorator kodu aplikacji</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
color: #333;
}
.container {
display: flex;
height: 100vh;
}
.file-tree {
width: 300px;
background-color: #2c3e50;
color: #ecf0f1;
overflow-y: auto;
padding: 15px;
box-sizing: border-box;
flex-shrink: 0; /* Zapobiega zmniejszaniu szerokości */
}
.content-view {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.file-tree-header {
font-size: 1.2em;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid #546e7a;
}
.file-tree-header h2 {
margin: 0;
font-size: 1.2em;
font-weight: normal;
}
.file-header {
background-color: #34495e;
color: #ecf0f1;
padding: 10px 15px;
font-size: 1.2em;
border-bottom: 1px solid #546e7a;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 0; /* Zapobiega zmniejszaniu wysokości */
}
.file-content {
flex: 1;
overflow: auto;
padding: 15px;
background-color: #fff;
position: relative; /* Potrzebne dla pozycjonowania copy-btn */
}
pre {
margin: 0;
white-space: pre-wrap; /* Zawijanie linii */
word-wrap: break-word; /* Zawijanie długich słów */
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
line-height: 1.5;
}
.folder, .file {
margin: 3px 0;
cursor: pointer;
padding: 5px;
border-radius: 3px;
transition: background-color 0.2s;
user-select: none; /* Zapobiega zaznaczaniu tekstu podczas klikania */
word-wrap: break-word; /* Zawijanie długich nazw */
}
.folder:hover, .file:hover {
background-color: #34495e;
}
.folder-content {
margin-left: 15px;
border-left: 1px dashed #546e7a; /* Linia wizualna dla struktury */
padding-left: 5px;
display: none;
}
.folder.open > .folder-content {
display: block;
}
/* Ikony - można użyć ikon z font-awesome lub wstawić unicode */
.folder::before {
content: "▶ "; /* Strzałka w prawo */
display: inline-block;
margin-right: 5px;
transition: transform 0.1s ease-in-out;
}
.folder.open > .folder-name::before {
content: "▼ "; /* Strzałka w dół */
}
.folder.open > .folder-name > .folder-name-text::before {
content: "📂 "; /* Ikona otwartego folderu */
}
.folder-name-text::before {
content: "📁 "; /* Ikona zamkniętego folderu */
}
.file.js::before { content: "📄 "; color: #f1c40f; margin-right: 5px;}
.file.php::before { content: "📄 "; color: #9b59b6; margin-right: 5px;}
.file.css::before { content: "📄 "; color: #3498db; margin-right: 5px;}
.file.html::before, .file.htm::before { content: "📄 "; color: #e74c3c; margin-right: 5px;}
.selected {
background-color: #3498db !important;
color: white;
}
.code-content {
tab-size: 4;
}
.copy-btn {
position: absolute;
top: 10px;
right: 15px; /* Dopasuj prawy margines */
background-color: #3498db;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
font-size: 0.9em;
z-index: 1; /* Upewnij się, że jest nad pre */
}
.copy-btn:hover {
background-color: #2980b9;
}
.copy-btn:active {
background-color: #2171a5;
}
.file-info {
font-size: 0.85em;
color: #7f8c8d;
margin-top: 5px;
margin-bottom: 10px; /* Dodaj margines poniżej informacji */
}
.all-code-buttons {
margin-top: 15px;
padding-top: 10px;
border-top: 1px solid #546e7a;
text-align: center;
}
.all-code-buttons button {
background-color: #e67e22;
color: white;
border: none;
padding: 8px 15px;
border-radius: 3px;
cursor: pointer;
margin: 0 5px;
font-size: 0.9em;
transition: background-color 0.2s;
}
.all-code-buttons button:hover {
background-color: #d35400;
}
.all-code-buttons button:active {
background-color: #bf4a00;
}
.loading-spinner {
display: none;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 2s linear infinite;
margin: 10px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.feedback-message {
text-align: center;
margin-top: 10px;
font-size: 0.9em;
color: #3498db;
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="file-tree">
<div class="file-tree-header">
<h2>Struktura plików</h2>
</div>
<div class="all-code-buttons">
<button id="copyAllBtn">Kopiuj cały kod</button>
<button id="downloadAllBtn">Pobierz cały kod (.txt)</button>
<div class="loading-spinner" id="allCodeSpinner"></div>
<div class="feedback-message" id="allCodeFeedback"></div>
</div>
<div id="fileTree"></div>
</div>
<div class="content-view">
<div class="file-header" id="fileHeader">Wybierz plik, aby zobaczyć jego zawartość</div>
<div class="file-content">
<button id="copyFileBtn" class="copy-btn" style="display: none;">Kopiuj</button>
<div id="fileInfo" class="file-info"></div>
<pre id="fileContent" class="code-content"></pre>
</div>
</div>
</div>
<script>
// Helper function to toggle folder open/close state
function toggleFolder(folderElement) {
folderElement.classList.toggle('open');
}
// Funkcja do renderowania drzewa plików
function renderFileTree(data, container) {
// Posortuj katalogi przed plikami, a następnie alfabetycznie
const sortedEntries = Object.entries(data).sort(([nameA, infoA], [nameB, infoB]) => {
if (infoA.type === 'directory' && infoB.type !== 'directory') return -1;
if (infoA.type !== 'directory' && infoB.type === 'directory') return 1;
return nameA.localeCompare(nameB);
});
for (const [name, info] of sortedEntries) {
if (info.type === 'directory') {
const folderElement = document.createElement('div');
folderElement.className = 'folder';
const folderNameElement = document.createElement('div');
folderNameElement.className = 'folder-name';
const folderNameTextElement = document.createElement('span'); // Dodatkowe opakowanie dla tekstu nazwy
folderNameTextElement.className = 'folder-name-text';
folderNameTextElement.textContent = name;
folderNameElement.appendChild(folderNameTextElement); // Dodaj tekst nazwy do div.folder-name
folderElement.appendChild(folderNameElement); // Dodaj div.folder-name do div.folder
folderNameElement.addEventListener('click', function() {
toggleFolder(folderElement);
});
const folderContentElement = document.createElement('div');
folderContentElement.className = 'folder-content';
renderFileTree(info.contents, folderContentElement);
folderElement.appendChild(folderContentElement);
container.appendChild(folderElement);
} else {
const fileElement = document.createElement('div');
fileElement.className = `file ${info.extension}`;
fileElement.textContent = name;
fileElement.dataset.path = info.path;
fileElement.dataset.extension = info.extension;
// Nie przechowuj całej zawartości w data- atrybucie, bo może być duża
// fileElement.dataset.content = info.content;
fileElement.dataset.size = info.size;
// Przechowaj zawartość w pamięci JS, jeśli jest potrzebna,
// lub pobierz ją ponownie, jeśli jest bardzo duża.
// W tym przypadku, ponieważ PHP już przesłał treść w JSON,
// możemy ją przypisać do elementu dla łatwego dostępu
// przy kliknięciu, mimo potencjalnych problemów z bardzo dużymi plikami.
fileElement._fileContent = info.content; // Użyj niestandardowej właściwości
fileElement.addEventListener('click', function() {
// Usunięcie poprzedniego zaznaczenia
document.querySelectorAll('.file.selected').forEach(el => {
el.classList.remove('selected');
});
// Dodanie nowego zaznaczenia
fileElement.classList.add('selected');
// Aktualizacja nagłówka i zawartości
document.getElementById('fileHeader').textContent = info.path; // Ścieżka jest już bez wiodącego ./
document.getElementById('fileContent').textContent = fileElement._fileContent; // Użyj zapisanej zawartości
document.getElementById('fileInfo').textContent = `Typ: ${info.extension.toUpperCase()} | Rozmiar: ${formatFileSize(info.size)}`;
document.getElementById('copyFileBtn').style.display = 'block';
});
container.appendChild(fileElement);
}
}
}
// Formatowanie rozmiaru pliku
function formatFileSize(bytes) {
if (bytes === undefined || bytes === null) return 'N/A';
if (bytes < 1024) return bytes + ' B';
else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
else return (bytes / 1048576).toFixed(2) + ' MB';
}
// Kopiowanie zawartości POJEDYNCZEGO pliku
document.getElementById('copyFileBtn').addEventListener('click', function() {
const content = document.getElementById('fileContent').textContent;
navigator.clipboard.writeText(content)
.then(() => {
const btn = document.getElementById('copyFileBtn');
const originalText = btn.textContent;
btn.textContent = 'Skopiowano!';
setTimeout(() => {
btn.textContent = originalText;
}, 2000);
})
.catch(err => {
console.error('Błąd podczas kopiowania pliku:', err);
const btn = document.getElementById('copyFileBtn');
btn.textContent = 'Błąd!'; // Prosta informacja o błędzie
});
});
// Kopiowanie CAŁEGO KODU APLIKACJI
document.getElementById('copyAllBtn').addEventListener('click', async function() {
const btn = this;
const spinner = document.getElementById('allCodeSpinner');
const feedback = document.getElementById('allCodeFeedback');
btn.disabled = true;
btn.textContent = 'Przygotowuję...';
spinner.style.display = 'block';
feedback.style.display = 'none';
try {
const response = await fetch('?action=get_all_code');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const combinedCode = await response.text();
await navigator.clipboard.writeText(combinedCode);
btn.textContent = 'Skopiowano!';
feedback.textContent = 'Cały kod aplikacji skopiowany do schowka.';
feedback.style.color = '#27ae60'; // Zielony kolor sukcesu
feedback.style.display = 'block';
setTimeout(() => {
btn.textContent = 'Kopiuj cały kod';
btn.disabled = false;
spinner.style.display = 'none';
feedback.style.display = 'none';
}, 3000);
} catch (error) {
console.error('Błąd podczas kopiowania całego kodu:', error);
btn.textContent = 'Błąd!';
feedback.textContent = 'Nie udało się skopiować kodu.';
feedback.style.color = '#e74c3c'; // Czerwony kolor błędu
feedback.style.display = 'block';
setTimeout(() => {
btn.textContent = 'Kopiuj cały kod';
btn.disabled = false;
spinner.style.display = 'none';
feedback.style.display = 'none';
}, 5000);
} finally {
// spinner.style.display = 'none'; // Usuń spinner w każdym przypadku, jeśli timeout nie zadziałał
}
});
// Pobieranie CAŁEGO KODU APLIKACJI jako plik .txt
document.getElementById('downloadAllBtn').addEventListener('click', async function() {
const btn = this;
const spinner = document.getElementById('allCodeSpinner');
const feedback = document.getElementById('allCodeFeedback');
btn.disabled = true;
btn.textContent = 'Przygotowuję...';
spinner.style.display = 'block';
feedback.style.display = 'none';
try {
const response = await fetch('?action=get_all_code');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const combinedCode = await response.text();
const blob = new Blob([combinedCode], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
// Ustaw nazwę pliku, np. application_code_YYYY-MM-DD.txt
const date = new Date().toISOString().slice(0, 10);
a.download = `application_code_${date}.txt`;
document.body.appendChild(a); // Wymagane dla Firefox
a.click();
document.body.removeChild(a); // Usuń element linku
URL.revokeObjectURL(url); // Zwolnij zasoby
btn.textContent = 'Pobrano!';
feedback.textContent = 'Plik z kodem został pobrany.';
feedback.style.color = '#27ae60'; // Zielony sukces
feedback.style.display = 'block';
setTimeout(() => {
btn.textContent = 'Pobierz cały kod (.txt)';
btn.disabled = false;
spinner.style.display = 'none';
feedback.style.display = 'none';
}, 3000);
} catch (error) {
console.error('Błąd podczas pobierania całego kodu:', error);
btn.textContent = 'Błąd!';
feedback.textContent = 'Nie udało się pobrać kodu.';
feedback.style.color = '#e74c3c'; // Czerwony błąd
feedback.style.display = 'block';
setTimeout(() => {
btn.textContent = 'Pobierz cały kod (.txt)';
btn.disabled = false;
spinner.style.display = 'none';
feedback.style.display = 'none';
}, 5000);
} finally {
// spinner.style.display = 'none'; // Usuń spinner
}
});
// Pobieranie danych i renderowanie drzewa plików po załadowaniu strony
fetch('?ajax=1')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
const fileTreeContainer = document.getElementById('fileTree');
renderFileTree(data, fileTreeContainer);
})
.catch(error => {
console.error('Błąd pobierania danych drzewa plików:', error);
document.getElementById('fileTree').innerHTML = '<div style="color: red; padding: 10px;">Błąd pobierania struktury plików:<br>' + error.message + '</div>';
});
</script>
</body>
</html>