error_reporting(E_ALL);
ini_set('display_errors', 1);
define('BASE_DIR', __DIR__);
define('DS', DIRECTORY_SEPARATOR);
if (!isset($_GET['path'])) {
$_GET['path'] = '';
}
$currentPath = realpath(BASE_DIR . DS . $_GET['path']);
if (strpos($currentPath, BASE_DIR) !== 0) {
$currentPath = BASE_DIR;
}
function formatSizeUnits($bytes) {
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
$action = $_POST['action'];
if ($action === 'upload') {
if (isset($_FILES['files'])) {
$uploadedCount = 0;
$errors = [];
foreach ($_FILES['files']['name'] as $key => $name) {
$tmp_name = $_FILES['files']['tmp_name'][$key];
$error = $_FILES['files']['error'][$key];
if ($error === UPLOAD_ERR_OK) {
$targetFile = $currentPath . DS . basename($name);
if (move_uploaded_file($tmp_name, $targetFile)) {
$uploadedCount++;
} else {
$errors[] = "Failed to upload " . htmlspecialchars($name);
}
} else {
$errors[] = "Upload error for " . htmlspecialchars($name) . ": Code " . $error;
}
}
if ($uploadedCount > 0) {
echo json_encode(['status' => 'success', 'message' => $uploadedCount . ' file(s) uploaded successfully.', 'errors' => $errors]);
} else {
echo json_encode(['status' => 'error', 'message' => 'No files uploaded.', 'errors' => $errors]);
}
} elseif (isset($_POST['url']) && !empty($_POST['url'])) {
$url = $_POST['url'];
$fileName = basename(parse_url($url, PHP_URL_PATH));
$targetFile = $currentPath . DS . $fileName;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300 && $data !== false) {
if (file_put_contents($targetFile, $data)) {
echo json_encode(['status' => 'success', 'message' => 'File uploaded from URL successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to save file from URL.']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to download from URL: HTTP Code ' . $httpCode . ' - ' . $error]);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'No file or URL provided.']);
}
exit;
} elseif ($action === 'delete') {
$target = $currentPath . DS . $_POST['item'];
if (file_exists($target)) {
if (is_dir($target)) {
$files = array_diff(scandir($target), array('.', '..'));
if (empty($files)) {
if (rmdir($target)) {
echo json_encode(['status' => 'success', 'message' => 'Folder deleted successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to delete folder.']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Folder is not empty.']);
}
} else {
if (unlink($target)) {
echo json_encode(['status' => 'success', 'message' => 'File deleted successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to delete file.']);
}
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Item not found.']);
}
exit;
} elseif ($action === 'rename') {
$oldName = $currentPath . DS . $_POST['old_name'];
$newName = $currentPath . DS . $_POST['new_name'];
if (file_exists($oldName)) {
if (rename($oldName, $newName)) {
echo json_encode(['status' => 'success', 'message' => 'Item renamed successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to rename item.']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Item not found.']);
}
exit;
} elseif ($action === 'create_file') {
$fileName = $currentPath . DS . $_POST['name'];
if (file_put_contents($fileName, '') !== false) {
echo json_encode(['status' => 'success', 'message' => 'File created successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to create file.']);
}
exit;
} elseif ($action === 'create_folder') {
$folderName = $currentPath . DS . $_POST['name'];
if (mkdir($folderName)) {
echo json_encode(['status' => 'success', 'message' => 'Folder created successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to create folder.']);
}
exit;
} elseif ($action === 'edit_file') {
$filePath = $currentPath . DS . $_POST['file_name'];
$content = $_POST['content'];
if (file_put_contents($filePath, $content) !== false) {
echo json_encode(['status' => 'success', 'message' => 'File content updated successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to update file content.']);
}
exit;
} elseif ($action === 'get_file_content') {
$filePath = $currentPath . DS . $_POST['file_name'];
if (file_exists($filePath) && is_file($filePath)) {
echo json_encode(['status' => 'success', 'content' => file_get_contents($filePath)]);
} else {
echo json_encode(['status' => 'error', 'message' => 'File not found or is not a file.']);
}
exit;
} elseif ($action === 'set_perm') {
$itemPath = $currentPath . DS . $_POST['item_name'];
$permissions = octdec($_POST['permissions']);
if (file_exists($itemPath)) {
if (chmod($itemPath, $permissions)) {
echo json_encode(['status' => 'success', 'message' => 'Permissions set successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to set permissions.']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Item not found.']);
}
exit;
}
}
}
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Simple File Manager <title>Simple File Manager</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 15px; background-color: #f4f7f6; color: #333; overflow-x: hidden; }
.container { max-width: 95%; margin: auto; background-color: #fff; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); padding: 20px; }
h1 { color: #5c636a; text-align: center; margin-bottom: 25px; }
.path-nav { background-color: #e9ecef; padding: 10px 15px; border-radius: 5px; margin-bottom: 20px; overflow-x: auto; white-space: nowrap; }
.path-nav a { text-decoration: none; color: #5c636a; margin-right: 5px; }
.path-nav span { color: #6c757d; }
.actions { display: flex; justify-content: space-around; gap: 5px; margin-bottom: 20px; padding: 0 10px; }
.actions button {
background-color: #007bff;
color: white; border: none; border-radius: 50%;
width: 45px; height: 45px; display: flex; align-items: center; justify-content: center;
font-size: 1.5em; cursor: pointer; flex-shrink: 0;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.actions button:hover { opacity: 0.9; }
.actions input[type="file"] { display: none; }
.file-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid #dee2e6;
position: relative;
cursor: pointer;
}
.file-item:last-child { border-bottom: none; }
.file-item:hover { background-color: #f1f1f1; }
.file-icon {
font-size: 1.5em;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 10px;
flex-shrink: 0;
color: #007bff;
}
.item-info { flex-grow: 1; min-width: 0; }
.item-name { font-weight: bold; color: #333; word-wrap: break-word; overflow-wrap: break-word; }
.item-meta { font-size: 0.8em; color: #6c757d; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item-actions-btn {
font-size: 1.2em;
cursor: pointer;
padding: 5px;
border-radius: 50%;
transition: background-color 0.2s;
flex-shrink: 0;
color: #6c757d;
}
.item-actions-btn:hover {
background-color: #e9ecef;
}
.modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); justify-content: center; align-items: center; }
.modal-content { background-color: #fff; margin: auto; padding: 25px; border-radius: 8px; width: 90%; max-width: 500px; box-shadow: 0 5px 20px rgba(0,0,0,0.2); position: relative; }
.modal-content h2 { margin-top: 0; color: #5c636a; }
.modal-content input[type="text"] {
width: calc(100% - 70px); /* Adjust width to make space for button */
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1em;
box-sizing: border-box;
display: inline-block; /* Align input with button */
vertical-align: middle; /* Align input with button */
}
.modal-content textarea {
width: calc(100% - 20px); padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; font-size: 1em;
box-sizing: border-box;
}
.modal-content button {
background-color: #007bff;
color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;
width: 45px; height: 45px; display: inline-flex; align-items: center; justify-content: center;
font-size: 1.5em; border-radius: 50%;
vertical-align: middle; /* Align button with input */
}
.modal-content button:hover { opacity: 0.9; }
.close-button { position: absolute; right: 15px; top: 10px; font-size: 28px; font-weight: bold; color: #6c757d; cursor: pointer; }
.close-button:hover, .close-button:focus { color: #333; text-decoration: none; }
.context-menu {
display: none;
position: absolute;
background-color: #fff;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
border-radius: 5px;
z-index: 1001;
min-width: 150px;
right: 0;
top: 30px;
}
.context-menu button {
display: block;
width: 100%;
padding: 10px 15px;
text-align: left;
border: none;
background: none;
cursor: pointer;
font-size: 0.9em;
color: #333;
border-radius: 0;
margin: 0;
}
.context-menu button:hover {
background-color: #f1f1f1;
color: #5c636a;
}
#viewFileContent {
white-space: pre-wrap;
word-wrap: break-word;
max-height: 70vh;
overflow-y: auto;
background-color: #f8f8f8;
border: 1px solid #ddd;
padding: 10px;
border-radius: 4px;
margin-bottom: 15px;
}
#viewFileActions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 15px;
}
#viewFileActions button {
background-color: #007bff;
color: white;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2em;
cursor: pointer;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
padding: 0;
}
#viewFileActions button:hover { opacity: 0.9; }
#editFileModal .modal-content {
height: 90vh;
display: flex;
flex-direction: column;
}
#editFileContent {
flex-grow: 1;
resize: none;
height: auto;
margin-bottom: 10px;
}
#editFileModal .modal-buttons {
display: flex;
justify-content: flex-end;
gap: 10px;
width: 100%;
}
</style>
<div class="container">
File Manager
<div class="path-nav">
$currentRelativePath = str_replace(BASE_DIR, '', $currentPath);
$pathParts = explode(DS, trim($currentRelativePath, DS));
$pathLink = '';
echo '<a href="?path=" title="Home">🏠</a>';
foreach ($pathParts as $part) {
if (empty($part)) continue;
$pathLink .= DS . $part;
echo ' / <a href="?path=' . urlencode(ltrim($pathLink, DS)) . '">' . htmlspecialchars($part) . '</a>';
}
</div>
<div class="actions">
<button onclick="document.getElementById('fileInput').click()" title="Upload Files">⬆️</button>
<button onclick="showUploadUrlModal()" title="Upload from URL">🌐</button>
<button onclick="showCreateFileModal()" title="Create New File">📄</button>
<button onclick="showCreateFolderModal()" title="Create New Folder">📁</button>
</div>
<div id="fileListContainer">
$items = scandir($currentPath);
$folders = [];
$files = [];
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$itemPath = $currentPath . DS . $item;
$relativePath = str_replace(BASE_DIR . DS, '', $itemPath);
$itemInfo = [
'name' => htmlspecialchars($item),
'full_path' => htmlspecialchars($relativePath),
'modified' => date('Y-m-d H:i:s', filemtime($itemPath)),
'perms' => substr(sprintf('%o', fileperms($itemPath)), -4)
];
if (is_dir($itemPath)) {
$folders[] = $itemInfo;
} else {
$itemInfo['size'] = formatSizeUnits(filesize($itemPath));
$files[] = $itemInfo;
}
}
usort($folders, function($a, $b) { return strnatcmp($a['name'], $b['name']); });
usort($files, function($a, $b) { return strnatcmp($a['name'], $b['name']); });
if ($currentPath !== BASE_DIR) {
$parentPath = dirname($currentPath);
$parentRelativePath = str_replace(BASE_DIR . DS, '', $parentPath);
echo '<div class="file-item" onclick="window.location.href=\'?path=' . urlencode($parentRelativePath) . '\'">';
echo '<div class="file-icon">📁</div>';
echo '<div class="item-info">';
echo '<span class="item-name">..</span>';
echo '<span class="item-meta">Parent Directory</span>';
echo '</div>';
echo '<div class="item-actions-btn"></div>';
echo '</div>';
}
foreach ($folders as $folder) {
echo '<div class="file-item" onclick="window.location.href=\'?path=' . urlencode($folder['full_path']) . '\'">';
echo '<div class="file-icon">📁</div>';
echo '<div class="item-info">';
echo '<span class="item-name">' . $folder['name'] . '</span>';
echo '<span class="item-meta">' . $folder['modified'] . ' • ' . $folder['perms'] . '</span>';
echo '</div>';
echo '<div class="item-actions-btn" onclick="event.stopPropagation(); showContextMenu(this, \'' . $folder['name'] . '\', \'folder\', \'' . $folder['perms'] . '\')">⋮</div>';
echo '</div>';
}
foreach ($files as $file) {
echo '<div class="file-item" onclick="viewFile(\'' . $file['name'] . '\')">';
echo '<div class="file-icon">📄</div>';
echo '<div class="item-info">';
echo '<span class="item-name">' . $file['name'] . '</span>';
echo '<span class="item-meta">' . $file['size'] . ' • ' . $file['modified'] . ' • ' . $file['perms'] . '</span>';
echo '</div>';
echo '<div class="item-actions-btn" onclick="event.stopPropagation(); showContextMenu(this, \'' . $file['name'] . '\', \'file\', \'' . $file['perms'] . '\')">⋮</div>';
echo '</div>';
}
</div>
</div>
<div id="uploadUrlModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('uploadUrlModal')">✕</span>
Upload from URL
<button onclick="uploadFromUrl()" title="Upload">➤</button>
</div>
</div>
<div id="createFileModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('createFileModal')">✕</span>
Create New File
<button onclick="createFile()" title="Create">➤</button>
</div>
</div>
<div id="createFolderModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('createFolderModal')">✕</span>
Create New Folder
<button onclick="createFolder()" title="Create">➤</button>
</div>
</div>
<div id="editFileModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('editFileModal')">✕</span>
Edit File: <span id="editFileName"></span>
<textarea id="editFileContent"></textarea>
<div class="modal-buttons">
<button onclick="saveFileContent()" title="Save">➤</button>
</div>
</div>
</div>
<div id="viewFileModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('viewFileModal')">✕</span>
View File: <span id="viewFileName"></span>
<pre id="viewFileContent"></pre>
<div id="viewFileActions">
<button onclick="editFile(currentItemName); closeModal('viewFileModal');" title="Edit File">✏️</button>
<button onclick="renameItem(currentItemName); closeModal('viewFileModal');" title="Rename Item">🔄</button>
<button onclick="deleteItem(currentItemName); closeModal('viewFileModal');" title="Delete Item">🗑️</button>
<button onclick="showPermissionsModal(currentItemName, currentItemPerms); closeModal('viewFileModal');" title="Set Permissions">🔑</button>
</div>
</div>
</div>
<div id="permissionsModal" class="modal">
<div class="modal-content">
<span class="close-button" onclick="closeModal('permissionsModal')">✕</span>
Set Permissions for: <span id="permsItemName"></span>
<button onclick="setPermissions()" title="Apply">➤</button>
</div>
</div>
<div id="contextMenu" class="context-menu"></div>
<script>
let currentItemName = '';
let currentItemType = '';
let currentItemPerms = '';
function showModal(id) {
document.getElementById(id).style.display = 'flex';
}
function closeModal(id) {
document.getElementById(id).style.display = 'none';
document.getElementById('contextMenu').style.display = 'none';
}
function showContextMenu(element, name, type, perms) {
currentItemName = name;
currentItemType = type;
currentItemPerms = perms;
const menu = document.getElementById('contextMenu');
menu.innerHTML = '';
const renameBtn = document.createElement('button');
renameBtn.innerText = 'Rename';
renameBtn.onclick = () => { renameItem(currentItemName); closeModal('contextMenu'); };
menu.appendChild(renameBtn);
const deleteBtn = document.createElement('button');
deleteBtn.innerText = 'Delete';
deleteBtn.onclick = () => { deleteItem(currentItemName); closeModal('contextMenu'); };
menu.appendChild(deleteBtn);
if (type === 'file') {
const viewBtn = document.createElement('button');
viewBtn.innerText = 'View';
viewBtn.onclick = () => { viewFile(currentItemName); closeModal('contextMenu'); };
menu.appendChild(viewBtn);
const editBtn = document.createElement('button');
editBtn.innerText = 'Edit';
editBtn.onclick = () => { editFile(currentItemName); closeModal('contextMenu'); };
menu.appendChild(editBtn);
const downloadBtn = document.createElement('button');
downloadBtn.innerText = 'Download';
downloadBtn.onclick = () => {
const downloadLink = document.createElement('a');
downloadLink.href = currentItemName;
downloadLink.download = currentItemName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
closeModal('contextMenu');
};
menu.appendChild(downloadBtn);
}
const permsBtn = document.createElement('button');
permsBtn.innerText = 'Set Permissions';
permsBtn.onclick = () => { showPermissionsModal(currentItemName, currentItemPerms); closeModal('contextMenu'); };
menu.appendChild(permsBtn);
menu.style.display = 'block';
menu.style.right = 'auto';
menu.style.left = 'auto';
const rect = element.getBoundingClientRect();
let desiredLeft = rect.right + window.scrollX - menu.offsetWidth;
const viewportWidth = window.innerWidth;
if (desiredLeft < 0) {
desiredLeft = 5;
} else if (desiredLeft + menu.offsetWidth > viewportWidth) {
desiredLeft = viewportWidth - menu.offsetWidth - 5;
}
menu.style.left = `${desiredLeft}px`;
menu.style.top = `${rect.bottom + window.scrollY}px`;
}
document.addEventListener('click', function(event) {
const menu = document.getElementById('contextMenu');
const target = event.target;
if (menu.style.display === 'block' && !menu.contains(target) && !target.classList.contains('item-actions-btn')) {
menu.style.display = 'none';
}
});
function uploadFile() {
const fileInput = document.getElementById('fileInput');
if (fileInput.files.length === 0) {
alert('No files selected.');
return;
}
const formData = new FormData();
formData.append('action', 'upload');
for (let i = 0; i < fileInput.files.length; i++) {
formData.append('files[]', fileInput.files[i]);
}
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message + (data.errors ? '\nErrors: ' + data.errors.join(', ') : ''));
if (data.status === 'success') {
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during upload.');
});
}
function showUploadUrlModal() {
showModal('uploadUrlModal');
}
function uploadFromUrl() {
const urlInput = document.getElementById('uploadUrlInput');
const url = urlInput.value.trim();
if (!url) {
alert('Please enter a URL.');
return;
}
const formData = new FormData();
formData.append('action', 'upload');
formData.append('url', url);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
closeModal('uploadUrlModal');
urlInput.value = '';
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during URL upload.');
});
}
function deleteItem(item) {
if (confirm(`Are you sure you want to delete "${item}"?`)) {
const formData = new FormData();
formData.append('action', 'delete');
formData.append('item', item);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during deletion.');
});
}
}
function renameItem(oldName) {
const newName = prompt(`Rename "${oldName}" to:`, oldName);
if (newName && newName !== oldName) {
const formData = new FormData();
formData.append('action', 'rename');
formData.append('old_name', oldName);
formData.append('new_name', newName);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during rename.');
});
}
}
function showCreateFileModal() {
showModal('createFileModal');
}
function createFile() {
const fileNameInput = document.getElementById('newFileNameInput');
const fileName = fileNameInput.value.trim();
if (!fileName) {
alert('Please enter a file name.');
return;
}
const formData = new FormData();
formData.append('action', 'create_file');
formData.append('name', fileName);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
closeModal('createFileModal');
fileNameInput.value = '';
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during file creation.');
});
}
function showCreateFolderModal() {
showModal('createFolderModal');
}
function createFolder() {
const folderNameInput = document.getElementById('newFolderNameInput');
const folderName = folderNameInput.value.trim();
if (!folderName) {
alert('Please enter a folder name.');
return;
}
const formData = new FormData();
formData.append('action', 'create_folder');
formData.append('name', folderName);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
closeModal('createFolderModal');
folderNameInput.value = '';
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during folder creation.');
});
}
function viewFile(fileName) {
currentItemName = fileName;
document.getElementById('viewFileName').innerText = fileName;
const formData = new FormData();
formData.append('action', 'get_file_content');
formData.append('file_name', fileName);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
document.getElementById('viewFileContent').innerText = data.content;
showModal('viewFileModal');
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while fetching file content.');
});
}
function editFile(fileName) {
document.getElementById('editFileName').innerText = fileName;
const formData = new FormData();
formData.append('action', 'get_file_content');
formData.append('file_name', fileName);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
document.getElementById('editFileContent').value = data.content;
showModal('editFileModal');
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while fetching file content.');
});
}
function saveFileContent() {
const content = document.getElementById('editFileContent').value;
const formData = new FormData();
formData.append('action', 'edit_file');
formData.append('file_name', currentItemName);
formData.append('content', content);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
closeModal('editFileModal');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while saving file content.');
});
}
function showPermissionsModal(itemName, currentPerms) {
document.getElementById('permsItemName').innerText = itemName;
document.getElementById('permsInput').value = currentPerms;
showModal('permissionsModal');
}
function setPermissions() {
const permissions = document.getElementById('permsInput').value.trim();
if (!permissions.match(/^[0-7]{3,4}$/)) {
alert('Invalid permissions format. Use octal (e.g., 0755).');
return;
}
const formData = new FormData();
formData.append('action', 'set_perm');
formData.append('item_name', currentItemName);
formData.append('permissions', permissions);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.message);
if (data.status === 'success') {
closeModal('permissionsModal');
location.reload();
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while setting permissions.');
});
}
</script>